diff --git "a/assets/index-DTY4d2sy.js" "b/assets/index-DTY4d2sy.js" new file mode 100644--- /dev/null +++ "b/assets/index-DTY4d2sy.js" @@ -0,0 +1,1489 @@ +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))i(o);new MutationObserver(o=>{for(const r of o)if(r.type==="childList")for(const s of r.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&i(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const r={};return o.integrity&&(r.integrity=o.integrity),o.referrerPolicy&&(r.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?r.credentials="include":o.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(o){if(o.ep)return;o.ep=!0;const r=n(o);fetch(o.href,r)}})();const Ck="modulepreload",yk=function(e){return"/"+e},dp={},Rl=function(t,n,i){let o=Promise.resolve();if(n&&n.length>0){let s=function(l){return Promise.all(l.map(u=>Promise.resolve(u).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),c=(a==null?void 0:a.nonce)||(a==null?void 0:a.getAttribute("nonce"));o=s(n.map(l=>{if(l=yk(l),l in dp)return;dp[l]=!0;const u=l.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${h}`))return;const d=document.createElement("link");if(d.rel=u?"stylesheet":Ck,u||(d.as="script"),d.crossOrigin="",d.href=l,c&&d.setAttribute("nonce",c),document.head.appendChild(d),u)return new Promise((f,p)=>{d.addEventListener("load",f),d.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${l}`)))})}))}function r(s){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=s,window.dispatchEvent(a),!a.defaultPrevented)throw s}return o.then(s=>{for(const a of s||[])a.status==="rejected"&&r(a.reason);return t().catch(r)})};let Ld=null,bu=null;async function Mf(){return bu||(bu=Rl(()=>import("./egm96-universal.esm-D6y_VLZc.js"),[]).then(e=>{Ld=e})),bu}function Hc(e,t){if(!Ld)throw new Error("geoid.js: geoidHeight() called before ensureGeoidReady() resolved — await ensureGeoidReady() first.");return Ld.meanSeaLevel(e,t)}function vk(e,t,n){return e+Hc(t,n)}function $C(e,t){return!Number.isFinite(e)||!Number.isFinite(t)?e:e-t}const wf=Object.freeze(Object.defineProperty({__proto__:null,ellipsoidalToMslDisplayM:$C,ensureGeoidReady:Mf,geoidHeight:Hc,orthometricToEllipsoidal:vk},Symbol.toStringTag,{value:"Module"}));function GC({source:e,signal:t}){if(typeof(e==null?void 0:e.getHeights)!="function")throw new TypeError("Terrain heights require a source");t==null||t.throwIfAborted();const n=64,i=6e4,o=new Map;function r(h,d){return`${h.toFixed(5)},${d.toFixed(5)}`}function s(h,d){const f=o.get(r(h,d));return f?f.ellipsoid:null}function a(h,d){const f=o.get(r(h,d));return f&&f.source==="reearth"?f.ellipsoid:null}async function c(h){var g;const f={results:await e.getHeights(h,{signal:t?AbortSignal.any([t,AbortSignal.timeout(3e4)]):AbortSignal.timeout(3e4)})};if(!Array.isArray(f==null?void 0:f.results))throw new Error("malformed terrain heights response (no results array)");if(f.results.length!==h.length)throw new Error(`terrain heights response length mismatch (expected ${h.length}, got ${f.results.length})`);const p=new Map;for(let _=0;_({index:m,lat:_.lat,lon:_.lon,sourceOrthometricM:_.sourceOrthometricM,key:r(_.lat,_.lon)})),f=[],p=new Set,g=Date.now();for(const _ of d){const m=o.get(_.key),b=(m==null?void 0:m.source)==="geoid-fallback"&&Number.isFinite(m.retryAt)&&g{const m=o.get(_.key);return m?{ellipsoid:m.ellipsoid,source:m.source}:{ellipsoid:null,source:"unresolved"}})}return t==null||t.addEventListener("abort",()=>o.clear(),{once:!0}),{cachedEllipsoidalGround:s,cachedRealEllipsoidalGround:a,resolveEllipsoidalGround:u}}function UC({terrain:e,signal:t}){const{cachedRealEllipsoidalGround:n,resolveEllipsoidalGround:i}=e;t==null||t.throwIfAborted();const o=1.5,r=15,s=80;function a($,x){return{lat:Number($.toFixed(3)),lon:Number(x.toFixed(3))}}function c($,x,N=o){const G=Number.isFinite($),W=Number.isFinite(x);return G&&W?Math.max($,x+N):G?$:W?x+N:null}function l($,x,N=o){if(!Number.isFinite($)||!Number.isFinite(x))return null;const G=x+N;return $=h?x:null}const f=12,p=125e-6,g=2e-4;function _($,x,N){return N&&Math.abs($-N.lat)<=5e-4+g&&Math.abs(x-N.lon)<=5e-4+g?N:a($,x)}function m($){var q,z;if(!Array.isArray($)||!$.length)return[];const x=$[0];if(!Number.isFinite(x==null?void 0:x.lat)||!Number.isFinite(x==null?void 0:x.lon))return[];const N=a(x.lat,x.lon),G=[N],W=new Set([`${N.lat},${N.lon}`]);let V=null;for(let j=$.length-1;j>=1;j--)if(Number.isFinite((q=$[j])==null?void 0:q.lat)&&Number.isFinite((z=$[j])==null?void 0:z.lon)){V=a($[j].lat,$[j].lon);break}if(!V)return G;const H=`${V.lat},${V.lon}`,B=f-1;e:for(let j=0;j<$.length-1;j++){const ne=$[j],ee=$[j+1];if(![ne==null?void 0:ne.lat,ne==null?void 0:ne.lon,ee==null?void 0:ee.lat,ee==null?void 0:ee.lon].every(Number.isFinite))continue;const re=Math.ceil(Math.max(Math.abs(ee.lat-ne.lat),Math.abs(ee.lon-ne.lon))/p);for(let se=1;se<=re;se++){if(G.length>=B)break e;const me=se/re,be=a(ne.lat+(ee.lat-ne.lat)*me,ne.lon+(ee.lon-ne.lon)*me),J=`${be.lat},${be.lon}`;W.has(J)||J===H||(W.add(J),G.push(be))}}return W.has(H)||G.push(V),G}function b($,x,N,G,W=0,V=H=>R(H.lat,H.lon)!=null){const H=[];if(!Array.isArray($)||!$.length||!(N>0))return H;const B=[...$].sort((ne,ee)=>ee.cold-ne.cold||ee.speedMps-ne.speedMps);if(Number.isFinite(W)&&W!==0)for(let ne=0;ne1){const se=(W%re+re)%re,me=B.slice(ne,ee);for(let be=0;be{for(let ee=0;ee=x-r&&$<=x+s}function k($,x,N){if(![$,x,N].every(Number.isFinite))return!1;const G=a($,x),W=n(G.lat,G.lon);return E(N,W)?(w(G.lat,G.lon,N),!0):!1}function T($,x){if(!y||!Number.isFinite($)||!Number.isFinite(x))return null;const N=a($,x),G=C.get(`${N.lat},${N.lon}`);return G??null}function I(){C.clear()}function R($,x){if(!Number.isFinite($)||!Number.isFinite(x))return null;const N=T($,x);if(N!=null)return N;const G=a($,x);return n(G.lat,G.lon)}const S=1200;function A($){return Promise.race([L($),new Promise(x=>setTimeout(x,S))])}async function L($){if(!Array.isArray($)||!$.length)return;const x=new Map;for(const N of $){if(!Number.isFinite(N==null?void 0:N.lat)||!Number.isFinite(N==null?void 0:N.lon))continue;const G=a(N.lat,N.lon),W=`${G.lat},${G.lon}`;x.has(W)||n(G.lat,G.lon)==null&&x.set(W,G)}if(x.size)try{await i([...x.values()])}catch{}}let F=!1;const P=new Map;function O($){F=!0,i([...$.values()]).catch(()=>{}).finally(()=>{if(F=!1,!(t!=null&&t.aborted)&&P.size){const x=new Map(P);P.clear(),O(x)}})}function D($){if(t!=null&&t.aborted||!Array.isArray($)||!$.length)return;const x=new Map;for(const N of $){if(!Number.isFinite(N==null?void 0:N.lat)||!Number.isFinite(N==null?void 0:N.lon))continue;const G=a(N.lat,N.lon),W=`${G.lat},${G.lon}`;x.has(W)||P.has(W)||n(G.lat,G.lon)==null&&x.set(W,G)}if(x.size){if(F){for(const[N,G]of x)P.set(N,G);return}O(x)}}return t==null||t.addEventListener("abort",()=>{C.clear(),P.clear()},{once:!0}),{GROUND_FLOOR_LIFT_M:o,MESH_FLOOR_BELOW_PRIOR_M:r,MESH_FLOOR_ABOVE_PRIOR_M:s,coarseFloorCoord:a,floorAltitudeM:c,displayFloorHeightM:l,FLOOR_CELL_DEG:u,NEIGHBOR_FLOOR_MIN_SAMPLES:h,neighborFloorM:d,CORRIDOR_MAX_CELLS:f,CORRIDOR_WALK_STEP_DEG:p,CELL_HYSTERESIS_DEG:g,stickyFloorCell:_,corridorFloorCells:m,allocateCorridorCells:b,setMeshFloorPreferred:v,meshFloorPreferred:M,reportMeshFloorCell:w,meshFloorSampleWithinPrior:E,reportValidatedMeshFloorCell:k,cachedMeshFloor:T,_clearMeshFloorCellsForTest:I,cachedGroundFloor:R,FLOOR_RESOLVE_DEADLINE_MS:S,resolveGroundFloorCellsBounded:A,resolveGroundFloorCells:L,warmGroundFloor:D}}function Mk({groundFloor:e,signal:t,eventTarget:n=null}){const{coarseFloorCoord:i,cachedMeshFloor:o,reportValidatedMeshFloorCell:r,setMeshFloorPreferred:s,meshFloorPreferred:a,cachedGroundFloor:c}=e;t==null||t.throwIfAborted();const l=40,u=15,h=25e3,d=new Cesium.Cartographic;function f(m){try{const b=m.primitives;for(let C=0;Ch||!f(m))return;let w=0;const E=new Set;for(const I of b){if(w>=l)break;if(!Number.isFinite(I==null?void 0:I.lat)||!Number.isFinite(I==null?void 0:I.lon))continue;const R=i(I.lat,I.lon),S=`${R.lat},${R.lon}`;if(E.has(S)||(E.add(S),o(R.lat,R.lon)!=null)||Number.isFinite(y)&&Number.isFinite(v)&&p(y,v,R.lat,R.lon)>u)continue;let A;try{const L=Cesium.Cartographic.fromDegrees(R.lon,R.lat,0,d);A=m.sampleHeight(L,C),w+=1}catch{continue}Number.isFinite(A)&&r(R.lat,R.lon,A)}}const _=m=>{var C;const b=(C=m==null?void 0:m.detail)==null?void 0:C.activeId;b&&s(b==="photoreal")};return n==null||n.addEventListener("gev:map-stack-changed",_),t==null||t.addEventListener("abort",()=>n==null?void 0:n.removeEventListener("gev:map-stack-changed",_),{once:!0}),{sampleMeshFloorCells:g,cachedGroundFloor:c}}const hp=50,fp=250,wk=5,Ek=2e3,Tk=3e4,kk=4,Ak=250;function Ik(e){var n;const t=(n=e==null?void 0:e.scene)==null?void 0:n.primitives;if(!t)return!1;for(let i=0;ifp*fp)return h(_);const b=d(m);return b!=null&&b-_.h>wk?h(_):_.h}function h(_){return _.h=null,_.samplePos=null,_.held=!1,null}function d(_){const m=Cesium.Cartographic.fromCartesian(_,Cesium.Ellipsoid.WGS84,l);return m?t(Cesium.Math.toDegrees(m.latitude),Cesium.Math.toDegrees(m.longitude)):null}function f(_,m,b,C){const y=Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(b,c);if(!y)return null;const v=o.get(m);if(v&&v.h!=null&&v.samplePos&&!v.held){if(Cesium.Cartesian3.distanceSquared(y,v.samplePos)<=hp*hp)return v.h;v.held=!0,v.nextRetryMs=0,v.misses=0}const M=Date.now(),w=o.get(m);if(w&&MAk&&(r=M,s=0),s>=kk))return u(w,y);const E=w?w.misses:0,k=()=>{const I=!!(w&&w.held&&w.h!=null&&w.samplePos),R={h:I?w.h:null,samplePos:I?w.samplePos:null,held:I,nextRetryMs:M+Math.min(Tk,Ek*2**E),misses:E+1};return o.set(m,R),u(R,y)};if(!Ik(_))return k();s+=1;let T;try{const I=Cesium.Cartographic.fromCartesian(b,Cesium.Ellipsoid.WGS84,a);T=_.scene.sampleHeight(I,C?C():void 0)}catch{T=void 0}return!Number.isFinite(T)||T<-150?k():(n()&&i(Cesium.Math.toDegrees(a.latitude),Cesium.Math.toDegrees(a.longitude),T),o.set(m,{h:T,samplePos:Cesium.Cartesian3.clone(y),held:!1,nextRetryMs:0,misses:0}),T)}function p(_){o.delete(_)}function g(){o.clear()}return{heightFor:f,forget:p,clear:g}}const Lk=5;function Pk({cachedGroundFloor:e,resolveGroundFloorCells:t}){function n(c,l){const u=e(c,l);return u!=null?u+Lk:0}let i=null;function o(c){const l=r(c);if(!l.length)return Promise.resolve(!1);const u=i,h=u?u.then(()=>s(l)):s(l);return i=h.then(()=>!0,()=>!1),h}function r(c){if(!Array.isArray(c))return[];const l=[];for(const u of c)!Number.isFinite(u==null?void 0:u.lat)||!Number.isFinite(u==null?void 0:u.lon)||e(u.lat,u.lon)==null&&l.push({lat:u.lat,lon:u.lon});return l}async function s(c){const l=c.filter(u=>e(u.lat,u.lon)==null);if(!l.length)return!1;try{await t(l)}catch{}return l.some(u=>e(u.lat,u.lon)!=null)}function a(){i=null}return{fireAnchorHeight:n,warmFireAnchorFloors:o,_resetFireAnchorsForTest:a}}function zC({terrainSource:e,signal:t,eventTarget:n=globalThis.window}){const i=GC({source:e,signal:t}),o=UC({terrain:i,signal:t}),r=Mk({groundFloor:o,signal:t,eventTarget:n});return Object.freeze({terrain:i,groundFloor:o,meshFloor:r,groundSnap:Object.freeze({createGroundSnap:()=>Rk({groundFloor:o})}),anchors:Pk(o),controlServices:Object.freeze({cachedGroundFloor:o.cachedGroundFloor,cachedMeshFloor:o.cachedMeshFloor,GROUND_FLOOR_LIFT_M:o.GROUND_FLOOR_LIFT_M,meshFloorPreferred:o.meshFloorPreferred,warmGroundFloor:o.warmGroundFloor,sampleMeshFloorCells:r.sampleMeshFloorCells})})}function xk(e){if(e==null||String(e).trim()==="")return null;const t=Number(e);if(Number.isFinite(t)&&t>=0)return Math.ceil(t*1e3);const n=Date.parse(String(e));return Number.isFinite(n)?Math.max(0,n-Date.now()):null}function Ef({fetchImpl:e=(...i)=>fetch(...i),signal:t,endpoints:n={}}={}){const i={boundaries:"/api/overpass",terrain:"/api/terrain/heights",regional:"/api/regional-brief",weather:"/api/weather-effects",summary:"/api/openai/hud-summary",...n};async function o(a,{signal:c,...l}={}){c=AbortSignal.any([t,c].filter(Boolean)),c.throwIfAborted();const u=await e(a,{...l,signal:c,redirect:"error"});c.throwIfAborted();let h=null;try{h=await u.json()}catch{}return c.throwIfAborted(),{ok:u.ok,status:u.status,headers:u.headers,data:h}}function r(a,c,l){if(!Number.isFinite(c)||c<-90||c>90||!Number.isFinite(l)||l<-180||l>180)throw new TypeError("Valid coordinates are required");return`${a}?${new URLSearchParams({latitude:c.toFixed(5),longitude:l.toFixed(5)})}`}function s(a,c){if(!a.ok)throw new Error(`${c} unavailable (${a.status})`);return a.data}return{boundaries:{async query(a,{signal:c}={}){var d,f,p,g;const l=await o(i.boundaries,{method:"POST",signal:c,headers:{"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(a)}`}),u=(f=(d=l.headers)==null?void 0:d.get)==null?void 0:f.call(d,"Retry-After");if(l.status===429||l.status===503&&u!=null)return{rateLimited:!0,retryAfterMs:xk(u)};if(!l.ok)return null;const h=String(((p=l.data)==null?void 0:p.remark)||"").toLowerCase();return/runtime error|timed out|out of memory/.test(h)?null:Array.isArray((g=l.data)==null?void 0:g.elements)?l.data.elements:null}},terrain:{async getHeights(a,{signal:c}={}){var u;const l=a.map(({lat:h,lon:d})=>`${d.toFixed(5)},${h.toFixed(5)}`).join(";");return(u=s(await o(`${i.terrain}?points=${encodeURIComponent(l)}`,{signal:c}),"Terrain heights"))==null?void 0:u.results}},regional:{async getBrief(a,c,l){return s(await o(r(i.regional,a,c),l),"Regional brief")}},weather:{async getConditions(a,c,l){return s(await o(r(i.weather,a,c),l),"Weather")}},summary:{async summarize(a,{signal:c}={}){return o(i.summary,{method:"POST",signal:c,headers:{"Content-Type":"application/json"},body:JSON.stringify(a)})}}}}const Fk=Object.freeze({trafficLayer:"traffic",flightsLayer:"flights",militaryFlightsLayer:"military",satellitesLayer:"satellites",cctvLayer:"cctv",radioLayer:"radio",bikeshareLayer:"bikeshare",transitLayer:"transit",aisLiveVesselsLayer:"ais-live-vessels",militaryAwarenessLayer:"military-awareness",militaryInstallationsLayer:"military-installations",rocketLaunchesLayer:"rocket-launches"});function Sk(e,t){if(!Array.isArray(e)||!Array.isArray(t))throw new TypeError("Layer instances and serialization metadata are required");const n=new Map;for(const o of e){if(typeof(o==null?void 0:o.id)!="string"||!o.id||n.has(o.id))throw new TypeError(`Invalid or duplicate catalog layer: ${o==null?void 0:o.id}`);n.set(o.id,o)}const i=new Set;for(const o of t){if(!n.has(o==null?void 0:o.id)||i.has(o.id))throw new TypeError(`Unmatched or duplicate catalog metadata: ${o==null?void 0:o.id}`);i.add(o.id)}if(i.size!==n.size)throw new TypeError("Catalog metadata is incomplete");return Object.freeze({layers:Object.freeze([...e]),metadata:Object.freeze(t.map(o=>Object.freeze({...o}))),get:o=>n.get(o)})}function Nk(e){if(!(e!=null&&e.get))throw new TypeError("An application layer catalog is required");return Object.fromEntries(Object.entries(Fk).map(([t,n])=>{const i=e.get(n);if(!i)throw new TypeError(`Control layer missing from catalog: ${n}`);return[t,i]}))}const Dk=new Set(["enabled-only","enabled+options","enabled+mirrored-options"]),Qr=2,mp=1e3,Ok=/^[0-9a-z~_-]{1,16}$/,Bk=64,Vk=512,rl="gev:layer-state:v2",zn=Object.freeze({share:"share-restore",local:"local-restore"}),Tf=Object.freeze({all:"a",news:"n",talk:"t",weather:"w","public-safety":"p","aviation-marine":"v","traffic-transit":"x",music:"m",other:"o"}),pp=Object.freeze(Object.fromEntries(Object.entries(Tf).map(([e,t])=>[t,e])));function Hk(e){return typeof e=="boolean"?e:null}function $k(e,t){return e.includes(t)?t:null}function kf(e){const t=String(e||"").trim().toLowerCase();return Object.hasOwn(Tf,t)||/^genre:[a-z0-9][a-z0-9 &-]{0,31}$/.test(t)?t:null}function Gk(e){return Tf[e]||`g-${e.slice(6)}`}function Uk(e){return Object.hasOwn(pp,e)?pp[e]:/^g-[a-z0-9][a-z0-9 &-]{0,31}$/.test(e)?`genre:${e.slice(2)}`:null}function gp(e){const t=Number(e);return Number.isFinite(t)?Math.round(Math.max(0,Math.min(1,t))*100)/100:null}function Cu(e,t,n,{absentValue:i=n}={}){return Object.freeze({key:e,token:t,defaultValue:n,absentValue:i,normalize:Hk,encode:o=>o?"1":"0",decode:o=>o==="1"?!0:o==="0"?!1:null})}function jC(e){return Object.hasOwn(e,"absentValue")?e.absentValue:e.defaultValue}function _p(e,t,n=null){const i=o=>{if(o==null)return null;const r=typeof o=="number"&&Number.isFinite(o)?String(o):typeof o=="string"?o:null;if(r===null)return null;const s=r.trim().toLowerCase();return Ok.test(s)?s:null};return Object.freeze({key:e,token:t,defaultValue:n,normalize:i,encode:o=>String(o),decode:i})}function yu(e,t,n,i,o){const r=Object.fromEntries(Object.entries(o).map(([s,a])=>[a,s]));return Object.freeze({key:e,token:t,defaultValue:n,normalize:s=>$k(i,s),encode:s=>o[s],decode:s=>r[s]||null})}function zk(e,t,n){return Object.freeze({key:e,token:t,defaultValue:n,normalize:i=>{if(typeof i=="number"&&Number.isInteger(i)&&i>0)return i;const o=typeof i=="string"?i.trim():"",r=Number(o);return!o||!Number.isInteger(r)||r<=0?null:r},encode:i=>String(Math.trunc(i)),decode:i=>{const o=Number(i);return!Number.isInteger(o)||o<=0?null:o}})}const jk=Object.freeze({flights:Object.freeze([Cu("models3d","e",!0,{absentValue:!1}),yu("models3dMode","m","proximity",["proximity","all"],{proximity:"p",all:"a"}),_p("selectedFlightsTrackingId","t",null),_p("selectedMilitaryTrackingId","u",null)]),satellites:Object.freeze([yu("catalog","c","core",["core","dense"],{core:"c",dense:"d"}),zk("selectedSatTrackingId","t",null)]),cctv:Object.freeze([yu("coverageMode","c","on",["off","on","viewshed"],{off:"0",on:"1",viewshed:"v"}),Cu("showProjection","p",!0),Cu("autoHop","a",!1)]),radio:Object.freeze([Object.freeze({key:"filter",token:"f",defaultValue:"all",normalize:kf,encode:Gk,decode:Uk}),Object.freeze({key:"volume",token:"v",defaultValue:.8,normalize:gp,encode:e=>String(Math.round(e*100)),decode:e=>/^\d{1,3}$/.test(e)?gp(Number(e)/100):null})])}),bp=Object.freeze({flights:"selectedFlightsTrackingId",military:"selectedMilitaryTrackingId",satellites:"selectedSatTrackingId"}),ir=Object.freeze({flights:Object.freeze({optionOwner:"flights",optionKey:"selectedFlightsTrackingId",expiryWindowMs:9e4,label:"flight"}),military:Object.freeze({optionOwner:"flights",optionKey:"selectedMilitaryTrackingId",expiryWindowMs:45e3,label:"military flight"}),satellites:Object.freeze({optionOwner:"satellites",optionKey:"selectedSatTrackingId",expiryWindowMs:3e5,label:"satellite"})}),pn=Object.freeze([Object.freeze({id:"ais-live-vessels",token:"a",disposition:"enabled-only"}),Object.freeze({id:"alpr-cameras",token:"p",disposition:"enabled-only"}),Object.freeze({id:"bikeshare",token:"b",disposition:"enabled-only"}),Object.freeze({id:"cctv",token:"c",disposition:"enabled+options",optionOwner:"cctv"}),Object.freeze({id:"directions",token:"n",disposition:"enabled-only"}),Object.freeze({id:"earthquakes",token:"e",disposition:"enabled-only"}),Object.freeze({id:"flights",token:"f",disposition:"enabled+options",optionOwner:"flights"}),Object.freeze({id:"local-dams",token:"q",disposition:"enabled-only"}),Object.freeze({id:"local-datacenters",token:"d",disposition:"enabled-only"}),Object.freeze({id:"local-firms",token:"w",disposition:"enabled-only"}),Object.freeze({id:"military",token:"m",disposition:"enabled+mirrored-options",optionOwner:"flights"}),Object.freeze({id:"military-awareness",token:"g",disposition:"enabled-only"}),Object.freeze({id:"military-installations",token:"i",disposition:"enabled-only"}),Object.freeze({id:"radio",token:"r",disposition:"enabled+options",optionOwner:"radio"}),Object.freeze({id:"rocket-launches",token:"x",disposition:"enabled-only"}),Object.freeze({id:"satellites",token:"s",disposition:"enabled+options",optionOwner:"satellites"}),Object.freeze({id:"telegeography-submarine-cables",token:"u",disposition:"enabled-only"}),Object.freeze({id:"traffic",token:"t",disposition:"enabled-only"}),Object.freeze({id:"transit",token:"j",disposition:"enabled-only"})]),qC=Object.freeze(pn.map(e=>e.id)),Af=new Map(pn.map(e=>[e.id,e])),vu=new Map(pn.map(e=>[e.token,e])),$c=Object.freeze([...new Set(pn.map(e=>e.optionOwner).filter(Boolean))]);function Lo(e){return jk[e]||[]}function qk(e){return Object.fromEntries(Lo(e).map(t=>[t.key,t.defaultValue]))}function Wk(e,t={}){const n=t&&typeof t=="object"?t:{},i={};for(const o of Lo(e)){const r=Object.hasOwn(n,o.key)?o.normalize(n[o.key]):null;i[o.key]=r===null?o.defaultValue:r}return i}function Mo(e){return e==="user"||e==="voice"||e==="tool"}function WC(e=pn){if(!Array.isArray(e)||e.length===0)throw new Error("Layer-state registry must be a non-empty array");const t=new Set,n=new Set;for(const i of e){if(!i||typeof i.id!="string"||!i.id)throw new Error("Layer-state entry missing id");if(!/^[a-z0-9-]+$/.test(i.id))throw new Error(`Invalid layer-state id: ${i.id}`);if(t.has(i.id))throw new Error(`Duplicate layer-state id: ${i.id}`);if(t.add(i.id),!/^[a-z0-9]$/.test(i.token||""))throw new Error(`Invalid layer-state token: ${i.id}`);if(n.has(i.token))throw new Error(`Duplicate layer-state token: ${i.token}`);if(n.add(i.token),!Dk.has(i.disposition))throw new Error(`Invalid layer-state disposition: ${i.id}`);if(i.disposition!=="enabled-only"){if(!i.optionOwner||Lo(i.optionOwner).length===0)throw new Error(`Layer-state option owner missing: ${i.id}`)}else if(i.optionOwner)throw new Error(`Enabled-only layer cannot own options: ${i.id}`)}return!0}WC();function Pd(){return{version:Qr,enabledLayerIds:[],options:Object.fromEntries($c.map(e=>[e,qk(e)]))}}function Pn(e){const t=e&&typeof e=="object"?e:{},n=new Set(Array.isArray(t.enabledLayerIds)?t.enabledLayerIds.map(String):[]),i=qC.filter(a=>n.has(a)),o=new Set(i),r=Object.fromEntries($c.map(a=>{var c;return[a,Wk(a,(c=t.options)==null?void 0:c[a])]}));return o.has("flights")||(r.flights.selectedFlightsTrackingId=null),o.has("military")||(r.flights.selectedMilitaryTrackingId=null),o.has("satellites")||(r.satellites.selectedSatTrackingId=null),[r.flights.selectedFlightsTrackingId,r.flights.selectedMilitaryTrackingId,r.satellites.selectedSatTrackingId].filter(a=>a!==null).length>1&&(r.flights.selectedFlightsTrackingId=null,r.flights.selectedMilitaryTrackingId=null,r.satellites.selectedSatTrackingId=null),{version:Qr,enabledLayerIds:i,options:r}}function KC(e){const t=Pn(e);return{...t,enabledLayerIds:[...t.enabledLayerIds],options:Object.fromEntries(Object.entries(t.options).map(([n,i])=>[n,{...i}]))}}function YC(e,t){const n=Pn(t),i=new Set(n.enabledLayerIds);e.set("l",pn.filter(r=>i.has(r.id)).map(r=>r.token).join("."));const o=[];for(const r of $c){const s=Af.get(r),a=n.options[r];for(const c of Lo(r))a[c.key]!==jC(c)&&o.push(`${s.token}.${c.token}.${c.encode(a[c.key])}`)}return o.length?e.set("lo",o.join("_")):e.delete("lo"),e}function XC(e){if(e.get("v")!==String(Qr)||!e.has("l"))return null;const t=String(e.get("l")||""),n=String(e.get("lo")||"");if(t.length>Bk||n.length>Vk)return null;const i=t.split(".").filter(Boolean);if(i.some(s=>!vu.has(s)))return null;const o=i.map(s=>vu.get(s).id),r={};for(const s of n.split("_")){if(!s)continue;const[a,c,l,...u]=s.split(".");if(u.length)continue;const h=vu.get(a),d=(h==null?void 0:h.optionOwner)||null;if(!d)continue;const f=Lo(d).find(g=>g.token===c);if(!f)continue;const p=f.decode(l);p!==null&&(r[d]||(r[d]={}),r[d][f.key]=p)}for(const s of $c)for(const a of Lo(s))r[s]&&Object.hasOwn(r[s],a.key)||(r[s]||(r[s]={}),r[s][a.key]=jC(a));return Pn({enabledLayerIds:o,options:r})}function QC(e){const t=Pn(e);return JSON.stringify({v:Qr,l:t.enabledLayerIds,o:t.options})}function ZC(e){if(typeof e!="string"||!e)return null;try{const t=JSON.parse(e);return(t==null?void 0:t.v)!==Qr||!Array.isArray(t.l)?null:Pn({enabledLayerIds:t.l,options:t.o})}catch{return null}}function JC(e,t){const n=Af.get(t);return n!=null&&n.optionOwner?{...Pn(e).options[n.optionOwner]}:null}function Kk(){try{return globalThis.localStorage||null}catch{return null}}function Cp(e,t){var i;const n=(i=e.getLayerLifecycleState)==null?void 0:i.call(e,t);return{settledEnabled:!!(n!=null&&n.enabled),lifecycleState:(n==null?void 0:n.lifecycleState)||"missing",lifecycleUncertain:!!(n!=null&&n.uncertain)}}class ey{constructor(t,n,{storage:i=Kk(),restoreGate:o=null,onDurableStateChange:r=null,onTrackingRestoreStatus:s=null,now:a=()=>Date.now(),setTimer:c=(u,h)=>setTimeout(u,h),clearTimer:l=u=>clearTimeout(u)}={}){if(!(t!=null&&t.registrationsFinalized))throw new Error("Layer state requires finalized data-layer registrations");this.dataManager=t,this.shareLinkManager=n||null,this.storage=i,this.restoreGate=o,this.onDurableStateChange=r,this.onTrackingRestoreStatus=s,this.now=a,this.setTimer=c,this.clearTimer=l,this._durableState=Pd(),this._source="defaults",this._destroyed=!1,this._restoreControllers=new Map,this._shareCreatedAtMs=null,this._trackingRestoreController=null,this._trackingRestoreGeneration=0,this._pendingTrackingTimer=null,this._pendingTrackingContext=null,this._unsubscribe=this.dataManager.subscribe(u=>this._handleManagerChange(u)),this._unsubscribeVisibilityRequests=this.dataManager.subscribeVisibilityRequests(u=>this._handleVisibilityRequest(u)),this.restorePromise=Promise.resolve([]),this.lastRestoreResults=[]}start({shareLayerState:t=null,allowLocalState:n=!0,shareCreatedAtMs:i=null}={}){var r,s,a,c,l,u;if(this._destroyed)throw new Error("Layer-state coordinator is destroyed");let o=t?Pn(t):null;if(o)this._source="share",this._shareCreatedAtMs=Number.isFinite(i)?i:null;else if(n){let h=null;try{h=ZC((s=(r=this.storage)==null?void 0:r.getItem)==null?void 0:s.call(r,rl))}catch{}h&&(o=h,this._source="local")}else this._source="legacy-share";return this._durableState=o||Pd(),(c=(a=this.shareLinkManager)==null?void 0:a.setLayerStateProvider)==null||c.call(a,()=>this.getDurableState()),(u=(l=this.shareLinkManager)==null?void 0:l.onLayerStateChange)==null||u.call(l),this._notifyDurableState(),o?(this.restorePromise=this._restoreSelectedState(this._source==="share"?zn.share:zn.local),this.restorePromise):this.restorePromise}get source(){return this._source}getDurableState(){return KC(this._durableState)}_notifyDurableState(){var t;try{(t=this.onDurableStateChange)==null||t.call(this,this.getDurableState())}catch{}}_handleVisibilityRequest(t){var n;Mo(t==null?void 0:t.origin)&&((n=this._restoreControllers.get(t.layerId))==null||n.abort("superseded-by-explicit-visibility"),ir[t.layerId]&&this._revokePendingTrackingWatch("superseded-by-explicit-visibility"))}cancelPendingRestores(t="superseded-by-explicit-navigation"){for(const n of this._restoreControllers.values())n.abort(t);this._revokePendingTrackingWatch(t)}cancelPendingShareTracking(t="superseded-by-explicit-navigation",{clearSelection:n=!1}={}){if(this._revokePendingTrackingWatch(t),!n)return!1;const i=this._selectedShareTrackingTarget();return i?this._passivelyClearTrackingSelection(i):!1}_handleManagerChange(t){var c;if(!t||this._destroyed)return;if(t.type==="params-requested"){Mo(t.origin)&&ir[t.layerId]&&this._revokePendingTrackingWatch("superseded-by-explicit-params");return}if(t.type==="visibility"&&t.enabled===!1&&ir[t.layerId]&&this._revokePendingTrackingWatch("owner-layer-disabled"),!Mo(t.origin))return;if(t.type==="visibility"){(c=this._restoreControllers.get(t.layerId))==null||c.abort("superseded-by-explicit-visibility"),ir[t.layerId]&&this._revokePendingTrackingWatch("superseded-by-explicit-visibility");const l=new Set(this._durableState.enabledLayerIds);t.enabled?l.add(t.layerId):l.delete(t.layerId),this._commitExplicit({...this._durableState,enabledLayerIds:[...l]});return}if(t.type!=="params")return;const n=Af.get(t.layerId);if(!(n!=null&&n.optionOwner))return;const i=n.optionOwner,o={...this._durableState.options[i]},r=t.requestedParams||{},s=bp[t.layerId]||null;let a=!1;for(const l of Lo(i)){const u=Object.hasOwn(r,l.key),h=!u&&l.key===s;if(!u&&!h)continue;const d=l.normalize(t.params[l.key]);if(d===null){if(h){o[l.key]=null,a=!0;continue}if(l.defaultValue!==null||t.params[l.key]!==null)continue}o[l.key]=d,a=!0}a&&this._commitExplicit({...this._durableState,options:{...this._durableState.options,[i]:o}})}_commitExplicit(t){var i,o,r,s,a,c;this._durableState=Pn(t);const n=QC(this._durableState);try{((o=(i=this.storage)==null?void 0:i.getItem)==null?void 0:o.call(i,rl))!==n&&((s=(r=this.storage)==null?void 0:r.setItem)==null||s.call(r,rl,n))}catch{}(c=(a=this.shareLinkManager)==null?void 0:a.onLayerStateChange)==null||c.call(a),this._notifyDurableState()}async _waitForRestoreGate(){this.restoreGate&&await(typeof this.restoreGate=="function"?this.restoreGate():this.restoreGate)}async _restoreSelectedState(t){for(const n of pn)this._restoreControllers.set(n.id,new AbortController);try{await this._waitForRestoreGate();const n=new Set(this._durableState.enabledLayerIds),i=await Promise.allSettled(pn.map(async o=>{const r=this._restoreControllers.get(o.id),s=n.has(o.id),a=JC(this._durableState,o.id);if(t===zn.share&&a)for(const l of Object.values(bp))delete a[l];if(this._destroyed||r!=null&&r.signal.aborted)return{layerId:o.id,targetEnabled:s,origin:t,phase:"reserved",...Cp(this.dataManager,o.id),appliedOptions:{},cancellationReason:this._destroyed?"destroyed":"superseded",errorClass:"cancelled",persistenceWrite:!1,succeeded:!1};const c=!a||Object.keys(a).length===0||this.dataManager.setLayerParams(o.id,a,{origin:t});return this.dataManager.restoreLayerState(o.id,{enabled:s,params:null},{origin:t,signal:r.signal}).then(l=>({...l,appliedOptions:c&&a?a:{},errorClass:c?l.errorClass:"ParamsRejected",succeeded:c&&l.succeeded}))}));return this.lastRestoreResults=i.map((o,r)=>{var a,c;if(o.status==="fulfilled")return o.value;const s=pn[r];return{layerId:s.id,targetEnabled:n.has(s.id),origin:t,phase:"coordinator",...Cp(this.dataManager,s.id),appliedOptions:{},cancellationReason:null,errorClass:((a=o.reason)==null?void 0:a.name)||"Error",error:String(((c=o.reason)==null?void 0:c.message)||o.reason),persistenceWrite:!1,succeeded:!1}}),this.lastRestoreResults.map(o=>({...o}))}finally{this._restoreControllers.clear(),this._notifyDurableState()}}_selectedShareTrackingTarget(){var t,n;if(this._source!=="share")return null;for(const[i,o]of Object.entries(ir)){const r=(n=(t=this._durableState.options)==null?void 0:t[o.optionOwner])==null?void 0:n[o.optionKey];if(r!=null&&r!=="")return{layerId:i,targetId:r,...o}}return null}_passivelyClearTrackingSelection(t){var o,r,s,a,c,l;const n=(r=(o=this._durableState.options)==null?void 0:o[t.optionOwner])==null?void 0:r[t.optionKey];if(String(n)!==String(t.targetId))return!1;const i={...this._durableState.options[t.optionOwner],[t.optionKey]:null};return this._durableState=Pn({...this._durableState,options:{...this._durableState.options,[t.optionOwner]:i}}),(a=(s=this.dataManager).setLayerParams)==null||a.call(s,t.layerId,{[t.optionKey]:null},{origin:zn.share}),(l=(c=this.shareLinkManager)==null?void 0:c.onLayerStateChange)==null||l.call(c),this._notifyDurableState(),!0}_classifyMissingTrackingTarget(t,n=this.now()){const i=this._shareCreatedAtMs;return Number.isFinite(i)&&n-i>t.expiryWindowMs?"expired":"unavailable"}_trackingTargetLatched(t){var o,r;const n=(r=(o=this.dataManager).getLayerParams)==null?void 0:r.call(o,t.layerId),i=n==null?void 0:n[t.optionKey];return i!=null&&String(i)===String(t.targetId)}_cancelPendingTrackingWatch(){this._pendingTrackingTimer!==null&&this.clearTimer(this._pendingTrackingTimer),this._pendingTrackingTimer=null;const t=this._pendingTrackingContext;t!=null&&t.signal&&t.abortHandler&&(t.signal.removeEventListener("abort",t.abortHandler),t.abortHandler=null)}_publishTrackingRestoreStatus(t){var n;try{(n=this.onTrackingRestoreStatus)==null||n.call(this,t)}catch{}}_revokePendingTrackingWatch(t){var i,o,r;(i=this._trackingRestoreController)==null||i.abort(t),this._trackingRestoreGeneration+=1,this._cancelPendingTrackingWatch();const n=this._pendingTrackingContext;this._pendingTrackingContext=null,n&&((r=(o=this.dataManager).cancelPendingLayerRestore)==null||r.call(o,n.selected.layerId,{origin:zn.share,reason:String(t||"cancelled")}),this._publishTrackingRestoreStatus({...n.probe,...n.selected,status:"cancelled",classification:"cancelled",reason:String(t||"cancelled"),cleared:!1}))}async _beginPendingTrackingRestore(t,n,i=null){var f,p,g,_,m,b;const o=this._trackingRestoreGeneration,r=this.now();let s=!1,a=null;try{s=await((p=(f=this.dataManager).setLayerParams)==null?void 0:p.call(f,t.layerId,{[t.optionKey]:t.targetId},{origin:zn.share}))===!0}catch(C){a=C}if(this._destroyed||o!==this._trackingRestoreGeneration||i!=null&&i.aborted)return s&&((_=(g=this.dataManager).cancelPendingLayerRestore)==null||_.call(g,t.layerId,{origin:zn.share,reason:String((i==null?void 0:i.reason)||"superseded")})),{...n,...t,status:"cancelled",classification:"cancelled",reason:String((i==null?void 0:i.reason)||"superseded"),cleared:!1};if(!s){const C={...n,...t,status:"source-unavailable",classification:"source-unavailable",reason:String((a==null?void 0:a.message)||a||"tracking restore latch rejected"),cleared:this._passivelyClearTrackingSelection(t)};return this._publishTrackingRestoreStatus(C),C}const c=this.now()+t.expiryWindowMs,l=C=>{var y;((y=this._pendingTrackingContext)==null?void 0:y.generation)===o&&(this._cancelPendingTrackingWatch(),this._pendingTrackingContext=null,this._publishTrackingRestoreStatus(C))},u=()=>{var C,y,v,M;if(this._pendingTrackingTimer=null,!(this._destroyed||o!==this._trackingRestoreGeneration)){if(((y=(C=this.dataManager).isEffectivelyEnabled)==null?void 0:y.call(C,t.layerId))===!1){this._revokePendingTrackingWatch("owner-layer-disabled");return}if(this._trackingTargetLatched(t)){l({...n,...t,status:"found",classification:"followed",cleared:!1});return}if(this.now()>=c){const w=n.status==="missing"?this._classifyMissingTrackingTarget(t,r):"source-unavailable",E=this._passivelyClearTrackingSelection(t);l({...n,...t,classification:w,cleared:E});return}this._pendingTrackingTimer=this.setTimer(u,mp),(M=(v=this._pendingTrackingTimer)==null?void 0:v.unref)==null||M.call(v)}};this._cancelPendingTrackingWatch();const h={...n,...t,status:"pending",classification:"pending",cleared:!1},d={generation:o,selected:t,probe:n,signal:i,abortHandler:null};return i&&(d.abortHandler=()=>{var C;((C=this._pendingTrackingContext)==null?void 0:C.generation)===o&&this._revokePendingTrackingWatch(i.reason||"aborted")},i.addEventListener("abort",d.abortHandler,{once:!0})),this._pendingTrackingContext=d,this._publishTrackingRestoreStatus(h),this._pendingTrackingTimer=this.setTimer(u,mp),(b=(m=this._pendingTrackingTimer)==null?void 0:m.unref)==null||b.call(m),h}async restoreShareTrackingSelection({signal:t=null}={}){const n=this._selectedShareTrackingTarget();if(!n||this._destroyed)return{status:"skipped",reason:"no-shared-target"};this._revokePendingTrackingWatch("superseded-by-newer-restore");const i=new AbortController,o=t?AbortSignal.any([t,i.signal]):i.signal;this._trackingRestoreController=i;const r=++this._trackingRestoreGeneration;let s;try{s=await this.dataManager.resolveLayerTrackingTarget(n.layerId,n.targetId,{signal:o,origin:zn.share})}catch(u){s=o.aborted?{status:"cancelled",reason:String(o.reason||"aborted")}:{status:"source-unavailable",reason:String((u==null?void 0:u.message)||u)}}if(r!==this._trackingRestoreGeneration||this._destroyed||o.aborted)return this._trackingRestoreController===i&&(this._trackingRestoreController=null),{...s,status:"cancelled",reason:String(o.reason||"superseded")};if(this._trackingRestoreController===i&&(this._trackingRestoreController=null),s.status==="found"){const u={...s,...n,classification:"followed",cleared:!1};return this._publishTrackingRestoreStatus(u),u}if(["cancelled","superseded","destroyed"].includes(s.status))return s;if(s.status==="missing"||s.status==="source-unavailable")return this._beginPendingTrackingRestore(n,s,o);const a=s.status==="missing"?this._classifyMissingTrackingTarget(n):"source-unavailable",c=this._passivelyClearTrackingSelection(n),l={...s,...n,classification:a,cleared:c};return this._publishTrackingRestoreStatus(l),l}destroy(){var t,n,i,o;if(!this._destroyed){this._destroyed=!0;for(const r of this._restoreControllers.values())r.abort("coordinator-destroyed");this._restoreControllers.clear(),this._revokePendingTrackingWatch("coordinator-destroyed"),this._trackingRestoreController=null,(t=this._unsubscribe)==null||t.call(this),this._unsubscribe=null,(n=this._unsubscribeVisibilityRequests)==null||n.call(this),this._unsubscribeVisibilityRequests=null,(o=(i=this.shareLinkManager)==null?void 0:i.setLayerStateProvider)==null||o.call(i,null),this.onDurableStateChange=null,this.onTrackingRestoreStatus=null}}}const Yk=Object.freeze(Object.defineProperty({__proto__:null,LAYER_RESTORE_ORIGINS:zn,LAYER_STATE_REGISTRY:pn,LAYER_STATE_STORAGE_KEY:rl,LAYER_STATE_VERSION:Qr,LayerStateCoordinator:ey,REGISTERED_LAYER_IDS:qC,SHARE_TRACKING_RESTORE_POLICIES:ir,cloneLayerState:KC,createDefaultLayerState:Pd,decodeLayerStateParams:XC,encodeLayerStateParams:YC,isExplicitLayerStateOrigin:Mo,layerOptionsForRestore:JC,normalizeLayerState:Pn,normalizeRadioFilter:kf,parseStoredLayerState:ZC,serializeStoredLayerState:QC,validateLayerStateRegistry:WC},Symbol.toStringTag,{value:"Module"}));function Xk({source:e,now:t=Date.now}={}){const i=new Set;let o=!1;const r=new Set;let s=0,a=!1,c=null,l=null,u=null;function h(C,{signal:y}={}){if(typeof(C==null?void 0:C.getSnapshot)!="function")throw new TypeError("A snapshot source is required");u==null||u();const v=new AbortController;l=v,c=C,i.clear(),s=0,a=!1;const M=()=>{v.abort(),y==null||y.removeEventListener("abort",M),l===v&&(c=null,l=null,u=null,i.clear(),s=0,a=!1)};return u=M,y!=null&&y.aborted?M():y==null||y.addEventListener("abort",M,{once:!0}),M}function d(){return o}function f(C){const y=!!C;if(y!==o){o=y;for(const v of r)try{v(y)}catch{}}}function p(C){return typeof C!="function"?()=>{}:(r.add(C),()=>r.delete(C))}function g(C){for(const y of C||[]){const v=String(y||"").trim().toLowerCase();v&&i.add(v)}s=t()}function _(C){return i.has(String(C||"").toLowerCase())}async function m(){if(!c||!l||l.signal.aborted||o||a||t()-s<6e4)return;const C=l,y=c,v=AbortSignal.any([C.signal,AbortSignal.timeout(1e4)]);a=!0;try{const M=typeof y.getIdentities=="function"?await y.getIdentities({},{signal:v}):(await y.getSnapshot({},{signal:v})).records.map(w=>w.id);if(v.throwIfAborted(),l!==C)return;if(!Array.isArray(M))throw new TypeError("Expected aircraft identities");g(M)}catch{}finally{l===C&&(a=!1)}}function b(){u==null||u(),i.clear(),s=0,r.clear(),o=!1}return e&&h(e),{configureSource:h,dispose:b,isMilitaryLayerActive:d,setMilitaryLayerActive:f,onMilitaryLayerActiveChange:p,registerMilitaryIcaos:g,isMilitaryIcao:_,refreshMilitaryRegistryIfStale:m}}const Ll=Math.PI/180,ty=new Cesium.Cartographic,Qk=new Cesium.Cartographic;function Po(e){return(e%360+360)%360}function ny(e,t,n){if(!n||!(e!=null&&e.position)||!t)return!1;const i=Cesium.Cartographic.fromCartesian(e.position,Cesium.Ellipsoid.WGS84,ty),o=Cesium.Cartographic.fromCartesian(t,Cesium.Ellipsoid.WGS84,Qk);return!i||!o||o.height<=i.height?!1:(Cesium.Cartesian3.fromRadians(i.longitude,i.latitude,o.height,Cesium.Ellipsoid.WGS84,e.position),!0)}function If(e){const t=Po(e);return t>180?t-360:t}function iy(e,t,n=25){const i=t.x-e.x,o=t.y-e.y,r=t.z-e.z;if(i*i+o*o+r*r=yp?1:(e-Mu)/(yp-Mu):1}function xl(e,t,n){return Po(e+If(t-e)*n)}function Gc(e,t,n=Zk){return n+(t-n)*Rf(e)}function oy({derivedSpeedMps:e,derivedTrackDeg:t,reportedSpeedMps:n,reportedTrackDeg:i}={}){return{speedMps:Number.isFinite(e)?Math.max(0,e):Number.isFinite(n)?Math.max(0,n):null,trackDeg:Number.isFinite(t)?t:Number.isFinite(i)?i:null}}function ry({fixEpochMs:e,lastContactEpochMs:t,minimumSec:n=60,contactGraceSec:i=60,maximumSec:o=300}={}){const r=Math.max(0,Number.isFinite(n)?n:60),s=Math.max(r,Number.isFinite(o)?o:300);if(!Number.isFinite(e)||!Number.isFinite(t))return r;const a=Math.max(0,(t-e)/1e3),c=Math.max(0,Number.isFinite(i)?i:60);return Math.min(s,Math.max(r,a+c))}function Uc(e,t,n,i){if(e==null||!Number.isFinite(e))return Po(t);const o=If(t-e),r=Math.max(0,n*Math.max(0,i)),s=Math.abs(o)<=r?o:Math.sign(o)*r;return Po(e+s)}function eA(e,t=.4,n=4,i=0){if(!e||e.length<2)return 0;let o=0,r=0;for(let a=1;a120)&&!(!Number.isFinite(e[a].trackDeg)||!Number.isFinite(e[a-1].trackDeg))){if(i>0){const l=e[a-1].speedMps,u=e[a].speedMps;if(Number.isFinite(l)&&l + + + `,widebody:` + + + + `,quadjet:` + + + + + `,turboprop:` + + + + + + `,light:` + + `,glider:` + + `,helicopter:` + + + + + + + + + + `,fastjet:` + `,bizjet:` + `,tr3b:` + + + + + + + + `,tr3bHot:` + + + + + + + + + + + + + + + + `,uav:` + `},Tp=new Map,lA=e=>typeof btoa=="function"?btoa(e):Buffer.from(e,"utf8").toString("base64"),cA=64,uA=192,Di=uA;function Nn(e,t=cA){const n=Ep[e]?e:"airliner",i=`${n}@${t}`;let o=Tp.get(i);if(!o){const r=`${Ep[n]}`;o="data:image/svg+xml;base64,"+lA(r),Tp.set(i,o)}return o}const kp=150,dA=4500,Ap=5,hA=1,fA=3,mA=2e4;function Fd(e,t,n,i){const o=(n-e)*111.32,r=(i-t)*111.32*Math.cos((e+n)/2*Math.PI/180);return Math.hypot(o,r)}function pA({flightState:e,records:t,militaryRegistry:n,groundFloor:i,meshFloor:o,rendering:r,tracking:s,motion:a,enrichment:c,queries:l}){const{refreshMilitaryRegistryIfStale:u,isMilitaryIcao:h}=n,{warmGroundFloor:d}=i,{sampleMeshFloorCells:f}=o;return function(g,_){var w,E,k,T;const m=new Set,b=new Set,C=((E=(w=_||e._viewer)==null?void 0:w.camera)==null?void 0:E.positionCartographic)||null,y=C?Cesium.Math.toDegrees(C.latitude):null,v=C?Cesium.Math.toDegrees(C.longitude):null,M=[];u();for(const I of g.records){const R=I.id;if(b.add(R),h(R)&&s._militaryLayerSuppresses(R)){const G=e._billboards.get(R);G&&(e._billboardCollection.remove(G),e._billboards.delete(R),r._releaseModel(R),t.forget(R),e._cullPositions.delete(R),e._positionHistory.delete(R),e._displayCourse.delete(R),e._groundSnap.forget(R));continue}m.add(R);const{prevMeta:A,meta:L,groundFlipped:F,fixEpochMs:P}=t.receive(I,{viewerLatDeg:y,viewerLonDeg:v,trackedId:e._trackedIcao,floorWarmPoints:M}),O=Cesium.Cartesian3.fromDegrees(L.rawLon,L.rawLat,L.renderAltitudeM);F&&e._groundSnap.forget(R),e._cullPositions.set(R,L.renderAltitudeM<10?Cesium.Cartesian3.fromDegrees(L.rawLon,L.rawLat,12):null);const D=R===e._trackedIcao,$=Cesium.JulianDate.fromDate(new Date(P));e._positionHistory.has(R)||e._positionHistory.set(R,[]);const x=e._positionHistory.get(R),N=x[x.length-1];if(!N||Cesium.JulianDate.greaterThan($,N.time))x.push({time:$,epochMs:P,position:O.clone(),velocity:L.velocity,track:L.true_track}),x.length>Ap&&x.shift(),L.turnRateDps=Fl(x),D&&s._appendTrailFix(O.clone());else if(r._modelOwnsVisual(R)||ny(N,O,L.onGround),N.velocity!==L.velocity||N.track!==L.true_track){const V=sy(N,{epochMs:Date.now(),velocity:L.velocity,track:L.true_track,turnRateDps:L.turnRateDps});V&&(x.push(V),x.length>Ap&&x.shift(),L.turnRateDps=Fl(x),D&&s._appendTrailFix(V.position.clone()))}if(e._billboards.has(R)){const G=e._billboards.get(R);D||(G.color=r._fleetBillboardColor(R).withAlpha(((k=G.color)==null?void 0:k.alpha)??1)),((A==null?void 0:A.klass)!==L.klass||F||e._cockpitContactMode)&&r._applyFleetBillboardPresentation(R,G),(A==null?void 0:A.klass)!==L.klass&&r._syncModelToClass(R)}else{const G=e._billboardCollection.add({position:O,image:Nn(r._iconKind(R,L.klass)),width:D?24:20,height:D?24:20,scale:r._fleetBillboardScale(R,L.klass),rotation:0,alignedAxis:Cesium.Cartesian3.ZERO,color:D?Cesium.Color.CYAN:r._fleetBillboardColor(R),sizeInMeters:!1,scaleByDistance:r._normalBillboardScaleByDistance(),disableDepthTestDistance:r._groundDepthDistance(),id:R,show:!D});e._billboards.set(R,G),r._applyFleetBillboardPresentation(R,G)}D&&F&&!L.onGround&&s._startTrail(R),D&&e._trackedEntity&&s._updateTrackedLabelModel(R)}for(const[I,R]of e._billboards){if(m.has(I))continue;const S=t.absence(I,{complete:g.complete,likelyLanded:l._likelyLanded(I)});if(S!=="retain"){if(S==="stale"){I===e._trackedIcao&&e._trackedEntity&&s._updateTrackedLabelModel(I);continue}I===e._trackedIcao&&s._clearTracking(!1,{evicted:!0}),e._billboardCollection.remove(R),e._billboards.delete(I),r._releaseModel(I),t.forget(I),e._cullPositions.delete(I),e._positionHistory.delete(I),e._displayCourse.delete(I),e._groundSnap.forget(I),e._displayFloorState.delete(I)}}return e._lastCamPoseSig="",c._sweepAmbientEnrichment(),a._collectDisplayCorridorCells(M,y,v),d(M),f((T=e._viewer)==null?void 0:T.scene,M,{excludeObjects:[...e._billboards.values(),...e._models.values(),e._trackedModel].filter(Boolean),viewerLat:y,viewerLon:v}),a._refloorStaleGroundedContacts(m),{count:e._billboards.size,ids:b}}}function lr(e,t){const n=String(e||"").trim();return n||String(t||"").trim()||""}function un(e,t,n){return Number.isFinite(e)?e:Number.isFinite(t)?t:n}function ay({geoAltM:e,baroAltM:t,onGround:n,surfaceM:i,geoidN:o}){return n&&Number.isFinite(i)?i:Number.isFinite(e)?e:Number.isFinite(t)?t+(Number.isFinite(o)?o:0):null}function gA({geoAltM:e,baroAltM:t,priorRenderM:n,geoidN:i}){return Number.isFinite(e)||Number.isFinite(t)||Number.isFinite(n)?null:Number.isFinite(i)?i:null}const _A=new Set(["EC20","EC25","EC30","EC35","EC45","EC55","AS50","AS55","AS65","AS32","A109","A119","A139","A169","A189","B06","B06T","B407","B412","B427","B429","B430","B505","S76","S92","S61","S64","H60","H500","MD52","MD60","R22","R44","R66","EXEC","EXPL","GAZL","LYNX","NH90","PUMA","SCAV","UH1","B105","B212","B214","B222","AC","H47","H64"]),bA=new Set(["B741","B742","B743","B744","B748","B74S","B74R","B74D","A388","A342","A343","A345","A346","A124","C5M","A225","IL96","B52","A140"]),CA=new Set(["A306","A30B","A310","A332","A333","A338","A339","A359","A35K","B762","B763","B764","B772","B77L","B773","B77W","B778","B779","B788","B789","B78X","MD11","IL86","DC10","L101","A337","B767","B777","B787","C17","K35R"]),yA=new Set(["DH8A","DH8B","DH8C","DH8D","AT43","AT44","AT45","AT46","AT72","AT73","AT75","AT76","SF34","SB20","SW3","SW4","E110","E120","C208","C212","C408","PC12","B190","BE20","B350","B300","JS31","JS32","JS41","D228","D328","F50","F27","ATP","TBM7","TBM8","TBM9","TBM0","PC6","C441","C425","DHC6","DHC7","C130","AN12","AN26","AN32","SH36","CVLT","SAAB","A400"]),vA=new Set(["DISC","DUOD","VENT","NIMB","NIM3","NIM4","JANS","ARCE","DG40","DG80","DG1T","DG30","DG50","LS3","LS4","LS6","LS7","LS8","STD3","G103","G102","G104","PW5","PW6","L13","L23","L33","PIK","PEGA","KEST","TWIN","AS33","ASW","ASG","ASK","VENS","GLID","MOSQ","DIMO"]),MA=new Set(["C150","C152","C162","C172","C72R","C175","C177","C180","C182","C185","C188","C206","C207","C210","C310","C337","SR20","SR22","S22T","PA18","PA24","PA28","P28A","P28B","P28R","PA32","P32R","PA34","PA38","PA44","PA46","DA20","DA40","DA42","DA62","BE33","BE35","BE36","BE58","BE76","BE19","BE23","BE24","M20P","M20T","AA1","AA5","GLAS","COL4","RV4","RV6","RV7","RV8","RV9","RV10","RV14","GA8","G115","BL8","CH7"]),wA=new Set(["C500","C501","C510","C525","C25A","C25B","C25C","C25M","C550","C551","C560","C56X","C650","C680","C68A","C700","C750","CL30","CL35","CL60","GLF2","GLF3","GLF4","GLF5","GLF6","GA5C","GA6C","G150","G280","GL5T","GL7T","GLEX","LJ23","LJ24","LJ25","LJ31","LJ35","LJ40","LJ45","LJ55","LJ60","LJ70","LJ75","FA10","FA20","FA50","FA7X","FA8X","F900","F2TH","H25A","H25B","H25C","HDJT","E50P","E55P","E545","E550","PC24","PRM1","BE40","ASTR","WW24","SF50"]),EA=new Set(["Q1","Q4","Q9","MQ1","MQ4","MQ9","RQ4","TB2","SHDW","HERN"]),TA=new Set(["F16","F15","F18","FA18","F14","F22","F35","F4","F5","A10","AV8B","TYPH","EUFI","RFAL","RAFL","GRIP","JAS39","TOR","MIR2","M2000","SU27","SU30","SU33","SU34","SU35","SU57","MG29","MIG29","MG31","J20","T38","HAWK","L39","M346","T7A"]),Ip={2:"light",3:"airliner",4:"airliner",5:"airliner",6:"widebody",7:"fastjet",8:"helicopter",9:"glider"},Rp={A1:"light",A2:"light",A3:"airliner",A4:"airliner",A5:"widebody",A6:"fastjet",A7:"helicopter",B1:"glider"};function Lf({typeCode:e,category:t}={}){const n=String(e||"").trim().toUpperCase();if(n)return TA.has(n)?"fastjet":EA.has(n)?"uav":_A.has(n)?"helicopter":bA.has(n)?"quadjet":CA.has(n)?"widebody":yA.has(n)?"turboprop":vA.has(n)?"glider":wA.has(n)?"bizjet":MA.has(n)?"light":"airliner";if(Number.isFinite(t)&&Ip[t])return Ip[t];const i=String(t||"").trim().toUpperCase();return Rp[i]?Rp[i]:"airliner"}const Oi={light:.62,glider:.58,turboprop:.86,airliner:1,widebody:1.3,quadjet:1.45,helicopter:.82,fastjet:.8,bizjet:.72,uav:.75},Sd={light:.75,glider:.75,turboprop:.85,airliner:1,widebody:1.3,quadjet:1.45,helicopter:.8,fastjet:.8,bizjet:.8,uav:.8},kA={light:"/models/airplane.glb",glider:"/models/airplane.glb",turboprop:"/models/airplane.glb",airliner:"/models/airplane.glb",widebody:"/models/airplane.glb",quadjet:"/models/airplane.glb",helicopter:"/models/airplane.glb",fastjet:"/models/airplane.glb",bizjet:"/models/airplane.glb",uav:"/models/airplane.glb"},ly={helicopter:{url:"/models/bell206.glb",bellyM:1.66,radiusM:8.24},light:{url:"/models/c172.glb",bellyM:1.36,radiusM:7},bizjet:{url:"/models/citation2.glb",bellyM:2.86,radiusM:11.24},uav:{url:"/models/mq9.glb",bellyM:2.02,radiusM:12},widebody:{url:"/models/b789.glb",bellyM:7.81,radiusM:44.08},turboprop:{url:"/models/atr72.glb",bellyM:3.81,radiusM:19.49}};class AA{constructor({geoidHeight:t,cachedGroundFloor:n,floorAltitudeM:i}){this.services={geoidHeight:t,cachedGroundFloor:n,floorAltitudeM:i},this.data=new Map,this.missingPolls=new Map,this.geoidNCache=new Map,this.geoidReady=!1}receive(t,{viewerLatDeg:n,viewerLonDeg:i,trackedId:o,floorWarmPoints:r}){const{geoidHeight:s,cachedGroundFloor:a,floorAltitudeM:c}=this.services,{id:l,callsign:u,originCountry:h,longitude:d,latitude:f,baroAltitudeM:p,onGround:g,speedMps:_,courseDeg:m,ellipsoidAltitudeM:b,category:C,verticalRateMps:y}=t,v=g===!0;this.missingPolls.delete(l);const M=this.data.get(l),w=un(p,M==null?void 0:M.altitude,v?0:1e4);let E=this.geoidNCache.get(l);E===void 0&&this.geoidReady&&(E=s(f,d),this.geoidNCache.set(l,E));let k=null;v&&(k=a(f,d),k==null&&Number.isFinite(M==null?void 0:M.rawLat)&&Number.isFinite(M==null?void 0:M.rawLon)&&(k=a(M.rawLat,M.rawLon)),n!=null&&Fd(n,i,f,d)<=kp&&r.push({lat:f,lon:d}),k==null&&(k=gA({geoAltM:b,baroAltM:p,priorRenderM:M==null?void 0:M.renderAltitudeM,geoidN:E})));const T=Number.isFinite(b)?b:null,I=ay({geoAltM:T,baroAltM:Number.isFinite(p)?p:null,onGround:v,surfaceM:k,geoidN:E});let R;I!=null?R=I:Number.isFinite(M==null?void 0:M.renderAltitudeM)?R=M.renderAltitudeM:R=w,!v&&R0?t.positionTimeMs:Date.now();return{icao24:l,prevMeta:M,meta:L,groundFlipped:S,fixEpochMs:F}}absence(t,{complete:n,likelyLanded:i}){var s;if(!n&&Date.now()-(((s=this.data.get(t))==null?void 0:s.observedReceiptMs)??0)<3e5)return"retain";const o=(this.missingPolls.get(t)||0)+1;return o<(i?hA:fA)?(this.missingPolls.set(t,o),"stale"):(this.missingPolls.delete(t),"remove")}forget(t){this.data.delete(t),this.missingPolls.delete(t),this.geoidNCache.delete(t)}}function IA({feed:e,getQuery:t,applySnapshot:n,setSourceLabel:i,applyPendingTrackingRestore:o}){return{methods:{async update(s,{signal:a=null}={}){const c=Date.now(),l=++e._trackingRefreshEpoch;if(e._lastTrackingRefreshOutcome={epoch:l,status:"source-unavailable",ids:new Set,source:e._lastSource,coverage:e._lastCoverage},e._retryAt&&c=i)return e;const s=Math.hypot(t.x-n.x,t.y-n.y,t.z-n.z);if(!(i>s))return null;const a=(r-s)/(i-s);return a<=0?null:(o.x=t.x+(e.x-t.x)*a,o.y=t.y+(e.y-t.y)*a,o.z=t.z+(e.z-t.z)*a,o)}function jc(e,t,n,i){if(!e||!i)return null;const o=Number.isFinite(n)?n:1,r=((t==null?void 0:t[0])||0)*o,s=((t==null?void 0:t[1])||0)*o,a=((t==null?void 0:t[2])||0)*o;return i.x=e[0]*r+e[4]*s+e[8]*a+e[12],i.y=e[1]*r+e[5]*s+e[9]*a+e[13],i.z=e[2]*r+e[6]*s+e[10]*a+e[14],i}function ro(){if(ro._dataUrl)return ro._dataUrl;const e=document.createElement("canvas");e.width=16,e.height=16;const t=e.getContext("2d");return t.clearRect(0,0,16,16),t.save(),t.shadowBlur=2.5,t.shadowColor="rgba(255, 255, 255, 0.55)",t.beginPath(),t.arc(8,8,4.25,0,Math.PI*2),t.lineWidth=1.25,t.strokeStyle="rgba(255, 255, 255, 0.82)",t.stroke(),t.shadowBlur=1.5,t.beginPath(),t.arc(8,8,1.55,0,Math.PI*2),t.fillStyle="rgba(255, 255, 255, 0.98)",t.fill(),t.restore(),ro._dataUrl=e.toDataURL("image/png"),ro._dataUrl}ro._dataUrl=null;const Sp=2e3,Np=.5,gI=Cesium.Math.toRadians(.5),_y=new Cesium.Matrix4,Nl=new Cesium.Cartesian3,ks=new Cesium.Cartesian3;function ri(e,t,n,i=null){const o=e==null?void 0:e.camera;if(!(o!=null&&o.rightWC)||!(o!=null&&o.upWC)||!t)return i;const r=Cesium.Math.toRadians(n||0);Cesium.Cartesian3.fromElements(Math.sin(r)*Sp,Math.cos(r)*Sp,0,Nl);const s=Cesium.Transforms.eastNorthUpToFixedFrame(t,Cesium.Ellipsoid.WGS84,_y);Cesium.Matrix4.multiplyByPointAsVector(s,Nl,ks);const a=Cesium.Cartesian3.dot(ks,o.rightWC),c=-Cesium.Cartesian3.dot(ks,o.upWC);return a*a+c*c0)||!Number.isFinite(a))return 0;let c=t.x*i.x-o,l=t.y*i.y-r,u=t.z*i.z-s;const h=Math.sqrt(c*c+l*l+u*u);if(!(h>0)||!Number.isFinite(h))return 0;c/=h,l/=h,u/=h;const d=-(o*c+r*l+s*u)/a,f=Math.acos(Math.min(1,Math.max(-1,d))),p=Math.asin(Math.min(1,1/a)),g=f-p;if(!(n>0))return g>0?1:0;const _=Math.min(1,Math.max(0,g/(2*n)+.5));return _*_*(3-2*_)}function Vo(e){return Dp.cameraPosition=e.positionWC,Dp}function qc(e){const t=e.positionWC;return`${Math.round(t.x/10)}:${Math.round(t.y/10)}:${Math.round(t.z/10)}:${e.heading.toFixed(3)}:${e.pitch.toFixed(3)}:${e.roll.toFixed(3)}`}const Op=30,Bp=new Cesium.Cartesian3,yI=new Cesium.Cartesian2,vI=new Cesium.Cartesian2;function Vp(e,t,n,i=null){if(!(e!=null&&e.camera)||!t||!Number.isFinite(n))return i;const o=Cesium.Math.toRadians(n);Cesium.Cartesian3.fromElements(Math.sin(o)*Op,Math.cos(o)*Op,0,Nl);const r=Cesium.Transforms.eastNorthUpToFixedFrame(t,Cesium.Ellipsoid.WGS84,_y);Cesium.Matrix4.multiplyByPointAsVector(r,Nl,ks),Cesium.Cartesian3.add(t,ks,Bp);const s=Cesium.SceneTransforms.worldToWindowCoordinates(e,t,yI),a=Cesium.SceneTransforms.worldToWindowCoordinates(e,Bp,vI);if(!s||!a)return ri(e,t,n,i);const c=a.x-s.x,l=a.y-s.y,u=Math.hypot(c,l),h=Math.atan2(-c,-l);if(u>=Hp)return h;const d=ri(e,t,n,i);if(!Number.isFinite(d))return h;if(u<=Iu)return d;const f=(u-Iu)/(Hp-Iu),p=Math.atan2(Math.sin(h-d),Math.cos(h-d));return d+p*f}const Iu=.5,Hp=3;function MI({flightState:e,services:t,parts:n,layer:i,resolveAsset:o}){const{isMilitaryIcao:r}=t.militaryRegistry,{tr3bIconKind:s,isTr3b:a}=t.aircraftPresentation,{trackedModelScaleForPixelCap:c}=t.camera,{focusNowMs:l,getFocusTarget:u,nearFarScalarValueAtDistance:h,advanceProjectedSpriteFocus:d}=t.focus,{applyAircraftBillboardTreatment:f,applyAircraftModelTreatment:p}=t.recession;function g(z){return r(z)?Aa:Cesium.Color.WHITE}function _(z,j){var ne;return(Oi[j]||1)*((ne=e.records.data.get(z))!=null&&ne.onGround?LA:1)}function m(){return Number.POSITIVE_INFINITY}function b(z){const j=e._specCache.get(z);if(j)return j;const ne=ly[z];let ee;if(ne)ee={url:ne.url,scale:1,nativeRadiusM:ne.radiusM,bellyM:ne.bellyM,blendAmount:Lp,visualCenterNative:br(ne.url),trailAnchorNative:Ts(ne.url)};else{const re=SA*(Sd[z]||1),se=kA[z]||cy;ee={url:se,scale:re,nativeRadiusM:FA,bellyM:UA*re,blendAmount:Lp,visualCenterNative:br(se),trailAnchorNative:Ts(se)}}return e._specCache.set(z,ee),ee}function C(){return new Cesium.NearFarScalar(1e3,3,8e6,.5)}function y(){return new Cesium.NearFarScalar(1e3,1.15,8e6,.65)}const v=(z,j)=>s(z,j,{hot:e._irBoost});function M(z,j){var me,be;if(!j)return;const ne=e._billboardLimbScale.get(j)??1,ee=e._cockpitContactMode&&z!==e._trackedIcao,re=ee&&e._cockpitNearContacts.has(z);if(ee&&!re){const J=((me=j.color)==null?void 0:me.alpha)??1;j.image=ro(),j.width=Pp,j.height=Pp,j.scale=ne,j.scaleByDistance=y(),j.color=(r(z)?Aa:xp).withAlpha(J),j.rotation=0;return}const se=e.records.data.get(z);j.image=Nn(v(z,se==null?void 0:se.klass),j._gevIconLarge?Di:void 0),j.width=z===e._trackedIcao?24:20,j.height=z===e._trackedIcao?24:20,j.scale=_(z,se==null?void 0:se.klass)*ne,j.scaleByDistance=C(),j.color=g(z).withAlpha(((be=j.color)==null?void 0:be.alpha)??1)}function w(z){return z===e._trackedIcao?Cesium.Color.CYAN:r(z)?Aa:Cesium.Color.WHITE}function E(){var j,ne,ee;return e._models3dEnabled?(((ee=(ne=(j=e._viewer)==null?void 0:j.camera)==null?void 0:ne.positionCartographic)==null?void 0:ee.height)??1/0){const j=b(z);return`${j.url}@${j.scale}`};function D(z){var ee;const j=O((ee=e.records.data.get(z))==null?void 0:ee.klass),ne=e._models.get(z);if(ne&&ne._gevSpecKey!==j||!ne&&e._modelPending.has(z)){const re=e._billboards.get(z);re&&z!==e._trackedIcao&&(re.show=!0),G(z)}z===e._trackedIcao&&e._trackedModel&&e._trackedModel._gevSpecKey!==j&&H()}function $(){e._irReloadQueue=[...e._models.keys()];for(const z of e._modelPending)e._models.has(z)||e._modelGen.set(z,(e._modelGen.get(z)||0)+1);H()}function x(){if(!e._irReloadQueue)return;const z=e._irReloadQueue.splice(0,dI);for(const j of z){const ne=e._models.get(j);if(!ne||ne._gevIrBoost===e._irBoost)continue;const ee=e._billboards.get(j);ee&&j!==e._trackedIcao&&(ee.show=!0),G(j)}e._irReloadQueue.length===0&&(e._irReloadQueue=null)}async function N(z){var be,J,Z;if(z===e._trackedIcao||(n.enrichment._requestTypeEnrichment(z,!0),e._models.has(z)||e._modelPending.has(z))||e._models.size+e._modelPending.size>=k())return;const j=e._modelEpoch,ne=e._modelGen.get(z)||0;e._modelPending.add(z);let ee=null;const re=O((be=e.records.data.get(z))==null?void 0:be.klass),se=e._irBoost;try{const ae=b((J=e.records.data.get(z))==null?void 0:J.klass);ee=await Cesium.Model.fromGltfAsync({url:o(ae.url),asynchronous:!1,minimumPixelSize:xA,scale:ae.scale,color:e._irBoost?Cesium.Color.WHITE:w(z),colorBlendMode:Cesium.ColorBlendMode.MIX,colorBlendAmount:e._irBoost?1:ae.blendAmount,customShader:e._irBoost?e._IR_UNLIT_SHADER:void 0,id:z})}catch{j===e._modelEpoch&&(e._modelPending.delete(z),W(z));return}if(j!==e._modelEpoch){try{ee.destroy()}catch{}return}if(e._modelPending.delete(z),(e._modelGen.get(z)||0)!==ne||!E()||!e._modelCollection||e._modelCollection.isDestroyed()||!e.records.data.has(z)||z===e._trackedIcao||e._models.has(z)||e._models.size>=k()||O((Z=e.records.data.get(z))==null?void 0:Z.klass)!==re||e._irBoost!==se){try{ee.destroy()}catch{}W(z);return}ee.id=z,ee._gevSpecKey=re,ee._gevIrBoost=se,ee.show=!1,e._modelCollection.add(ee),e._models.set(z,ee),e._planeModelLoaded=!0}function G(z){const j=e._models.get(z),ne=e._modelPending.has(z);if((j||ne)&&e._modelGen.set(z,(e._modelGen.get(z)||0)+1),j){if(e._modelCollection&&!e._modelCollection.isDestroyed())try{e._modelCollection.remove(j)}catch{}e._models.delete(z)}W(z)}function W(z){!e._modelPending.has(z)&&!e._models.has(z)&&e._modelGen.delete(z)}function V(){e._irReloadQueue=null;for(const z of e._modelPending)e._modelGen.set(z,(e._modelGen.get(z)||0)+1);if(e._modelCollection&&!e._modelCollection.isDestroyed())for(const z of e._models.values())try{e._modelCollection.remove(z)}catch{}e._models.clear()}function H(){if(e._trackedModelGen++,e._trackedModelLoading=!1,e._trackedModel){if(e._modelCollection&&!e._modelCollection.isDestroyed())try{e._modelCollection.remove(e._trackedModel)}catch{}e._trackedModel=null}}function B(){var ne,ee,re,se;if(!(e._trackedIcao&&n.tracking._trackedModelRegimeActive()&&e._modelCollection&&!e._modelCollection.isDestroyed())){e._trackedModel&&(e._trackedModel.show=!1);return}const j=n.motion._trackedDisplayPosition(e._trackedIcao)||((ne=e._billboards.get(e._trackedIcao))==null?void 0:ne.position);if(!j){e._trackedModel&&(e._trackedModel.show=!1);return}if(!e._trackedModel&&!e._trackedModelLoading&&n.tracking._trackedModelLoadAllowed()){e._trackedModelLoading=!0;const me=e._trackedModelGen,be=b((ee=e.records.data.get(e._trackedIcao))==null?void 0:ee.klass),J=O((re=e.records.data.get(e._trackedIcao))==null?void 0:re.klass),Z=e._irBoost;Cesium.Model.fromGltfAsync({url:o(be.url),asynchronous:!1,minimumPixelSize:uy,scale:be.scale,color:e._irBoost?Cesium.Color.WHITE:Cesium.Color.CYAN,colorBlendMode:Cesium.ColorBlendMode.MIX,colorBlendAmount:e._irBoost?1:be.blendAmount,customShader:e._irBoost?e._IR_UNLIT_SHADER:void 0,id:e._trackedIcao}).then(ae=>{var le,Y;if(me!==e._trackedModelGen||!e._modelCollection||e._modelCollection.isDestroyed()){try{ae.destroy()}catch{}return}if(O((le=e.records.data.get(e._trackedIcao))==null?void 0:le.klass)!==J||e._irBoost!==Z){try{ae.destroy()}catch{}e._trackedModelLoading=!1;return}ae.id=e._trackedIcao,ae._gevSpecKey=J,ae.show=!1;const oe=n.motion._trackedDisplayCached()||((Y=e._billboards.get(e._trackedIcao))==null?void 0:Y.position);if(oe){const K=A(e._trackedIcao,oe,e._scratchGroundPos);K&&R(K,n.motion._trackedDisplayCourse(),ae.modelMatrix)}e._trackedModel=ae,e._trackedModelLoading=!1,e._trackedModelFailIcao=null,e._trackedModelFailCount=0,e._trackedModelRetryAtMs=0,e._modelCollection.add(ae),e._planeModelLoaded=!0}).catch(ae=>{me===e._trackedModelGen&&(e._trackedModelLoading=!1,n.tracking._noteTrackedModelLoadFailure(be.url,ae))});return}if(e._trackedModel){const me=A(e._trackedIcao,j,e._scratchGroundPos);if(!me){e._trackedModel.show=!1;return}if(R(me,n.motion._trackedDisplayCourse(),e._trackedModel.modelMatrix),!e._trackedModel.ready)return;const be=b((se=e.records.data.get(e._trackedIcao))==null?void 0:se.klass);e._trackedModel.scale=c({baseScale:be.scale,nativeRadiusM:be.nativeRadiusM,rangeM:Cesium.Cartesian3.distance(e._viewer.camera.positionWC,me),viewportHeightPx:e._viewer.scene.canvas.clientHeight,fovyRad:e._viewer.camera.frustum.fovy,maximumPixelSize:Nd}),e._trackedModel.show=!0}}function q(){var ae;if(!e._viewer||!e._billboardCollection||!e._billboardCollection.show)return;const z=e._viewer.scene,j=e._viewer.camera,ne=l(Date.now());if(ne-e._lastFleetTickMs=KA;se&&(e._lastCamPoseSig=re,e._lastRotPassMs=ne);const me=Vo(j),be=u(),J=E();!J&&(e._models.size||e._modelPending.size)&&V();let Z=null;if(J){const oe=k(),le=j.positionWC,Y=T(),K=Y*Y,_e=I(),he=_e*_e,Ce=j.frustum.computeCullingVolume(le,j.directionWC,j.upWC),ye=[];for(const[pe,te]of e._billboards){if(pe===e._trackedIcao||a(pe))continue;const de=Cesium.Cartesian3.distanceSquared(le,te.position);de>he||(Cesium.Cartesian3.clone(te.position,e._scratchModelBS.center),ye.push([pe,de,Ce.computeVisibility(e._scratchModelBS)!==Cesium.Intersect.OUTSIDE]))}ye.sort((pe,te)=>pe[1]-te[1]),ye.length>oe&&ne-e._lastModelCapWarnMs>5e3&&(console.warn(`[Data:Flights] ${ye.length} planes in 3D range; capped at ${oe} (${e._models3dMode}). On-screen planes are prioritized.`),e._lastModelCapWarnMs=ne),Z=new Set;for(const[pe,,te]of ye){if(Z.size>=oe)break;te&&e._models.has(pe)&&Z.add(pe)}for(const[pe,te,de]of ye){if(Z.size>=oe)break;de&&te<=K&&!Z.has(pe)&&Z.add(pe)}for(const[pe,,te]of ye){if(Z.size>=oe)break;!te&&e._models.has(pe)&&Z.add(pe)}for(const[pe,te,de]of ye){if(Z.size>=oe)break;!de&&te<=K&&!Z.has(pe)&&Z.add(pe)}const ve=[];for(const pe of e._models.keys())pe!==e._trackedIcao&&!Z.has(pe)&&ve.push(pe);for(const pe of ve)G(pe)}for(const[oe,le]of e._billboards){if(oe===e._trackedIcao)continue;const Y=e.records.data.get(oe),K=n.motion._deadReckon(oe,e._scratchFleetPos),_e=n.motion._floorGroundedDisplayPosition(oe,Y,K,F(oe),ne);_e&&Cesium.Cartesian3.distanceSquared(_e,le.position)>1&&(le.position=_e);const he=!me.isPointVisible(e._cullPositions.get(oe)||le.position),Ce=!he&&!le.show;if(le.show===he&&(le.show=!he),he){const Se=e._models.get(oe);Se&&Se.show&&(Se.show=!1);continue}const ye=Cesium.Cartesian3.distance(j.positionWC,le.position),ve=h(le.scaleByDistance,ye),pe=d(le,le.position,z,j,ne,be,void 0,(le.width||20)*(le.scale||1)*ve*.5,(le.height||20)*(le.scale||1)*ve*.5),te=e._cockpitContactMode&&e._cockpitNearContacts.has(oe),de=e._cockpitContactMode&&!te?r(oe)?Aa:xp:g(oe),U=f({billboard:le,baseScale:e._cockpitContactMode&&!te?1:_(oe,Y==null?void 0:Y.klass),baseAlpha:e.records.missingPolls.get(oe)?.45:1,baseColor:de,focusFactor:pe.factor,cameraDistanceM:ye,cameraHeightM:(ae=j.positionCartographic)==null?void 0:ae.height});if(e._billboardLimbScale.set(le,U.factors.scale),!e._cockpitContactMode||te){const Se=(le.width||20)*(le.scale||1)*ve*(globalThis.devicePixelRatio||1),Ue=le._gevIconLarge?Se>56:Se>76;Ue!==!!le._gevIconLarge&&(le._gevIconLarge=Ue,le.image=Nn(v(oe,Y==null?void 0:Y.klass),Ue?Di:void 0))}const Le=e._drCourseDeg!=null?e._drCourseDeg:Y&&Y.true_track||0,ke=e._displayCourse.get(oe),Ne=e._drCourseHold&&ke!=null?ke:Uc(ke,Le,Gc(e._drSpeedMps!=null?e._drSpeedMps:(Y&&Y.velocity)??NaN,hy),ee);if(e._displayCourse.set(oe,Ne),J&&K&&Z.has(oe)&&!a(oe)){N(oe);const Se=e._models.get(oe);if(L(oe,Se,le,K,Ne,()=>{p({model:Se,baseColor:e._irBoost?Cesium.Color.WHITE:w(oe),alpha:e._irBoost?1:U.alpha})}))continue}if((!e._cockpitContactMode||te)&&(se||Ce)){const Se=ri(z,le.position,Ne,le.rotation);Se!==null&&Math.abs(Se-le.rotation)>.002&&(le.rotation=Se)}}}return{_fleetBillboardColor:g,_fleetBillboardScale:_,_groundDepthDistance:m,_modelSpec:b,_normalBillboardScaleByDistance:C,_cockpitBillboardScaleByDistance:y,_iconKind:v,_applyFleetBillboardPresentation:M,_modelColor:w,_modelRegimeActive:E,_modelCap:k,_modelAddDistM:T,_modelKeepDistM:I,_modelMatrix:R,_groundSampleExclusions:S,_modelDisplayPosition:A,_driveFleetModelHandoff:L,_modelOwnsVisual:F,_modelIsRendering:P,_specKeyFor:O,_syncModelToClass:D,_reloadModelsForIrBoost:$,_drainIrReloadQueue:x,_ensureModel:N,_releaseModel:G,_cleanupModelGen:W,_releaseModels:V,_releaseTrackedModel:H,_updateTrackedModel:B,_fleetTick:q}}function wI({flightState:e,services:t,parts:n,layer:i,resolveAsset:o}){const{cachedGroundFloor:r,GROUND_FLOOR_LIFT_M:s,neighborFloorM:a,stickyFloorCell:c,displayFloorHeightM:l,coarseFloorCoord:u,corridorFloorCells:h,allocateCorridorCells:d}=t.groundFloor,{trackedModelScaleForPixelCap:f}=t.camera,{nearFarScalarValueAtDistance:p,clearFocusTarget:g,publishFocusTargetFromCachedPosition:_}=t.focus;function m(x){for(const[N,G]of e.records.data){if(!(G!=null&&G.onGround)||x.has(N)||!Number.isFinite(G.rawLat)||!Number.isFinite(G.rawLon))continue;const W=r(G.rawLat,G.rawLon);if(!Number.isFinite(W))continue;const V=W+s;if(Number.isFinite(G.renderAltitudeM)&&G.renderAltitudeM>=W-1)continue;G.renderAltitudeM=V,e._cullPositions.delete(N);const H=Cesium.Cartesian3.fromDegrees(G.rawLon,G.rawLat,V),B=e._positionHistory.get(N),q=B==null?void 0:B[B.length-1];q&&(q.position=Cesium.Cartesian3.clone(H,q.position));const z=e._billboards.get(N);z&&(z.position=H)}}function b(x,N){const G=e.records.data.get(x),W=e._positionHistory.get(x);if(!W||W.length===0)return e._drCourseDeg=null,e._drSpeedMps=null,e._drCourseHold=!1,e._drExtrapolating=!1,null;const V=N||new Cesium.Cartesian3,H=Cesium.JulianDate.addSeconds(Cesium.JulianDate.now(),-Sl,e._scratchRenderTime);for(let j=W.length-1;j>=1;j--){const ne=W[j-1],ee=W[j];if(Cesium.JulianDate.lessThanOrEquals(ne.time,H)&&Cesium.JulianDate.lessThanOrEquals(H,ee.time)){const re=Cesium.JulianDate.secondsDifference(ee.time,ne.time),se=re>0?Cesium.JulianDate.secondsDifference(H,ne.time)/re:1,me=Cesium.Cartesian3.distance(ne.position,ee.position),be=re>0?me/re:G&&G.velocity||0,J=G&&G.true_track||0,Z=Number.isFinite(ne.track)?ne.track:J,ae=Number.isFinite(ee.track)?ee.track:Z,oe=xl(Z,ae,se),le=G&&G.klass==="helicopter"?0:Rf(be),Y=le>0?iy(ne.position,ee.position):null;return e._drCourseDeg=Y!=null?xl(oe,Y,le):oe,e._drSpeedMps=be,e._drCourseHold=beZ&&(Cesium.Cartesian3.subtract(e._drPrevDisplay,W,e._drCorrection),e._drCorrectionStartMs=V)}else Cesium.Cartesian3.fromElements(0,0,0,e._drCorrection),e._drCorrectionStartMs=V-Au;const B=V-e._drCorrectionStartMs,q=B>=Au?0:1-B/Au;let z=Cesium.Cartesian3.multiplyByScalar(e._drCorrection,q,e._trackedPosHolder);Cesium.Cartesian3.add(W,z,z),z=D(x,H,z,n.rendering._modelOwnsVisual(x),V),Cesium.Cartesian3.clone(W,e._drPrevRaw),Cesium.Cartesian3.clone(z,e._drPrevDisplay),e._drPrevMs=V,e._drReconcileValid=!0,e._cachedDRPosition=z;const j=v(x,e._cachedDRPosition);return _({ownerLayer:"flights",id:x,scene:(se=e._viewer)==null?void 0:se.scene,camera:(me=e._viewer)==null?void 0:me.camera,displayPosition:e._cachedDRPosition,widthPx:j,heightPx:j}),z}function w(){return e._drReconcileValid&&e._drReconcileIcao===e._trackedIcao?e._cachedDRPosition:null}function E(){var x;if(e._trackedIcao&&n.rendering._modelOwnsVisual(e._trackedIcao)){const N=n.rendering._modelSpec((x=e.records.data.get(e._trackedIcao))==null?void 0:x.klass);return jc(e._trackedModel.modelMatrix,N.visualCenterNative,Number.isFinite(e._trackedModel.computedScale)?e._trackedModel.computedScale:N.scale,e._trackedVisualPos)}return w()}function k(){return!e._trackedIcao||!e._trackedModel||!n.rendering._modelOwnsVisual(e._trackedIcao)?null:Cesium.Matrix4.getTranslation(e._trackedModel.modelMatrix,e._scratchTrailClip)}function T(){var G;if(!e._trackedIcao||!e._trackedModel||!n.rendering._modelOwnsVisual(e._trackedIcao))return 0;const x=n.rendering._modelSpec((G=e.records.data.get(e._trackedIcao))==null?void 0:G.klass),N=Number.isFinite(e._trackedModel.computedScale)?e._trackedModel.computedScale:x.scale;return x.nativeRadiusM*N}function I(){var x;if(e._trackedIcao&&n.rendering._modelOwnsVisual(e._trackedIcao)){const N=n.rendering._modelSpec((x=e.records.data.get(e._trackedIcao))==null?void 0:x.klass);return py(e._trackedModel,N.trailAnchorNative,e._trackedTrailPos)}return w()}function R(){const x=e.records.data.get(e._trackedIcao),N=x&&x.true_track||0,G=e._drReconcileValid&&e._drReconcileIcao===e._trackedIcao&&e._cachedDRCourse!=null,W=G?e._cachedDRCourse:N,V=Date.now(),H=e._trackedCourseMs?Math.min(fy,(V-e._trackedCourseMs)/1e3):0;e._trackedCourseMs=V;const B=e._displayCourse.get(e._trackedIcao);if(G&&e._cachedDRHold&&B!=null)return B;const q=Gc(G?e._cachedDRSpeedMps:(x&&x.velocity)??NaN,hy),z=Uc(B,W,q,H);return e._displayCourse.set(e._trackedIcao,z),z}function S(){e._drReconcileValid=!1,e._drReconcileIcao=null,e._cachedDRFrame=-1,e._cachedDRPosition=null,e._cachedDRCourse=null,e._cachedDRSpeedMps=null,e._cachedDRHold=!1,e._trackedCourseMs=0}function A(x,N,G){if(x.heldTier&&!(Number.isFinite(x.heldM)&&x.heldCell&&n.queries._approxDistanceKm(N.lat,N.lon,x.heldCell.lat,x.heldCell.lon)<=rI)&&F(x),x.heldTier==="own"&&!x.seeded||x.probeMs!=null&&G-x.probeMsuI}function O(x,N){const G=e._displayFloorState.get(x);G&&(G.retiredMs==null?(G.retiredMs=N,G.seeded=!0,G.heldActive=!1,G.easedM=null,G.easeMs=null,G.probeMs=null,G.out=null,G.effectiveM=null,Cesium.Cartesian3.clone(Cesium.Cartesian3.ZERO,G.in)):P(G,N)&&e._displayFloorState.delete(x))}function D(x,N,G,W,V=Date.now()){if(!G||!(N!=null&&N.onGround)||W)return O(x,V),G;const H=e._displayFloorState.get(x),B=Cesium.Cartographic.fromCartesian(G,Cesium.Ellipsoid.WGS84,e._scratchDisplayCarto),q=c(Cesium.Math.toDegrees(B.latitude),Cesium.Math.toDegrees(B.longitude),H==null?void 0:H.cell),z=r(q.lat,q.lon),j=H||{cell:q,in:new Cesium.Cartesian3,out:null,effectiveM:null,heldM:null,heldCell:null,heldTier:null,heldActive:!1,seeded:!1,probeMs:null,easedM:null,easeMs:null,retiredMs:null};P(j,V)&&F(j),j.retiredMs=null;const ne=j.heldActive,ee=j.heldM;let re=z;if(Number.isFinite(re)?(L(j,re,q,"own"),j.heldActive=!1):(re=A(j,q,V),j.heldActive=Number.isFinite(re)),j.easedM==null&&ne&&Number.isFinite(ee)&&Number.isFinite(re)&&re=j.easedM)j.easedM=null,j.easeMs=null;else{const me=Math.max(0,V-j.easeMs);j.easeMs=V;const be=Math.min(lI,1-Math.exp(-me/aI));let J=j.easedM+(re-j.easedM)*be;Math.abs(J-re)<=cI?(J=re,j.easedM=null,j.easeMs=null):j.easedM=J,re=J}if(H&&H.effectiveM===re&&Cesium.Cartesian3.equals(G,H.in))return H.out||G;const se=l(B.height,re);return j.cell=q,j.effectiveM=re,Cesium.Cartesian3.clone(G,j.in),se==null?j.out=null:j.out=Cesium.Cartesian3.fromRadians(B.longitude,B.latitude,se,Cesium.Ellipsoid.WGS84,j.out||new Cesium.Cartesian3),H||e._displayFloorState.set(x,j),j.out||G}function $(x,N,G){if(N==null||G==null)return;const W=new Set;for(const H of x){const B=u(H.lat,H.lon);W.add(`${B.lat},${B.lon}`)}const V=[];for(const[H,B]of e.records.data){if(!(B!=null&&B.onGround)||n.rendering._modelOwnsVisual(H)||!Number.isFinite(B.rawLat)||!Number.isFinite(B.rawLon)||n.queries._approxDistanceKm(N,G,B.rawLat,B.rawLon)>oI)continue;const q=b(H,e._scratchCorridorPos);if(!q)continue;const z=e._drExtrapolating,j=Number.isFinite(e._drSpeedMps)?e._drSpeedMps:B.velocity||0,ne=e._drCourseDeg!=null?e._drCourseDeg:B.true_track||0,ee=Cesium.Cartographic.fromCartesian(q,Cesium.Ellipsoid.WGS84,e._scratchCorridorCarto),re=Cesium.Math.toDegrees(ee.latitude),se=Cesium.Math.toDegrees(ee.longitude),me=h(rA({extrapolating:z,displayLat:re,displayLon:se,courseDeg:ne,speedMps:j,turnRateDps:B.turnRateDps||0,fixLat:B.rawLat,fixLon:B.rawLon,lookaheadSec:iI}));let be=0;for(const J of me)r(J.lat,J.lon)==null&&(be+=1);V.push({cells:me,cold:be,speedMps:j})}e._corridorEpoch+=1;for(const H of d(V,W,tI,nI,e._corridorEpoch))x.push(H)}return{_refloorStaleGroundedContacts:m,_deadReckon:b,_extrapolateFix:C,_isTrackWarmingUp:y,_trackedFocusSizePx:v,_trackedDisplayPosition:M,_trackedDisplayCached:w,_trackedVisualCached:E,_trackedModelCenterWorld:k,_trackedModelEnvelopeM:T,_trackedTrailCached:I,_trackedDisplayCourse:R,_resetTrackedDisplay:S,_heldDisplayFloorM:A,_adoptHeldFloorM:L,_dropHeldFloor:F,_seedExpired:P,_retireDisplayFloorState:O,_floorGroundedDisplayPosition:D,_collectDisplayCorridorCells:$}}function by(e,t,n,i){const o=e instanceof Set?e:new Set,r=Math.max(0,Number(n)||0)**2,s=Math.max(r,Math.max(0,Number(i)||0)**2),a=new Set;for(const[c,l]of t||[]){if(!c||!Number.isFinite(l)||l<0)continue;const u=o.has(c)?s:r;l<=u&&a.add(c)}return a}const Cy=15e4,EI=1.15,TI=Cy*EI;function yy(e,t=!1){return Number.isFinite(e)?e<(t?TI:Cy):!1}const so=Math.PI/180,Od=6371;function sl(e,t,n,i){const o=e*so,r=n*so,s=(n-e)*so,a=(i-t)*so,c=Math.sin(s/2)**2+Math.cos(o)*Math.cos(r)*Math.sin(a/2)**2;return Od*2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c))}function $p(e,t,n,i){const o=e*so,r=n*so,s=(i-t)*so,a=Math.sin(s)*Math.cos(r),c=Math.cos(o)*Math.sin(r)-Math.sin(o)*Math.cos(r)*Math.cos(s);return Math.atan2(a,c)}function kI(e,t,n,i,o,r){const s=sl(n,i,e,t)/Od,a=$p(n,i,e,t),c=$p(n,i,o,r);return Math.asin(Math.sin(s)*Math.sin(a-c))*Od}const AI=130,II=200,RI=3700,LI=2,Gp=150;function PI({latDeg:e,lonDeg:t,altitudeM:n=null,verticalRateMps:i=null,origin:o=null,destination:r=null}){const s=Number.isFinite(o==null?void 0:o.lat)&&Number.isFinite(o==null?void 0:o.lon),a=Number.isFinite(r==null?void 0:r.lat)&&Number.isFinite(r==null?void 0:r.lon);if(!s&&!a)return!0;const c=u=>sl(e,t,u.lat,u.lon)LI){if(i>0){if(s&&sl(e,t,o.lat,o.lon)>Gp)return!1}else if(a&&sl(e,t,r.lat,r.lon)>Gp)return!1}return!0}let tn=null,xI=1;function vy(e){const t=My(e);return!t||tn!==null?null:(tn=Object.freeze({owner:t,id:xI++}),tn)}function Bd(e){return!tn||!e||e.id!==tn.id?!1:(tn=null,!0)}function Zs(){return tn?tn.owner:null}function Bt(){return tn===null}function FI(e){const t=My(e);return!!t&&Zs()===t}function SI(e){return!!(tn&&e&&e.id===tn.id)}function NI(){const e=Zs();return tn=null,e}function My(e){return typeof e=="string"&&e.trim()?e.trim():null}const DI=Object.freeze(Object.defineProperty({__proto__:null,claimPointer:vy,isLeaseCurrent:SI,isPointerFree:Bt,isPointerOwnedBy:FI,pointerOwner:Zs,releasePointer:Bd,resetPointerOwnership:NI},Symbol.toStringTag,{value:"Module"})),OI=6,BI=400;function Pf(e={}){return(Number.isFinite(e.travelPx)?Math.max(0,e.travelPx):Number.POSITIVE_INFINITY)<=OI}function xf(e={}){const t=Number.isFinite(e.durationMs)?Math.max(0,e.durationMs):Number.POSITIVE_INFINITY;return Pf(e)&&t<=BI}function Ff(e,t,n={}){const i=n.now||(()=>performance.now()),o=n.eventTypes||Cesium.ScreenSpaceEventType;let r=!1,s=0,a=null,c=0,l=null;const u=d=>{!r||!Number.isFinite(d==null?void 0:d.x)||!Number.isFinite(d==null?void 0:d.y)||(a&&(c+=Math.hypot(d.x-a.x,d.y-a.y)),a={x:d.x,y:d.y})},h=d=>{r&&(u(d),l={travelPx:c,durationMs:Math.max(0,i()-s)},r=!1,a=null)};e.setInputAction(d=>{r=!0,s=i(),a=null,c=0,l=null,u(d==null?void 0:d.position)},o.LEFT_DOWN),e.setInputAction(d=>{var f;u((d==null?void 0:d.endPosition)??(d==null?void 0:d.position)),(f=n.onMouseMove)==null||f.call(n,d)},o.MOUSE_MOVE),e.setInputAction(d=>{h(d==null?void 0:d.position)},o.LEFT_UP),e.setInputAction(d=>{r&&h(d==null?void 0:d.position);const f=l||{travelPx:0,durationMs:0};l=null,Bt()&&t(d,f)},o.LEFT_CLICK)}function VI({flightState:e,services:t,parts:n,layer:i,resolveAsset:o}){const{selectTrackedSubjectContext:r,clearTrackedSubjectContext:s,refreshTrackedSubjectContext:a}=t.context,{isTr3b:c,tr3bTypeLabel:l,tr3bConvertedIds:u}=t.aircraftPresentation,{createTrail:h}=t.trails,{ensureGeoidReady:d,geoidHeight:f}=t.geoid,{resolveGroundFloorCellsBounded:p,floorAltitudeM:g,cachedGroundFloor:_}=t.groundFloor,{clearFocusTarget:m}=t.focus,{isMilitaryLayerActive:b,isMilitaryIcao:C}=t.militaryRegistry,{trackedLabelModelFromText:y,refreshTrackedReadout:v}=t.readout,{applyTrackedCameraFrame:M}=t.camera,{resolvePickId:w,isOwnedByOtherLayer:E}=t.picking,k=i;function T(Y,K){typeof window>"u"||!window.dispatchEvent||typeof CustomEvent>"u"||window.dispatchEvent(new CustomEvent(Y,{detail:K}))}function I(Y,K="programmatic"){const _e=e._billboards.get(Y),he=e.records.data.get(Y);return!(_e!=null&&_e.position)||!he?!1:(e._trackedEntity&&(e._trackedEntity.gevSelectionOrigin=K),T("gev:awareness-subject-selected",{layerId:"flights",id:Y,label:n.queries._contactLabel(Y,he),position:Cesium.Cartesian3.clone(_e.position),origin:K}),r(R(Y)),!0)}function R(Y){const K=n.queries._describeFlight(Y);if(!K)return null;const _e=Math.round((K.altitudeM||0)*3.28084),he=K.route&&J(Y,K.route)?`${K.route.origin.code} → ${K.route.destination.code}`:null;return{id:Y,layerId:"flights",layerName:"Live Flights",source:e.feed._lastSource,label:n.queries._contactLabel(Y,e.records.data.get(Y)),latitude:K.latitude,longitude:K.longitude,properties:{name:n.queries._contactLabel(Y,e.records.data.get(Y)),operator:K.airline||"",callsign:K.callsign||"",registration:K.registration||"",type:K.typeName||K.typeCode||"",altitude:K.onGround?"on ground":`${_e.toLocaleString("en-US")} ft`,speed:Number.isFinite(K.velocityMps)?`${Math.round(K.velocityMps*1.944)} kt`:"",heading:Number.isFinite(K.track)?`${Math.round(K.track)}°`:"",route:he||"",icao24:Y,status:K.stale?"stale (missed polls)":"live"}}}function S(Y){return Y==="user"||Y==="voice"||Y==="tool"}function A(){var Ce,ye;if(!e._cockpitContactMode||!((ye=(Ce=e._viewer)==null?void 0:Ce.camera)!=null&&ye.positionWC)){e._cockpitNearContacts.size&&(e._cockpitNearContacts=new Set);return}const Y=e._cockpitNearContacts,K=[];for(const[ve,pe]of e._billboards)ve===e._trackedIcao||!(pe!=null&&pe.position)||K.push([ve,Cesium.Cartesian3.distanceSquared(e._viewer.camera.positionWC,pe.position)]);const _e=by(Y,K,n.rendering._modelAddDistM(),n.rendering._modelKeepDistM());e._cockpitNearContacts=_e;let he=!1;for(const[ve,pe]of e._billboards)Y.has(ve)!==_e.has(ve)&&(n.rendering._applyFleetBillboardPresentation(ve,pe),he=!0);he&&(e._lastCamPoseSig="")}function L(Y){var _e;const K=Y===!0;if(e._cockpitContactMode!==K){e._cockpitContactMode=K,K?A():e._cockpitNearContacts=new Set,e._modelCollection&&(e._modelCollection.show=!0),(_e=e._trail)==null||_e.setVisible(!K),e._trailHeadEntity&&(e._trailHeadEntity.show=!K);for(const[he,Ce]of e._billboards)n.rendering._applyFleetBillboardPresentation(he,Ce);e._lastCamPoseSig="",e._lastFleetTickMs=0}}function F(Y={}){const K=(Y==null?void 0:Y.active)===!0;e._cockpitSubjectId=K&&String((Y==null?void 0:Y.subjectId)||"").trim().toLowerCase()||null,L(K)}function P(){e._trackedZoomLatched=!1,e._trackedZoomLatchIcao=null,e._trackedModelFailIcao=null,e._trackedModelFailCount=0,e._trackedModelRetryAtMs=0}function O(Y=Date.now()){return e._trackedModelFailIcao!==e._trackedIcao?!0:e._trackedModelFailCount>=Fp?!1:Y>=e._trackedModelRetryAtMs}function D(Y,K){e._trackedModelFailIcao!==e._trackedIcao&&(e._trackedModelFailIcao=e._trackedIcao,e._trackedModelFailCount=0),e._trackedModelFailCount+=1,e._trackedModelRetryAtMs=Date.now()+eI,e._trackedModelFailCount>=Fp&&console.warn(`[Data:Flights] tracked 3D model gave up after ${e._trackedModelFailCount} failed loads of ${Y} — this contact stays 2D until another is selected`,K)}function $(){var Y,K,_e;return e._trackedZoomLatchIcao!==e._trackedIcao&&(e._trackedZoomLatchIcao=e._trackedIcao,e._trackedZoomLatched=!1),!e._trackedIcao||e._cockpitContactMode||c(e._trackedIcao)?(e._trackedZoomLatched=!1,!1):(e._trackedZoomLatched=yy((_e=(K=(Y=e._viewer)==null?void 0:Y.camera)==null?void 0:K.positionCartographic)==null?void 0:_e.height,e._trackedZoomLatched),e._trackedZoomLatched)}function x(){var he;if(!e._trackedIcao||!e._viewer)return;const Y=n.motion._trackedDisplayCached()||((he=e._billboards.get(e._trackedIcao))==null?void 0:he.position);if(!Y)return;const K=ri(e._viewer.scene,Y,n.motion._trackedDisplayCourse(),e._lastTrackedRotation),_e=Dl(e._lastTrackedRotation,K,0);_e!==null&&(e._lastTrackedRotation=_e)}function N(Y){e._trailPositions.push(Y),e._trailPositions.length>ku&&e._trailPositions.shift(),G()}function G(){e._trail&&e._trail.setPositions(e._trailPositions.length>1?e._trailPositions.slice(0,-1):e._trailPositions)}function W(Y){var Ce;e._trailBackfillToken+=1,e._trailPositions=[];const K=e._positionHistory.get(Y)||[],_e=Cesium.JulianDate.addSeconds(Cesium.JulianDate.now(),-Sl,e._scratchWarmupTime);for(const ye of K)Cesium.JulianDate.lessThanOrEquals(ye.time,_e)&&e._trailPositions.push(Cesium.Cartesian3.clone(ye.position));!e._trail&&e._viewer&&(e._trail=h(e._viewer,{color:Tu,width:2.5})),(Ce=e._trail)==null||Ce.setVisible(!e._cockpitContactMode),!e._trailHeadEntity&&e._viewer&&(e._trailHeadEntity=e._viewer.entities.add({id:`gev-trail:fl-head-${++e._trailHeadSeq}`,show:!e._cockpitContactMode,polyline:{positions:new Cesium.CallbackProperty(()=>{if(!e._trackedIcao||e._trailPositions.length<2||n.motion._isTrackWarmingUp())return[];const ye=n.motion._trackedTrailCached()||n.motion._trackedDisplayPosition(e._trackedIcao);if(!ye)return[];const ve=e._trailPositions[e._trailPositions.length-2],pe=gy(ve,ye,n.motion._trackedModelCenterWorld(),n.motion._trackedModelEnvelopeM(),e._scratchTrailHead);return pe?[pe,Cesium.Cartesian3.clone(ye)]:[]},!1),width:2.5,material:Cesium.Color.fromCssColorString(Tu).withAlpha(.9),depthFailMaterial:Cesium.Color.fromCssColorString(Tu).withAlpha(.45),arcType:Cesium.ArcType.GEODESIC}})),G();const he=K.length?Cesium.JulianDate.toDate(K[0].time).getTime()/1e3:1/0;V(Y,e._trailBackfillToken,he)}async function V(Y,K,_e){var pe,te,de;let he=null;try{const U=await((de=(te=e.feed._source).getTrack)==null?void 0:de.call(te,((pe=e.records.data.get(Y))==null?void 0:pe.sourceReference)??Y,{signal:AbortSignal.any([e.lifetime.signal,AbortSignal.timeout(8e3)])}));he=(U==null?void 0:U.records)??null}catch{return}if(!he||K!==e._trailBackfillToken||Y!==e._trackedIcao)return;await d();const Ce=[];for(const U of he){const{observedAtMs:Le,latitude:ke,longitude:Ne,baroAltitudeM:Se}=U,Ue=Le/1e3;!Number.isFinite(ke)||!Number.isFinite(Ne)||!Number.isFinite(Ue)||Ue>=_e||Ce.push({lat:ke,lon:Ne,baroAlt:Se})}if(!Ce.length||(await p(Ce),K!==e._trailBackfillToken||Y!==e._trackedIcao))return;const ye=[];let ve=null;for(const{lat:U,lon:Le,baroAlt:ke}of Ce){const Ne=Number.isFinite(ke)?ke+f(U,Le):null;let Se=g(Ne,_(U,Le));Se==null&&(Se=ve??1e4),ve=Se,ye.push(Cesium.Cartesian3.fromDegrees(Le,U,Se))}e._trailPositions=ye.concat(e._trailPositions),e._trailPositions.length>ku&&(e._trailPositions=e._trailPositions.slice(e._trailPositions.length-ku)),G()}function H(){if(e._trailBackfillToken+=1,e._trailPositions=[],e._trail&&e._trail.clear(),e._trailHeadEntity&&e._viewer&&!e._viewer.isDestroyed())try{e._viewer.entities.remove(e._trailHeadEntity)}catch{}e._trailHeadEntity=null}function B(){H(),e._trail&&(e._trail.destroy(),e._trail=null)}function q(Y=!1,{evicted:K=!1,origin:_e="programmatic"}={}){var Ce,ye;if((Ce=e._trackedCameraFrameStop)==null||Ce.call(e),e._trackedCameraFrameStop=null,!e._trackedIcao){m("flights");return}const he=e._trackedIcao;if(m("flights",he),e._billboards.has(e._trackedIcao)){const ve=e._billboards.get(e._trackedIcao);ve.show=!0,ve.width=20,ve.height=20,ve.color=n.rendering._fleetBillboardColor(e._trackedIcao),ve.scale=n.rendering._fleetBillboardScale(e._trackedIcao,(ye=e.records.data.get(e._trackedIcao))==null?void 0:ye.klass),ve.rotation=e._lastTrackedRotation}e._lastCamPoseSig="",e._viewer&&!Y&&(e._viewer.trackedEntity=void 0),e._trackedEntity&&(e._viewer.entities.remove(e._trackedEntity),e._trackedEntity=null),n.rendering._releaseTrackedModel(),P(),e._trackedIcao=null,n.rendering._applyFleetBillboardPresentation(he,e._billboards.get(he)),s("flights"),T("gev:awareness-subject-cleared",{layerId:"flights",id:he,origin:_e,reason:K?"evicted":"deliberate"}),n.motion._resetTrackedDisplay(),H()}function z(Y){var K;return!(!b()||Y===e._trackedIcao||Y===((K=e._pendingTrackingRestore)==null?void 0:K.id))}function j(){var K;const Y=e._pendingTrackingRestore;return!Y||Y.generation!==e._trackingIntentGeneration||!((K=e._billboardCollection)!=null&&K.show)||!e._billboards.has(Y.id)?!1:(e._pendingTrackingRestore=null,Z(Y.id,{origin:Y.origin}),!0)}function ne(){e._trackingIntentGeneration+=1,e._pendingTrackingRestore=null}function ee(Y){const K=e.records.data.get(Y);if(!K)return Y;const _e=n.queries._contactLabel(Y,K),he=Math.round((K.altitude||0)*3.28084),Ce=he>=18e3?`FL${Math.round(he/100)}`:`${he} ft`,ye=K.velocity?`${Math.round(K.velocity*1.944)} kts`:"",ve=e.records.missingPolls.get(Y)||e.feed._backoff?"STALE":"",pe=[[_e,Ce,ye,ve].filter(Boolean).join(" · ")],te=c(Y)?l(Y):[K.airline,K.typeName||K.typeCode].filter(Boolean).join(" · ");return te&&pe.push(te),K.route&&J(Y,K.route)&&pe.push(`${K.route.origin.code} → ${K.route.destination.code}`),pe.join(` +`)}function re(Y){!e._trackedEntity||Y!==e._trackedIcao||(e._trackedEntity.gevLabelModel=y(ee(Y),"#39d0ff"),v(e._trackedEntity),a(R(Y)))}function se(){var Y,K;!e._trackedIcao||!((Y=e._trackedEntity)!=null&&Y.billboard)||(e._trackedEntity.billboard.image=Nn(n.rendering._iconKind(e._trackedIcao,(K=e.records.data.get(e._trackedIcao))==null?void 0:K.klass),Di))}function me(Y){var he,Ce,ye;const K=String(Y||"").trim().toLowerCase();if(!K)return!1;if(c(K)){(e._models.has(K)||e._modelPending.has(K))&&n.rendering._releaseModel(K);const ve=e._billboards.get(K);ve&&K!==e._trackedIcao&&(ve.show=!0),K===e._trackedIcao&&(n.rendering._releaseTrackedModel(),x())}const _e=e._billboards.get(K);return _e&&n.rendering._applyFleetBillboardPresentation(K,_e),K===e._trackedIcao&&(se(),re(K)),(ye=(Ce=(he=e._viewer)==null?void 0:he.scene)==null?void 0:Ce.requestRender)==null||ye.call(Ce),e._billboards.has(K)||K===e._trackedIcao}function be(){for(const Y of u())(e._billboards.has(Y)||Y===e._trackedIcao)&&me(Y)}function J(Y,K){const _e=e.records.data.get(Y),he=e._billboards.get(Y);if(!_e||!he||!he.position)return!0;const Ce=Cesium.Cartographic.fromCartesian(he.position,Cesium.Ellipsoid.WGS84,e._scratchCarto);return Ce?PI({latDeg:Cesium.Math.toDegrees(Ce.latitude),lonDeg:Cesium.Math.toDegrees(Ce.longitude),altitudeM:_e.altitude??null,verticalRateMps:_e.verticalRate??null,origin:K.origin,destination:K.destination}):!0}function Z(Y,{origin:K="programmatic"}={}){var pe,te;q(!1,{origin:K});const _e=e._billboards.get(Y),he=e.records.data.get(Y);if(!_e||!he)return;e._trackedIcao=Y,P(),e._cachedDRFrame=-1,e._lastTrackedRotation=_e.rotation||0,n.rendering._releaseModel(Y),_e.show=!1;const Ce=()=>n.motion._trackedDisplayPosition(Y)||_e.position,ye=new Cesium.CallbackProperty(()=>Ce(),!1);e._trackedEntity=e._viewer.entities.add({position:ye,trackingReferenceFrame:Cesium.TrackingReferenceFrame.ENU,billboard:{image:Nn(n.rendering._iconKind(e._trackedIcao,(pe=e.records.data.get(e._trackedIcao))==null?void 0:pe.klass),Di),width:28,height:28,scale:Oi[(te=e.records.data.get(e._trackedIcao))==null?void 0:te.klass]||1,color:new Cesium.CallbackProperty(()=>n.rendering._modelOwnsVisual(e._trackedIcao)?dy:Cesium.Color.CYAN,!1),sizeInMeters:!1,scaleByDistance:new Cesium.NearFarScalar(1e3,3,8e6,.5),alignedAxis:Cesium.Cartesian3.ZERO,disableDepthTestDistance:Number.POSITIVE_INFINITY,rotation:new Cesium.CallbackProperty(()=>{const de=e.records.data.get(e._trackedIcao),U=Ce();if(!de||!U||!e._viewer)return e._lastTrackedRotation;const Le=ri(e._viewer.scene,U,n.motion._trackedDisplayCourse(),e._lastTrackedRotation),ke=Dl(e._lastTrackedRotation,Le);return ke!==null&&(e._lastTrackedRotation=ke),e._lastTrackedRotation},!1)}}),e._trackedEntity.gevSelectionOrigin=K,e._trackedEntity.gevTrackedId=`flights:${Y}`,e._trackedEntity.gevLabelModel=y(ee(Y),"#39d0ff");const ve=Math.min(Math.max((he.altitude||1500)*1.1+2500,3e3),3e4);e._trackedEntity.viewFrom=new Cesium.Cartesian3(0,-ve*.8,ve*.55),e._trackedEntity.gevDisplayPosition=n.motion._trackedDisplayCached,e._trackedEntity.gevVisualPosition=n.motion._trackedVisualCached,v(e._trackedEntity),e._viewer.camera.cancelFlight(),e._viewer.trackedEntity=e._trackedEntity,e._trackedCameraFrameStop=M(e._viewer,e._trackedEntity,e._trackedEntity.viewFrom)||null,n.enrichment._requestTypeEnrichment(Y,!0),n.enrichment._requestRouteEnrichment(Y),W(Y),I(Y,K),console.log(`[Data:Flights] Tracking ${n.queries._contactLabel(Y,he)} (${Y})`)}function ae(Y){if(!(!e._viewer||!e._billboardCollection))if(Y){for(const[K,_e]of e._billboards)!C(K)||K===e._trackedIcao||(e._billboardCollection.remove(_e),e._billboards.delete(K),n.rendering._releaseModel(K),e.records.data.delete(K),e._cullPositions.delete(K),e._positionHistory.delete(K),e._displayCourse.delete(K),e._groundSnap.forget(K),e.records.missingPolls.delete(K));e.feed._count=e._billboards.size}else e._billboardCollection.show&&k.update(e._viewer)}function oe(Y){Y.key==="Escape"&&e._trackedIcao&&(ne(),q(!1,{origin:"user"}))}function le(Y){e._clickHandler||(e._trackedEntityChangedRemove||(e._trackedEntityChangedRemove=Y.trackedEntityChanged.addEventListener(()=>{var K;e._trackedIcao&&e._viewer&&e._viewer.trackedEntity&&e._viewer.trackedEntity!==e._trackedEntity&&q(!0,{origin:((K=e._viewer.trackedEntity)==null?void 0:K.gevSelectionOrigin)||"programmatic"})})),e._clickHandler=new Cesium.ScreenSpaceEventHandler(Y.scene.canvas),Ff(e._clickHandler,(K,_e)=>{var Ce;if(!Pf(_e)||document.body.classList.contains("cockpit-mode"))return;const he=Y.scene.pick(K.position);if(he){if(he.id===e._trackedEntity)return;if(e._trackedIcao){const ve=typeof he.id=="string"?he.id:(Ce=he.primitive)==null?void 0:Ce.id;if(he.primitive===e._trackedModel||ve===e._trackedIcao)return}const ye=he.primitive;if(ye&&ye.id&&e._billboards.has(ye.id)){ne(),Z(ye.id,{origin:"user"});return}if(he.id&&typeof he.id=="string"&&e._billboards.has(he.id)){ne(),Z(he.id,{origin:"user"});return}}if(he){const ye=w(he);if(ye&&E("flights",ye))return}xf(_e)&&e._trackedIcao&&(ne(),q(!1,{origin:"user"}))}),document.addEventListener("keydown",oe))}return{_emitAwarenessEvent:T,_publishTrackedSelection:I,_contextSubjectMetadata:R,_isExplicitTrackingOrigin:S,_refreshCockpitNearContacts:A,_setCockpitContactMode:L,_applyCockpitState:F,_resetTrackedSelectionState:P,_trackedModelLoadAllowed:O,_noteTrackedModelLoadFailure:D,_trackedModelRegimeActive:$,_syncTracked2dRotation:x,_appendTrailFix:N,_refreshTrailDisplay:G,_startTrail:W,_backfillTrail:V,_clearTrail:H,_destroyTrail:B,_clearTracking:q,_militaryLayerSuppresses:z,_applyPendingTrackingRestore:j,_cancelPendingTrackingRestore:ne,_trackedLabelText:ee,_updateTrackedLabelModel:re,_syncTrackedBillboardImage:se,_refreshTr3bContact:me,_refreshTr3bForStyle:be,_routeIsPlausible:J,_trackFlight:Z,_onMilitaryActiveChange:ae,_onKeyDown:oe,_installClickHandler:le}}function HI({flightState:e,services:t,parts:n,layer:i,resolveAsset:o}){function r(){for(const a of e.feed._activeUpdateControllers)a.abort();e.feed._activeUpdateControllers.clear()}function s(a){var l;const c=(l=a==null?void 0:a.camera)==null?void 0:l.positionCartographic;return c?{latitude:Cesium.Math.toDegrees(c.latitude),longitude:Cesium.Math.toDegrees(c.longitude)}:{}}return{_abortActiveUpdates:r,_flightQuery:s}}function $I({flightState:e,services:t,parts:n,layer:i,resolveAsset:o}){function r(d,f,p,g=!1){if(e.lifetime.signal.aborted||e._enrichSeen.has(d))return;e._enrichSeen.add(d);const _={query:f,onData:p};g?e._enrichQueue.unshift(_):e._enrichQueue.push(_),s()}function s(){if(!e.lifetime.signal.aborted)for(;e._enrichActive0){e._enrichDripTimer||(e._enrichDripTimer=setTimeout(()=>{e._enrichDripTimer=null,s()},d));return}e._enrichLastDispatchMs=Date.now();const f=e._enrichQueue.shift();e._enrichActive+=1;const p=e.lifetime;Promise.resolve().then(()=>{var g,_;return p.signal.throwIfAborted(),(_=(g=e.feed._source).getEnrichment)==null?void 0:_.call(g,f.query,{signal:p.signal})}).then(g=>{!p.signal.aborted&&g&&g.found&&f.onData(g)}).catch(()=>{}).finally(()=>{p.signal.aborted||(e._enrichActive-=1,s())})}}function a(d,f=!1){/^[0-9a-f]{6}$/i.test(d)&&r(`t:${d}`,{kind:"type",id:d.toLowerCase()},p=>{const g=e.records.data.get(d);if(g){if(g.typeCode=p.typeCode||g.typeCode,g.typeName=p.typeName||g.typeName,g.registration=p.registration||g.registration,g.typeCode){const _=Lf({typeCode:g.typeCode,category:g.category});if(_!==g.klass){g.klass=_;const m=e._billboards.get(d);m&&n.rendering._applyFleetBillboardPresentation(d,m),n.rendering._syncModelToClass(d)}}d===e._trackedIcao&&e._trackedEntity&&n.tracking._updateTrackedLabelModel(d)}},f)}function c(d){var p;const f=String(((p=e.records.data.get(d))==null?void 0:p.callsign)||"").trim().toUpperCase();/^[A-Z]{3}\d/.test(f)&&r(`r:${f}`,{kind:"route",id:f},g=>{const _=e.records.data.get(d);_&&(_.airline=g.airline||_.airline,g.origin&&g.destination&&(_.route={origin:g.origin,destination:g.destination}),d===e._trackedIcao&&e._trackedEntity&&n.tracking._updateTrackedLabelModel(d))},!0)}function l(){const d=typeof window<"u"&&window.__GEV_ENRICH_AMBIENT_QA||null;return{ceil:Number.isFinite(d==null?void 0:d.ceil)&&d.ceil>0?d.ceil:my,refillTokens:Number.isFinite(d==null?void 0:d.refillTokens)&&d.refillTokens>0?d.refillTokens:QA,windowMs:Number.isFinite(d==null?void 0:d.windowMs)&&d.windowMs>0?d.windowMs:ZA}}function u(d){const{ceil:f,refillTokens:p,windowMs:g}=l();if(!e._enrichAmbientRefillAnchorMs){e._enrichAmbientRefillAnchorMs=d;return}const _=Math.floor((d-e._enrichAmbientRefillAnchorMs)/g);_<=0||(e._enrichAmbientBudget=Math.min(f,e._enrichAmbientBudget+_*p),e._enrichAmbientRefillAnchorMs+=_*g)}function h(){var d;if(u(Date.now()),!(e._enrichAmbientBudget<=0||!e._viewer||!e._billboardCollection||!e._billboardCollection.show))try{const f=e._viewer.camera,p=f.positionWC,g=Vo(f),_=f.frustum.computeCullingVolume(p,f.directionWC,f.upWC),m=[];for(const[C,y]of e._billboards)e._enrichSeen.has(`t:${C}`)||/^[0-9a-f]{6}$/i.test(C)&&((d=e.records.data.get(C))!=null&&d.onGround||!y.position||!g.isPointVisible(y.position)||(Cesium.Cartesian3.clone(y.position,e._scratchModelBS.center),_.computeVisibility(e._scratchModelBS)!==Cesium.Intersect.OUTSIDE&&m.push([C,Cesium.Cartesian3.distanceSquared(p,y.position)])));m.sort((C,y)=>C[1]-y[1]);const b=Math.min(m.length,JA,e._enrichAmbientBudget);for(let C=0;C{if(b===e._modelEpoch)e._preloadModel=C,e._planeModelLoaded=!0;else try{C.destroy()}catch{}}).catch(()=>{})}e._billboards=new Map,e._cullPositions.clear(),e._detectionObjects=new Map,e.records.data=new Map,e._positionHistory=new Map,e._displayCourse.clear(),e._groundSnap.clear(),e.feed._count=0,e.feed._lastUpdate=null,e.feed._backoff=!1,e.feed._retryAt=0,e.feed._lastError=null,e.feed._lastStatus=null,e.feed._lastSource=e.feed._source.label||"Aircraft",e.feed._lastCoverage="worldwide upstream snapshot",e._trackedIcao=null,n.tracking._resetTrackedSelectionState(),e._trackedEntity=null,e._cockpitSubjectId=null,e._cockpitContactMode=document.body.classList.contains("cockpit-mode"),e._cockpitNearContacts=new Set,e._cockpitModeListener||(e._cockpitModeListener=b=>n.tracking._applyCockpitState(b==null?void 0:b.detail),window.addEventListener("gev:cockpit-mode-changed",e._cockpitModeListener)),e._enrichAmbientBudget=n.enrichment._ambientBudgetKnobs().ceil,e._enrichAmbientRefillAnchorMs=0,n.tracking._installClickHandler(_),e._milActiveChangeUnsub||(e._milActiveChangeUnsub=l(n.tracking._onMilitaryActiveChange)),a(_),console.log("[Data:Flights] Initialized with billboard icons")},enable(_){if(e._billboardCollection&&(e._billboardCollection.show=!0),u("flights"),e._modelCollection&&(e._modelCollection.show=!0),n.tracking._setCockpitContactMode(document.body.classList.contains("cockpit-mode")),!e.records.geoidReady){const m=e.lifetime;d().then(()=>{m.signal.aborted||(e.records.geoidReady=!0)}).catch(()=>{})}n.tracking._installClickHandler(_),f("flights",m=>e._billboards.has(m)),e._lastCamPoseSig="",!e._preRenderRemove&&(_!=null&&_.scene)&&(e._preRenderRemove=_.scene.preRender.addEventListener(n.rendering._fleetTick)),!e._trackedModelPreUpdateRemove&&(_!=null&&_.scene)&&(e._trackedModelPreUpdateRemove=_.scene.preUpdate.addEventListener(n.rendering._updateTrackedModel)),!e._moveEndRemove&&(_!=null&&_.camera)&&(e._moveEndRemove=_.camera.moveEnd.addEventListener(()=>{e._lastCamPoseSig="",e._lastFleetTickMs=0})),c("flights",_)},disable(_){n.controller._abortActiveUpdates(),n.tracking._cancelPendingTrackingRestore(),e._billboardCollection&&(e._billboardCollection.show=!1),h("flights"),n.rendering._releaseModels(),e._modelCollection&&(e._modelCollection.show=!1),n.tracking._clearTracking(),n.tracking._destroyTrail(),e._clickHandler&&(e._clickHandler.destroy(),e._clickHandler=null),e._trackedEntityChangedRemove&&(e._trackedEntityChangedRemove(),e._trackedEntityChangedRemove=null),document.removeEventListener("keydown",n.tracking._onKeyDown),p("flights"),e._preRenderRemove&&(e._preRenderRemove(),e._preRenderRemove=null),e._trackedModelPreUpdateRemove&&(e._trackedModelPreUpdateRemove(),e._trackedModelPreUpdateRemove=null),e._moveEndRemove&&(e._moveEndRemove(),e._moveEndRemove=null)},destroy(_){if(e.lifetime.abort(),e._enrichActive=0,e._enrichLastDispatchMs=0,n.controller._abortActiveUpdates(),h("flights"),n.tracking._clearTracking(),n.tracking._destroyTrail(),n.tracking._cancelPendingTrackingRestore(),e._clickHandler&&(e._clickHandler.destroy(),e._clickHandler=null),e._trackedEntityChangedRemove&&(e._trackedEntityChangedRemove(),e._trackedEntityChangedRemove=null),e._milActiveChangeUnsub&&(e._milActiveChangeUnsub(),e._milActiveChangeUnsub=null),document.removeEventListener("keydown",n.tracking._onKeyDown),e._cockpitModeListener&&(window.removeEventListener("gev:cockpit-mode-changed",e._cockpitModeListener),e._cockpitModeListener=null),p("flights"),e._preRenderRemove&&(e._preRenderRemove(),e._preRenderRemove=null),e._trackedModelPreUpdateRemove&&(e._trackedModelPreUpdateRemove(),e._trackedModelPreUpdateRemove=null),e._moveEndRemove&&(e._moveEndRemove(),e._moveEndRemove=null),n.rendering._releaseModels(),e._billboardCollection&&(_.scene.primitives.remove(e._billboardCollection),e._billboardCollection=null),e._modelCollection&&(_.scene.primitives.remove(e._modelCollection),e._modelCollection=null),e._modelEpoch+=1,e._modelPending.clear(),e._modelGen.clear(),e._preloadModel){try{e._preloadModel.destroy()}catch{}e._preloadModel=null}e._planeModelLoaded=!1,e._billboards.clear(),e._cullPositions.clear(),e._detectionObjects.clear(),e.records.data.clear(),e._positionHistory.clear(),e._displayCourse.clear(),e._groundSnap.clear(),e._displayFloorState.clear(),e._enrichQueue.length=0,e._enrichSeen.clear(),e._enrichDripTimer&&(clearTimeout(e._enrichDripTimer),e._enrichDripTimer=null),e.records.missingPolls.clear(),e._focusEvidenceIds.clear(),e.feed._count=0,e.feed._lastUpdate=null,e._cockpitContactMode=!1,e._cockpitNearContacts=new Set,e._cockpitSubjectId=null,e.feed._trackingRefreshEpoch+=1,e.feed._lastTrackingRefreshOutcome={epoch:e.feed._trackingRefreshEpoch,status:"destroyed",ids:new Set,source:e.feed._lastSource,coverage:e.feed._lastCoverage},n.tracking._resetTrackedSelectionState(),e._viewer=null}}}}function UI({flightState:e,services:t,parts:n,layer:i,resolveAsset:o}){function r(l){const u=l==null?void 0:l.cartesian;return Array.isArray(u)&&u.length>=3&&u.slice(0,3).every(Number.isFinite)?Cesium.Cartesian3.fromElements(u[0],u[1],u[2]):!Number.isFinite(l==null?void 0:l.longitude)||!Number.isFinite(l==null?void 0:l.latitude)?null:Cesium.Cartesian3.fromDegrees(l.longitude,l.latitude,Number.isFinite(l.altitudeM)?l.altitudeM:3e3)}function s(l=[]){return{ok:!1,count:0}}function a(l=[]){return{ok:!1,moved:0}}function c(){return[]}return{_focusEvidencePosition:r,_setFocusEvidenceAircraft:s,_moveFocusEvidenceAircraft:a,_focusEvidenceSnapshot:c}}function zI({flightState:e,services:t,parts:n,layer:i,resolveAsset:o}){function r(y,v,M,w="__test__",E=Date.now()){return n.motion._floorGroundedDisplayPosition(w,y,v,M,E)}function s(){e._displayFloorState.clear()}function a({icao24:y,entity:v,meta:M,billboard:w,billboardCollection:E,viewer:k,history:T=[],tracked:I=!0,models:R=[],modelCollection:S=null}){e._viewer=k,e._modelCollection=S,e._billboardCollection=E,e._billboards=new Map([[y,w]]),e._cullPositions.clear(),e._models.clear();for(const[A,L]of R)e._models.set(A,L);e._detectionObjects=new Map,e.records.data=new Map([[y,M]]),e._positionHistory=new Map([[y,T]]),e.records.missingPolls=new Map,e._displayCourse.clear(),e.records.geoidNCache.clear(),e._trackedIcao=I?y:null,e._trackedEntity=I?v:null,e._trackedModel=null,n.tracking._cancelPendingTrackingRestore(),e._trackedModelLoading=!1,e.feed._backoff=!1,e.feed._retryAt=0}function c({status:y="accepted",ids:v=[],source:M="OpenSky Network",coverage:w="test"}={}){const E=++e.feed._trackingRefreshEpoch;e.feed._lastTrackingRefreshOutcome={epoch:E,status:y,ids:new Set(v.map(k=>String(k).trim().toLowerCase())),source:M,coverage:w}}function l({icao24:y,meta:v,billboard:M,history:w=[]}){e._billboards.set(y,M),e.records.data.set(y,v),e._positionHistory.set(y,w)}function u(y){return n.tracking._militaryLayerSuppresses(y)}function h(y,v="share-restore"){e._pendingTrackingRestore=y===null?null:{id:y,generation:e._trackingIntentGeneration,origin:v}}function d(){var y;return((y=e._pendingTrackingRestore)==null?void 0:y.id)??null}function f(){return n.tracking._applyPendingTrackingRestore()}function p(y,v=null){n.tracking._applyCockpitState({active:y,subjectId:v})}function g(){return n.tracking._trackedModelRegimeActive()}function _(){return n.rendering._updateTrackedModel()}function m(){return n.rendering._modelOwnsVisual(e._trackedIcao)?dy:Cesium.Color.CYAN}function b({icao24:y,position:v,course:M=0}){return n.rendering._driveFleetModelHandoff(y,e._models.get(y),e._billboards.get(y),v,M)}async function C(y){return await n.rendering._ensureModel(y),e._models.get(y)||null}return{_floorGroundedDisplayPositionForTest:r,_clearDisplayFloorStateForTest:s,_setTrackedFlightRefreshStateForTest:a,_setFlightTrackingRefreshOutcomeForTest:c,_addFlightTrackingCandidateForTest:l,_militaryLayerSuppressesForTest:u,_armFlightTrackingRestoreForTest:h,_pendingFlightTrackingRestoreForTest:d,_applyPendingFlightTrackingRestoreForTest:f,_setCockpitDetectionSubjectForTest:p,_trackedModelRegimeActiveForTest:g,_updateTrackedModelForTest:_,_trackedBillboardColorForTest:m,_driveFleetModelHandoffForTest:b,_ensureFleetModelForTest:C}}const Qt=Object.freeze({HEX_EXACT:0,CALLSIGN_EXACT:1,REGISTRATION_EXACT:2,CALLSIGN_PREFIX:3,REGISTRATION_PREFIX:4,CALLSIGN_SUBSTRING:5,REGISTRATION_SUBSTRING:6,NONE:Number.POSITIVE_INFINITY});function Up(e){return String(e??"").replace(/[^a-z0-9]/gi,"").toUpperCase()}function wy({query:e,hex:t="",callsign:n="",registration:i=""}){const o=String(e??"").trim().toLowerCase();if(!o)return Qt.NONE;if(String(t??"").trim().toLowerCase()===o)return Qt.HEX_EXACT;const r=String(n??"").trim().toLowerCase();if(r&&r===o)return Qt.CALLSIGN_EXACT;const s=Up(o),a=Up(i);return s&&a===s?Qt.REGISTRATION_EXACT:r&&r.startsWith(o)?Qt.CALLSIGN_PREFIX:s&&a.startsWith(s)?Qt.REGISTRATION_PREFIX:r&&r.includes(o)?Qt.CALLSIGN_SUBSTRING:s&&a.includes(s)?Qt.REGISTRATION_SUBSTRING:Qt.NONE}function Ey(e,t){return!e||e.tier===Qt.NONE?!1:t?e.tier!==t.tier?e.tierNumber.isFinite(O)?O:null,R=O=>String(O??"").trim()||null,S=R(E==null?void 0:E.callsign);return{id:S||R(E==null?void 0:E.registration)||w,icao24:w,callsign:S,lat:I(E==null?void 0:E.rawLat),lon:I(E==null?void 0:E.rawLon),altitudeM:I(E==null?void 0:E.altitude),speedMps:I(E==null?void 0:E.velocity),heading:I(E==null?void 0:E.true_track),verticalRateMps:I(E==null?void 0:E.verticalRate),onGround:(E==null?void 0:E.onGround)===!0,military:k,aircraftClass:s(w,R(E==null?void 0:E.klass)),originCountry:R(E==null?void 0:E.originCountry),operator:R(E==null?void 0:E.airline),routeOrigin:T?R((L=(A=E==null?void 0:E.route)==null?void 0:A.origin)==null?void 0:L.code):null,routeDestination:T?R((P=(F=E==null?void 0:E.route)==null?void 0:F.destination)==null?void 0:P.code):null}}const M={mapAnalystRecord:v,id:"flights",name:"Live Flights",icon:"✈️",source:e.feed._lastSource,_clearDisplayFloorStateForTest:n.testing._clearDisplayFloorStateForTest,updateInterval:3e4,setParams(w={},{origin:E="programmatic"}={}){if(Mo(E)&&!Object.hasOwn(w,"selectedFlightsTrackingId")&&n.tracking._cancelPendingTrackingRestore(),typeof w.models3d=="boolean"&&w.models3d!==e._models3dEnabled&&(e._models3dEnabled=w.models3d,!e._models3dEnabled&&(n.rendering._releaseModels(),n.tracking._syncTracked2dRotation(),e._billboardCollection)))for(const[k,T]of e._billboards)k!==e._trackedIcao&&(T.show=!0);if((w.models3dMode==="proximity"||w.models3dMode==="all")&&w.models3dMode!==e._models3dMode&&(e._models3dMode=w.models3dMode,e._cockpitContactMode&&(n.tracking._refreshCockpitNearContacts(),e._lastFleetTickMs=0)),typeof w.irBoost=="boolean"&&w.irBoost!==e._irBoost&&(e._irBoost=w.irBoost,n.rendering._reloadModelsForIrBoost(),n.tracking._refreshTr3bForStyle()),Object.hasOwn(w,"selectedFlightsTrackingId")){const k=y(w.selectedFlightsTrackingId);if(k===e._trackedIcao)e._pendingTrackingRestore=null;else if(k===null)n.tracking._cancelPendingTrackingRestore(),e._trackedIcao&&n.tracking._clearTracking(!1,{origin:E});else{const T=++e._trackingIntentGeneration;e._pendingTrackingRestore={id:k,generation:T,origin:E},e._trackedIcao&&n.tracking._clearTracking(!1,{origin:E}),n.tracking._applyPendingTrackingRestore()}}return!0},getParams(){return{models3d:e._models3dEnabled,models3dMode:e._models3dMode,irBoost:e._irBoost,selectedFlightsTrackingId:e._trackedIcao}},refreshTr3b(w){return n.tracking._refreshTr3bContact(w)},getDetectableObjects(w={}){if(!e._billboardCollection||!e._billboardCollection.show)return[];const E=Number.isFinite(w.maxCount)?Math.max(1,Math.floor(w.maxCount)):e._billboards.size,k=Number.isFinite(w.seed)?Math.floor(w.seed):0,T=Math.max(1,Math.ceil(e._billboards.size/E)),I=k%T,R=[];let S=0;for(const[A,L]of e._billboards){const F=(S-I)%T===0;if(S++,!F||e._cockpitContactMode&&A.toLowerCase()===e._cockpitSubjectId)continue;const P=A===e._trackedIcao,O=e._models.get(A),D=n.rendering._modelOwnsVisual(A);if(!P&&!L.show&&!D)continue;const $=e.records.data.get(A);let x=e._detectionObjects.get(A);x||(x={sourceId:A,type:"AIR",_weldPos:new Cesium.Cartesian3},e._detectionObjects.set(A,x));const N=D?n.rendering._modelSpec($==null?void 0:$.klass):null,G=P?n.motion._trackedVisualCached()||L.position:D?jc(O.modelMatrix,N.visualCenterNative,Number.isFinite(O.computedScale)?O.computedScale:N.scale,x._weldPos||(x._weldPos=new Cesium.Cartesian3)):L.position;if(!G)continue;x.position=G,x.skipLabel=P;const W=b(A,$);x.id!==W&&(x.id=W);const V=$==null?void 0:$.altitude;if(x._altitude!==V&&(x._altitude=V,x.metric=a(V)),R.push(x),R.length>=E)break}if(e._detectionObjects.size>e._billboards.size+512)for(const A of e._detectionObjects.keys())e._billboards.has(A)||e._detectionObjects.delete(A);return R},findByQuery(w){if(!e.records.data||e.records.data.size===0)return null;const E=String(w||"").trim().toLowerCase();if(!E)return null;let k=null;for(const[T,I]of e.records.data){const R={tier:wy({query:E,hex:T,callsign:I==null?void 0:I.callsign,registration:I==null?void 0:I.registration}),id:T};if(Ey(R,k)&&(k=R,R.tier===Qt.HEX_EXACT))break}return k?C(k.id):null},getNearby(w,E,k=50,{includeHidden:T=!1}={}){var A;if(!w||!e._billboardCollection||!e._billboardCollection.show)return[];const I=Number.isFinite(k)?Math.max(1,Math.floor(k)):50,R=Number.isFinite(E)&&E>0?E:Number.POSITIVE_INFINITY;Cesium.JulianDate.now();const S=[];for(const[L,F]of e._billboards){const P=L===e._trackedIcao;if(!Ty({isTracked:P,billboardShown:F.show,modelRendering:n.rendering._modelOwnsVisual(L),includeHidden:T}))continue;const D=(P?n.motion._trackedDisplayCached():null)||F.position;if(!D)continue;const $=Cesium.Cartesian3.distance(w,D);if($>R)continue;const x=e.records.data.get(L),N=((A=x==null?void 0:x.callsign)==null?void 0:A.trim())||null;S.push({id:b(L,x),icao24:L,callsign:N,position:D,distance:$,aircraftClass:s(L,String((x==null?void 0:x.klass)||"").trim().toLowerCase()||null),altitudeM:(x==null?void 0:x.altitude)??null,velocityMps:(x==null?void 0:x.velocity)??null,track:(x==null?void 0:x.true_track)??null})}return S.sort((L,F)=>L.distance-F.distance),S.slice(0,I)},hasContact(w){if(!e._billboardCollection||!e._billboardCollection.show||e._billboards.size===0)return null;if(!w)return!1;const E=String(w).trim();return e._billboards.has(E)||e._billboards.has(E.toLowerCase())},getAllPositions(w=500){if(!e._billboardCollection||e._billboards.size===0)return[];const E=Number.isFinite(w)?Math.max(1,Math.floor(w)):500,k=[];for(const[T,I]of e._billboards){const R=I.position;if(!R)continue;const S=Cesium.Cartographic.fromCartesian(R,Cesium.Ellipsoid.WGS84,e._scratchCarto);if(!S)continue;const A=e.records.data.get(T);if(k.push({id:T,label:b(T,A),position:R,latitude:Cesium.Math.toDegrees(S.latitude),longitude:Cesium.Math.toDegrees(S.longitude),altitudeM:S.height,airline:(A==null?void 0:A.airline)??null,typeName:(A==null?void 0:A.typeName)??null,typeCode:(A==null?void 0:A.typeCode)??null,registration:(A==null?void 0:A.registration)??null,origin:A!=null&&A.route&&n.tracking._routeIsPlausible(T,A.route)?A.route.origin.code:null,destination:A!=null&&A.route&&n.tracking._routeIsPlausible(T,A.route)?A.route.destination.code:null}),k.length>=E)break}return k},getAnalystRecords(w=2e3){if(!e._billboardCollection||!e._billboardCollection.show||e.records.data.size===0)return[];const E=Number.isFinite(w)?Math.max(1,Math.floor(w)):2e3,k=[];for(const[T,I]of e.records.data){const R=!!(I!=null&&I.route)&&n.tracking._routeIsPlausible(T,I.route);if(k.push(v(T,I,{military:c(T),routeOk:R})),k.length>=E)break}return k},trackById(w,{origin:E="programmatic"}={}){if(!w)return!1;let k=String(w).trim();return e._billboards.has(k)||(k=k.toLowerCase()),e._billboards.has(k)?(n.tracking._isExplicitTrackingOrigin(E)&&n.tracking._cancelPendingTrackingRestore(),e._trackedIcao===k?n.tracking._publishTrackedSelection(k,E):(n.tracking._trackFlight(k,{origin:E}),!0)):!1},async resolveTrackingRestoreTarget(w,{signal:E=null,origin:k="share-restore"}={}){if(E!=null&&E.aborted)return{status:"cancelled",reason:String(E.reason||"aborted")};const T=y(w);if(!T)return{status:"missing",reason:"invalid-target"};const I=e.feed._lastTrackingRefreshOutcome;return I.status!=="accepted"?{status:"source-unavailable",reason:"OpenSky snapshot unavailable",refreshEpoch:I.epoch,source:I.source,coverage:I.coverage}:I.ids.has(T)?E!=null&&E.aborted?{status:"cancelled",reason:String(E.reason||"aborted")}:this.trackById(T,{origin:k})?{status:"found",refreshEpoch:I.epoch,source:I.source,coverage:I.coverage}:{status:"source-unavailable",reason:"target-not-renderable",refreshEpoch:I.epoch}:{status:"missing",reason:"target-absent-from-snapshot",refreshEpoch:I.epoch,source:I.source,coverage:I.coverage}},refocusTrackedById(w,{origin:E="programmatic"}={}){var T,I,R;if(!w||e._cockpitContactMode||!e._viewer||!e._trackedEntity)return!1;let k=String(w).trim();return e._billboards.has(k)||(k=k.toLowerCase()),k!==e._trackedIcao||!((I=(T=e._viewer.entities)==null?void 0:T.contains)!=null&&I.call(T,e._trackedEntity))||e._viewer.trackedEntity!==e._trackedEntity?!1:((R=e._trackedCameraFrameStop)==null||R.call(e),e._viewer.camera.cancelFlight(),e._viewer.trackedEntity=e._trackedEntity,e._trackedCameraFrameStop=l(e._viewer,e._trackedEntity,e._trackedEntity.viewFrom)||null,n.tracking._publishTrackedSelection(k,E),!0)},stopTracking({origin:w="programmatic"}={}){return n.tracking._cancelPendingTrackingRestore(),n.tracking._clearTracking(!1,{origin:w}),!0},cancelPendingTrackingRestore(){n.tracking._cancelPendingTrackingRestore()},getTrackedInfo(){if(!e._trackedIcao)return null;const w=C(e._trackedIcao);if(!w)return null;const{position:E,...k}=w;return k},getTrackedSubject(){if(!e._trackedIcao)return null;const w=C(e._trackedIcao);return w!=null&&w.position?{layerId:"flights",id:w.icao24,label:w.callsign||m(w.registration)||w.icao24,position:Cesium.Cartesian3.clone(w.position)}:null},getStats(){const w=e.feed._retryAt?Math.max(0,Math.ceil((e.feed._retryAt-Date.now())/1e3)):0;return{count:e.feed._count,lastUpdate:e.feed._lastUpdate,stale:e.feed._backoff,error:e.feed._lastError,status:e.feed._lastStatus,retryInSec:w,source:e.feed._lastSource,coverage:e.feed._lastCoverage}}};return{_approxDistanceKm:Fd,_likelyLanded:_,_toCleanText:m,_contactLabel:b,_describeFlight:C,_normalizeTrackedIcao:y,mapAnalystRecord:v,methods:M}}function qI({source:e,services:t,resolveAsset:n=i=>i}={}){const i=hI({source:e,services:t}),o={},r={},s={flightState:i,services:t,parts:o,layer:r,resolveAsset:n};o.rendering=MI(s),o.motion=wI(s),o.tracking=VI(s),o.controller=HI(s),o.enrichment=$I(s),o.lifecycle=GI(s),o.evidence=UI(s),o.testing=zI(s),o.queries=jI(s);const a=pA({flightState:i,records:i.records,militaryRegistry:t.militaryRegistry,groundFloor:t.groundFloor,meshFloor:t.meshFloor,rendering:o.rendering,tracking:o.tracking,motion:o.motion,enrichment:o.enrichment,queries:o.queries});return o.ingestion=IA({feed:i.feed,getQuery:c=>o.controller._flightQuery(c||i._viewer),applySnapshot:a,setSourceLabel:c=>{r.source=c},applyPendingTrackingRestore:()=>o.tracking._applyPendingTrackingRestore()}),Object.assign(r,o.queries.methods,o.lifecycle.methods,o.ingestion.methods),Object.defineProperty(r,"testing",{value:o.testing}),r}const Sf=new Map;function WI(e){var i;if(!e)return null;const t=o=>{if(o!=null)return typeof o=="object"?typeof o.mmsi=="string"||typeof o.mmsi=="number"?o.mmsi:typeof o.id=="string"||typeof o.id=="number"?o.id:void 0:o};let n=t(e.id);return n===void 0&&(n=t((i=e.primitive)==null?void 0:i.id)),typeof n=="string"||typeof n=="number"?String(n):null}function ky(e,t){!e||typeof t!="function"||Sf.set(e,t)}function KI(e){Sf.delete(e)}function YI(e,t){if(!t)return!1;for(const[n,i]of Sf)if(n!==e)try{if(i(t))return!0}catch{}return!1}const rn=Object.freeze(Object.defineProperty({__proto__:null,isOwnedByOtherLayer:YI,registerPickOwner:ky,resolvePickId:WI,unregisterPickOwner:KI},Symbol.toStringTag,{value:"Module"})),Nf=Object.freeze(["cctv","firms","bikeshare","transit","transit-motion","directions","ais","military","flights"]),Ol=new Map;function XI(e,t){!e||!t||Ol.set(e,t)}function QI(e,t){t&&Ol.get(e)!==t||Ol.delete(e)}function Ay(e){var i,o,r,s,a;if(!e||(i=e.isDestroyed)!=null&&i.call(e))return;const t=e.scene,n=t==null?void 0:t.primitives;if(!(!n||(o=t.isDestroyed)!=null&&o.call(t)||(r=n.isDestroyed)!=null&&r.call(n)))for(const c of Nf){const l=Ol.get(c);!l||(s=l.isDestroyed)!=null&&s.call(l)||((a=n.contains)==null?void 0:a.call(n,l))!==!1&&n.raiseToTop(l)}}function ZI(e,t,n=Ay){!Nf.includes(e)||typeof n!="function"||n(t)}const Ki=Object.freeze(Object.defineProperty({__proto__:null,SPRITE_LAYER_ORDER:Nf,registerSpriteCollection:XI,restoreSpriteOrder:Ay,restoreSpriteOrderOnEnable:ZI,unregisterSpriteCollection:QI},Symbol.toStringTag,{value:"Module"}));ky("trails",e=>String(e).startsWith("gev-trail:"));let JI=0;const eR=.85,tR=.4,nR=.01;function iR(e,{color:t,width:n=2.5}){const i=Cesium.Color.fromCssColorString(t);let o=[],r=!1,s=!0,a=null;function c(){a||r||!e||e.isDestroyed()||(a=e.entities.add({id:`gev-trail:${++JI}`,show:s,polyline:{positions:new Cesium.CallbackProperty(()=>o,!1),width:n,material:i.withAlpha(eR),depthFailMaterial:i.withAlpha(tR),arcType:Cesium.ArcType.GEODESIC}}))}return{setPositions(l){if(r||!e||e.isDestroyed())return;const u=[];for(const h of Array.isArray(l)?l:[]){if(!h)continue;const d=u[u.length-1];d&&Cesium.Cartesian3.distanceSquared(d,h)=2?u:[],c()},setVisible(l){s=l!==!1,a&&(a.show=s)},clear(){o=[]},destroy(){if(r=!0,o=[],a&&e&&!e.isDestroyed())try{e.entities.remove(a)}catch{}a=null}}}const Df=Object.freeze(Object.defineProperty({__proto__:null,createTrail:iR},Symbol.toStringTag,{value:"Module"})),wo=new Set,Iy="TR-3B",Bl="tr3b";function Ry(e){return String(e??"").trim().toLowerCase()}function Zr(e){const t=Ry(e);return t?wo.has(t):!1}function Ly(e,t){const n=Ry(e);return n?(t===!0?wo.add(n):wo.delete(n),wo.has(n)):!1}function Py(e){return Ly(e,!Zr(e))}function oR(){return[...wo]}function rR(){return wo.size}function sR(){wo.clear()}function aR(e,t,{hot:n=!1}={}){return Zr(e)?n===!0?"tr3bHot":"tr3b":t}function lR(e,t=null){return Zr(e)?Iy:t}function cR(e,t=null){return Zr(e)?Bl:t}const xy=Object.freeze(Object.defineProperty({__proto__:null,TR3B_CLASS:Bl,TR3B_TYPE_LABEL:Iy,clearTr3bRegistry:sR,isTr3b:Zr,setTr3b:Ly,toggleTr3b:Py,tr3bAircraftClass:cR,tr3bConvertedIds:oR,tr3bCount:rR,tr3bIconKind:aR,tr3bTypeLabel:lR},Symbol.toStringTag,{value:"Module"})),uR=120,Fy=150,La=new WeakMap;function dR({baseScale:e,nativeRadiusM:t,rangeM:n,viewportHeightPx:i,fovyRad:o,maximumPixelSize:r}){if(!Number.isFinite(e)||e<=0||!Number.isFinite(t)||t<=0||!Number.isFinite(n)||n<=0||!Number.isFinite(i)||i<=0||!Number.isFinite(o)||o<=0||!Number.isFinite(r)||r<=0)return e;const s=i/(2*Math.tan(o/2)),a=2*t*e*s/n;return a<=r?e:e*(r/a)}function Sy(e,t,n){var o,r;const i=(o=e==null?void 0:e.gevDisplayPosition)==null?void 0:o.call(e);return i?Cesium.Cartesian3.clone(i,n):(r=e==null?void 0:e.position)==null?void 0:r.getValue(t,n)}function hR(e,t){if(!e)return()=>{};let n=La.get(e);return n||(n={originalInertiaZoom:e.inertiaZoom,originalMinimumZoomDistance:e.minimumZoomDistance,owners:new Set},La.set(e,n)),n.owners.add(t),e.inertiaZoom=0,e.minimumZoomDistance=Math.max(n.originalMinimumZoomDistance,Fy),()=>{const i=La.get(e);i&&(i.owners.delete(t),!(i.owners.size>0)&&(e.inertiaZoom=i.originalInertiaZoom,e.minimumZoomDistance=i.originalMinimumZoomDistance,La.delete(e)))}}function Ny(e,t,n=Fy){const i=Cesium.Cartesian3.dot(e.position,t)<=0,o=-Cesium.Cartesian3.dot(e.position,e.direction),r=Cesium.Cartesian3.magnitudeSquared(e.position);return i?(Cesium.Cartesian3.normalize(t,e.position),Cesium.Cartesian3.multiplyByScalar(e.position,n,e.position),!0):o{h||(h=!0,d==null||d(),u())};return d=e.scene.preUpdate.addEventListener(()=>{if(e.isDestroyed()||e.trackedEntity!==t){f();return}if(i+=l?0:1,!l){const p=Sy(t,e.clock.currentTime,r);if(!p){i>=uR&&f();return}const g=Cesium.Transforms.eastNorthUpToFixedFrame(p,Cesium.Ellipsoid.WGS84,o),_=typeof n.getValue=="function"?n.getValue(e.clock.currentTime,s):Cesium.Cartesian3.clone(n,s);if(!_||Cesium.Cartesian3.magnitudeSquared(_)r==null?"":String(r).trim()).filter(r=>r.length>0).join(" · ").slice(0,pR);return{primary:n,secondary:o}}function Oy(e,t,n){if(!Number.isFinite(e)||!(n>0))return 1;const i=t-e;return i<=0?0:i>=n?1:i/n}function Of(e,t,n,i,o){const r=t-i,s=n-o,a=t+i,c=n+o,l=Math.max(4,Math.floor(Math.min(i,o)*.55));e.moveTo(r,s+l),e.lineTo(r,s),e.lineTo(r+l,s),e.moveTo(a-l,s),e.lineTo(a,s),e.lineTo(a,s+l),e.moveTo(a,c-l),e.lineTo(a,c),e.lineTo(a-l,c),e.moveTo(r+l,c),e.lineTo(r,c),e.lineTo(r,c-l)}function By(e){if(e&&e.tier)return e.tier;const t=e&&e.type;return t==="SEA"?"sea":t==="SAT"?"space":t==="VEH"?"vehicle":"civil"}function yR(e,t,n){const u=!!(t&&t.length),h=Js(e,n),d=u?Js(t,n):0,f=Math.max(h,d),p=Math.ceil(7+f+6),g=12,_=u?g+11:0,b=(u?_:g)+3+4;return{w:p,h:b,idBase:g,subBase:_,textX:7,hasSec:u}}function Vy(e,t,n){const h=!!(t&&t.length),d=Js(e,n),f=h?Js(t,n*.9):0,p=d+(h?6+f:0),g=Math.ceil(7+p+6),_=12,m=_+3+4,b=7,C=b+d+6;return{w:g,h:m,baseline:_,primaryX:b,microX:C,hasMicro:h}}function Hy(e,t,n=0){return!e||!Array.isArray(t)?!1:t.some(i=>i&&e.xi.x&&e.yi.y)}function $y(e,t,n,i,o){if(!(i>t)||e<=t)return n;if(e>=i)return o;const r=(e-t)/(i-t);return n+r*(o-n)}function Gy(e,t,n,i=1){var o,r;(o=e.save)==null||o.call(e),e.globalCompositeOperation="source-over",e.globalAlpha=i,e.strokeStyle="#05080C",e.lineWidth=3.25,e.stroke(t),e.strokeStyle=n,e.lineWidth=1.25,e.stroke(t),(r=e.restore)==null||r.call(e)}function Uy(e,t,n,i,o){Of(e,Math.floor(t)+.5,Math.floor(n)+.5,Math.round(i),Math.round(o))}const Bf=Object.freeze(Object.defineProperty({__proto__:null,acquireAlpha:Oy,appendCornerBracket:Of,appendTransitBracket:Uy,composeLabel:CR,formatFlightLevel:_R,formatKnots:bR,measureLabelCard:yR,measureTrackLabel:Vy,monoTextWidth:Js,nearFarScale:$y,paintTransitBracket:Gy,rectIntersectsAny:Hy,resolveTier:By},Symbol.toStringTag,{value:"Module"})),Vf=Object.freeze({paddingPx:18,dimFloor:.25,nearerBehavior:"allow",hysteresisPx:6,distanceHysteresisRatio:.08,attackMs:300,releaseMs:600,writeEpsilon:.005});let wi={...Vf},An=null;const As=new WeakMap,zy=new Cesium.Cartesian2,yt={factor:1,changed:!1,transitioning:!1,active:!1,desired:1};function vi(e,t,n){return Math.min(n,Math.max(t,e))}function fa(e){return!e||e===wi?wi:{...wi,...e}}function jy(e,t,n,i,o,r,s,a){if(!(n!=null&&n.screenRect)||!e||!Number.isFinite(e.x)||!Number.isFinite(e.y))return 1;const c=i.paddingPx-(Number.isFinite(n.paddingPx)?n.paddingPx:0),l=o?i.hysteresisPx:0,u=c+l+Math.max(0,Number.isFinite(r)?r:0),h=c+l+Math.max(0,Number.isFinite(s)?s:0),d=n.screenRect;if(!(e.x>=d.left-u&&e.x<=d.right+u&&e.y>=d.top-h&&e.y<=d.bottom+h))return 1;const p=vi(i.dimFloor,.01,1);if(i.nearerBehavior==="dim")return p;const g=Number.isFinite(n.cameraDistance)?Math.max(0,n.cameraDistance*i.distanceHysteresisRatio):0,_=Number.isFinite(n.cameraDistance)?n.cameraDistance+(a?-g:g):Number.NaN;return!Number.isFinite(t)||!Number.isFinite(_)||t>=_?p:i.nearerBehavior==="partial"?p+(1-p)*.5:1}function Vd(e,t,n,i){const o=vi(Number.isFinite(e)?e:1,i.dimFloor,1),r=vi(Number.isFinite(t)?t:1,i.dimFloor,1);if(Math.abs(r-o)Hd.delete(e)}function $d(e,t=null){An&&(e&&An.ownerLayer!==e||t!=null&&An.id!==t||(An=null))}function kR(){return An}function AR(e,t,n,i,o=!1,r=0,s=r,a=o){const c=fa(i);return jy(e,t,n,c,o,r,s,a)}function IR(e,t,n,i){const o=fa(i);return Vd(e,t,n,o)}function qy(e,{screenPosition:t,cameraDistance:n,nowMs:i,target:o=An,params:r,spriteHalfWidthPx:s=0,spriteHalfHeightPx:a=s}){const c=fa(r);let l=As.get(e);if(!l){if(!o)return yt.factor=1,yt.changed=!1,yt.transitioning=!1,yt.active=!1,yt.desired=1,yt;l={factor:1,desired:1,transitionFrom:1,transitionStartMs:i,wasFarther:!1},As.set(e,l)}const u=Math.max(0,i-l.transitionStartMs),h=Vd(l.transitionFrom,l.desired,u,c),d=jy(t,n,o,c,l.desired<1,s,a,l.wasFarther);d!==l.desired&&(l.transitionFrom=h,l.transitionStartMs=i,l.desired=d);const f=Math.max(0,i-l.transitionStartMs),p=Vd(l.transitionFrom,d,f,c),g=Math.abs(p-l.factor)>c.writeEpsilon;l.factor=p,l.desired=d,l.wasFarther=c.nearerBehavior!=="dim"&&Math.abs(d-c.dimFloor)<=c.writeEpsilon;const _=Math.abs(p-d)>c.writeEpsilon,m=Math.abs(p-1)>c.writeEpsilon;return!o&&!_&&p===1&&As.delete(e),yt.factor=p,yt.changed=g,yt.transitioning=_,yt.active=m,yt.desired=d,yt}function RR(e,t,n,i,o,r=An,s,a=0,c=a){if(!r&&!As.has(e))return yt.factor=1,yt.changed=!1,yt.transitioning=!1,yt.active=!1,yt.desired=1,yt;const l=t&&n?Cesium.SceneTransforms.worldToWindowCoordinates(n,t,zy):null,u=t&&(i!=null&&i.positionWC)?Cesium.Cartesian3.distance(i.positionWC,t):Number.NaN;return qy(e,{screenPosition:l,cameraDistance:u,nowMs:o,target:r,params:s,spriteHalfWidthPx:a,spriteHalfHeightPx:c})}function LR(e,t){return e!=null||Number.isFinite(t)&&t>0}function PR(e,t){if(!e||!Number.isFinite(t))return 1;const n=e.near*e.near,i=e.far*e.far;if(!Number.isFinite(n)||!Number.isFinite(i)||i<=n)return 1;const o=(t*t-n)/(i-n),r=Math.pow(vi(o,0,1),.2);return e.nearValue+(e.farValue-e.nearValue)*r}let Cr=null;function xR(e){return Cr??e}function FR(e){return Cr=Number.isFinite(e)?e:null,Cr}function SR(e){return Cr===null?null:(Cr+=Math.max(0,Number.isFinite(e)?e:0),Cr)}function NR(e){e&&As.delete(e)}function DR(e,t,n){const i=fa(n);return!Number.isFinite(e)||Math.abs(e-t)>i.writeEpsilon}const ma=Object.freeze(Object.defineProperty({__proto__:null,DEFAULT_FOCUS_DEEMPHASIS_PARAMS:Vf,advanceFocusEvidenceNowMs:SR,advanceProjectedSpriteFocus:RR,advanceSpriteFocus:qy,clearFocusTarget:$d,focusAlphaNeedsWrite:DR,focusNowMs:xR,focusPassIsNeeded:LR,focusTargetEmphasis:AR,forgetSpriteFocus:NR,getFocusDeemphasisParams:MR,getFocusTarget:kR,nearFarScalarValueAtDistance:PR,onFocusTargetAppear:TR,publishFocusTargetFromCachedPosition:ER,resetFocusDeemphasisParams:wR,setFocusDeemphasisParams:vR,setFocusEvidenceNowMs:FR,smoothFocusEmphasis:IR},Symbol.toStringTag,{value:"Module"}));let Jt=null,Jr=!1;const Bi=new Set,yr=[],OR=16;function Hf(){var n;if(!Jr||!(Jt!=null&&Jt.scene))return;const e=Bi.size>0,t=Jt.scene;t.requestRenderMode!==!e&&(t.requestRenderMode=!e,e||(n=t.requestRender)==null||n.call(t))}function Wy(e){if(!(e!=null&&e.scene))throw new TypeError("installRenderGovernor requires a Cesium viewer");Jt=e,Jr=!0,e.scene.maximumRenderTimeChange=1/0,Hf()}function ii(e){e&&(Bi.add(e),Hf())}function Vi(e){e&&(Bi.delete(e),Hf())}function qt(e="unspecified"){var t,n;!Jr||!(Jt!=null&&Jt.scene)||(Bi.size===0&&(yr.push({reason:e,at:Date.now()}),yr.length>OR&&yr.shift()),(n=(t=Jt.scene).requestRender)==null||n.call(t))}function Ky(){return{installed:Jr,mode:Bi.size>0?"continuous":"idle",holds:[...Bi].sort(),recentRequests:[...yr]}}function Yy(e){Jt===e&&(Jt=null,Jr=!1,Bi.clear(),yr.length=0)}function BR(){Jt=null,Jr=!1,Bi.clear(),yr.length=0}const Pt=Object.freeze(Object.defineProperty({__proto__:null,_resetRenderGovernorForTest:BR,getRenderGovernorDiagnostics:Ky,governorRequestRender:qt,holdContinuousRender:ii,installRenderGovernor:Wy,releaseContinuousRender:Vi,uninstallRenderGovernor:Yy},Symbol.toStringTag,{value:"Module"})),Xy=1.05,Qy=24,Zy=12,al=.045,Jy=.07,ev=.4,tv=.01,VR=11,HR=36,$R=32,GR=Cesium.Math.toRadians(6),UR=.61,xr=Math.PI*2,nv=30,iv=2e6,ov=1600,zR=1.25;let $f=Jy,Vl=tv;function Fr(e,t,n){return Math.max(t,Math.min(n,e))}function rv({fadeRatio:e,outsideOpacity:t}={}){return Number.isFinite(e)&&($f=Fr(e,0,ev)),Number.isFinite(t)&&(Vl=Fr(t,0,1)),pa()}function pa(){return{fadeRatio:$f,outsideOpacity:Vl}}function es(e,t){const n=Number(e),i=Number(t);if(!(n>0)||!(i>0))return{centerX:0,centerY:0,radius:0,featherPx:0};const o=i*.5*Xy;return{centerX:n*.5,centerY:i*.5,radius:o,featherPx:o*$f}}function jR(e,t,n,i){return si(e,t,es(n,i))}function si(e,t,n){if(!n||!(n.radius>0)||!Number.isFinite(e)||!Number.isFinite(t))return 0;const i=n.featherPx,o=Math.hypot(e-n.centerX,t-n.centerY);if(o<=n.radius)return 1;if(!(i>0)||o>=n.radius+i)return Vl;const r=Fr((o-n.radius)/i,0,1);return 1-(1-Vl)*r}function ea(e){const t=e%xr;return t<0?t+xr:t}function sv(e,t){const n=Math.abs(ea(e)-ea(t));return Math.min(n,xr-n)}function av(e){return e==="normal"}function Gd(e,t,n=0){const i=Math.hypot(e,t);return!Number.isFinite(i)||i=(t?Zy:Qy)}function lv(e,t,n){const i=Cesium.Ellipsoid.WGS84.maximumRadius;if(!Number.isFinite(e)||e<=i||!(t>0)||!Number.isFinite(n)||n<=0||n>=Math.PI)return null;const o=Math.asin(Fr(i/e,0,1)),r=t*.5*Math.tan(o)/Math.tan(n*.5);return Number.isFinite(r)&&r>0?r:null}function cv(e,t,n,i=void 0,o=void 0){var d;const r=e==null?void 0:e.camera,s=e==null?void 0:e.scene;if(!r||!s||!(t>0)||!(n>0))return null;const a=Cesium.Cartesian3.magnitude(r.positionWC);if(!Number.isFinite(a)||a<=Cesium.Ellipsoid.WGS84.maximumRadius)return null;const c=Cesium.Cartesian3.negate(r.positionWC,o||new Cesium.Cartesian3);if(Cesium.Cartesian3.dot(r.directionWC,c)<=0)return null;const l=Cesium.SceneTransforms.worldToWindowCoordinates(s,Cesium.Cartesian3.ZERO,i);if(!l||!Number.isFinite(l.x)||!Number.isFinite(l.y))return null;const u=lv(a,n,(d=r.frustum)==null?void 0:d.fovy);if(!u)return null;const h=es(t,n);return{earthCenterX:l.x,earthCenterY:l.y,earthRadius:u,keyholeCenterX:h.centerX,keyholeCenterY:h.centerY,keyholeRadius:h.radius}}function zp(e,t,n,i,o,r,s){e.save(),e.lineCap="round",e.shadowColor=`rgba(${r}, ${.5*s})`,e.shadowBlur=9;for(let l=0;l<18;l++){const u=l/18,h=(l+1)/18,d=o-.82+.82*2*u,f=o-.82+.82*2*h,p=Math.sin(Math.PI*((u+h)*.5));e.strokeStyle=`rgba(${r}, ${s*p*p})`,e.lineWidth=.7+p*1.25,e.beginPath(),e.arc(t,n,i,d,f),e.stroke()}e.restore()}function qR(e,t,n,i,o,r){const s=t+Math.cos(r)*i,a=n+Math.sin(r)*i;e.save(),e.beginPath(),e.arc(t,n,i+3,0,xr),e.arc(t,n,o,0,xr,!0),e.clip("evenodd"),e.globalCompositeOperation="screen";const c=e.createRadialGradient(s,a,4,s,a,i*.94);c.addColorStop(0,"rgba(255, 222, 126, 0.17)"),c.addColorStop(.22,"rgba(255, 229, 157, 0.085)"),c.addColorStop(.58,"rgba(255, 235, 188, 0.027)"),c.addColorStop(1,"rgba(255, 242, 214, 0)"),e.fillStyle=c,e.fillRect(t-i-4,n-i-4,(i+4)*2,(i+4)*2),e.lineCap="round",e.shadowColor="rgba(255, 232, 171, 0.11)",e.shadowBlur=18;const l=Math.max(1,i-o);for(let u=-2;u<=2;u++){const h=u*.043,d=r+Math.PI+h,f=l*(.7+(2-Math.abs(u))*.07),p=s+Math.cos(d)*f,g=a+Math.sin(d)*f,_=e.createLinearGradient(s,a,p,g);_.addColorStop(0,`rgba(255, 230, 166, ${.075-Math.abs(u)*.011})`),_.addColorStop(1,"rgba(255, 226, 156, 0)"),e.strokeStyle=_,e.lineWidth=u===0?1.8:.9,e.beginPath(),e.moveTo(s,a),e.lineTo(p,g),e.stroke()}e.restore()}function WR(e,t,n,i,o){const r=t+Math.cos(o)*i,s=n+Math.sin(o)*i,a=e.createRadialGradient(r,s,0,r,s,i*.22);a.addColorStop(0,"rgba(63, 214, 255, 0.16)"),a.addColorStop(.42,"rgba(63, 214, 255, 0.055)"),a.addColorStop(1,"rgba(63, 214, 255, 0)"),e.save(),e.globalCompositeOperation="screen",e.fillStyle=a,e.beginPath(),e.arc(r,s,i*.22,0,xr),e.fill(),e.restore()}class uv{constructor(t,{enabled:n=!0,onAutoDisable:i=null}={}){this.viewer=t,this.enabled=!!n,this.visible=!1,this._onAutoDisable=typeof i=="function"?i:null,this._focusInProgress=!1,this._ephemerisDirty=!0,this._ephemerisUpdateCount=0,this._sunAngle=0,this._moonAngle=Math.PI,this._sunOpacity=1,this._moonOpacity=1,this._debug=null,this._nextDrawAt=0,this._renderScale=1,this._sunRenderKey="",this._moonRenderKey="",this._outlineRenderKey="",this._sunInertial=new Cesium.Cartesian3,this._moonInertial=new Cesium.Cartesian3,this._sunFixed=new Cesium.Cartesian3,this._moonFixed=new Cesium.Cartesian3,this._toCenter=new Cesium.Cartesian3,this._screenCenter=new Cesium.Cartesian2,this._fixedMatrix=new Cesium.Matrix3,this._buildDOM(),this._removePostRender=t.scene.postRender.addEventListener(()=>this._draw()),this._ephemerisTimer=setInterval(()=>{this.enabled&&(this._ephemerisDirty=!0,!(typeof document<"u"&&document.hidden)&&qt("celestial-ephemeris"))},6e4),this.setEnabled(this.enabled)}_buildDOM(){this._root=document.createElement("div"),this._root.id="celestial-ring-overlay",this._root.className="celestial-ring-overlay",this._root.setAttribute("aria-hidden","true"),this._ringOutline=document.createElement("div"),this._ringOutline.className="celestial-ring-outline",this._sunCanvas=document.createElement("canvas"),this._sunCanvas.className="celestial-ring-canvas celestial-sun-canvas",this._sunCtx=this._sunCanvas.getContext("2d",{alpha:!0,desynchronized:!0}),this._moonCanvas=document.createElement("canvas"),this._moonCanvas.className="celestial-ring-canvas celestial-moon-canvas",this._moonCtx=this._moonCanvas.getContext("2d",{alpha:!0,desynchronized:!0}),this._sunMarker=document.createElement("span"),this._sunMarker.className="celestial-marker celestial-sun material-symbols-outlined",this._sunMarker.textContent="light_mode",this._moonMarker=document.createElement("span"),this._moonMarker.className="celestial-marker celestial-moon material-symbols-outlined",this._moonMarker.textContent="dark_mode",this._root.append(this._ringOutline,this._sunCanvas,this._moonCanvas,this._sunMarker,this._moonMarker),this.viewer.container.appendChild(this._root)}setEnabled(t){const n=this.enabled;this.enabled=!!t,this.enabled&&!n&&(this._ephemerisDirty=!0),this.enabled!==n&&qt("celestial-ring"),this._root.classList.toggle("disabled",!this.enabled),this.enabled||(this.visible=!1,this._root.classList.remove("visible"),this._clear())}isGlobeFullyVisible(){const t=this.viewer.scene.canvas,n=t.clientWidth||t.width,i=t.clientHeight||t.height;if(!(n>0&&i>0))return!1;const o=this._projectedEarthDisc(n,i);return!!o&&Ud(o,!1)}focusFullGlobe({duration:t=2.4}={}){var f;const n=this.viewer.scene.canvas,i=n.clientHeight||n.height,o=this.viewer.camera.positionCartographic,r=(f=this.viewer.camera.frustum)==null?void 0:f.fovy;if(!(i>0)||!o||!Number.isFinite(r)||r<=0||r>=Math.PI)return!1;const s=Cesium.Ellipsoid.WGS84.maximumRadius,c=es(n.clientWidth||n.width,i).radius*UR,l=Math.atan(c/(i*.5)*Math.tan(r*.5)),u=s/Math.max(Math.sin(l),1e-4),h=Math.max(s*1.55,u-s);this._focusInProgress=!0;const d=()=>{var p,g;this._focusInProgress=!1,(g=(p=this.viewer.scene).requestRender)==null||g.call(p)};return this.viewer.camera.flyTo({destination:Cesium.Cartesian3.fromRadians(o.longitude,o.latitude,h),orientation:{heading:this.viewer.camera.heading,pitch:-Cesium.Math.PI_OVER_TWO,roll:0},duration:t,easingFunction:Cesium.EasingFunction.CUBIC_IN_OUT,complete:d,cancel:()=>{d(),this.isGlobeFullyVisible()||this._autoDisable()}}),!0}_clear(){var t;for(const[n,i]of[[this._sunCanvas,this._sunCtx],[this._moonCanvas,this._moonCtx]])n&&i&&i.clearRect(0,0,n.width,n.height);(t=this._ringOutline)==null||t.style.setProperty("display","none"),this._sunRenderKey="",this._moonRenderKey="",this._outlineRenderKey=""}_resize(t,n){const i=Math.max(1,window.devicePixelRatio||1),o=Math.sqrt(iv/(t*n)),r=ov/Math.max(t,n),s=Math.min(i,zR,o,r),a=Math.max(1,Math.round(t*s)),c=Math.max(1,Math.round(n*s));for(const[l,u]of[[this._sunCanvas,this._sunCtx],[this._moonCanvas,this._moonCtx]])(l.width!==a||l.height!==c)&&(l.width=a,l.height=c),l.style.width=`${t}px`,l.style.height=`${n}px`,u.setTransform(s,0,0,s,0,0);this._renderScale=s}_updateEphemeris(t){if(!this._ephemerisDirty)return!0;Cesium.Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame(t,this._sunInertial),Cesium.Simon1994PlanetaryPositions.computeMoonPositionInEarthInertialFrame(t,this._moonInertial);const n=Cesium.Transforms.computeIcrfToFixedMatrix(t,this._fixedMatrix)||Cesium.Transforms.computeTemeToPseudoFixedMatrix(t,this._fixedMatrix);return n?(Cesium.Matrix3.multiplyByVector(n,this._sunInertial,this._sunFixed),Cesium.Matrix3.multiplyByVector(n,this._moonInertial,this._moonFixed),Cesium.Cartesian3.normalize(this._sunFixed,this._sunFixed),Cesium.Cartesian3.normalize(this._moonFixed,this._moonFixed),this._ephemerisDirty=!1,this._ephemerisUpdateCount+=1,!0):!1}_autoDisable(){var t;this.enabled&&(this.setEnabled(!1),(t=this._onAutoDisable)==null||t.call(this))}_projectedEarthDisc(t,n){return cv(this.viewer,t,n,this._screenCenter,this._toCenter)}_positionMarker(t,n,i,o,r,s){const a=Math.cos(r),c=Math.sin(r),l=14,u=Math.abs(a)>1e-4?(n-l)/Math.abs(a):Number.POSITIVE_INFINITY,h=Math.abs(c)>1e-4?(i-l)/Math.abs(c):Number.POSITIVE_INFINITY,d=Math.min(o,u,h);t.style.left=`${n+a*d}px`,t.style.top=`${i+c*d}px`,t.style.opacity=String(s)}_renderEffectLayers(t,n,i,o){const r=`${t}:${n}:${i}`;r!==this._outlineRenderKey&&(this._ringOutline.style.display="",this._ringOutline.style.left=`${t-i}px`,this._ringOutline.style.top=`${n-i}px`,this._ringOutline.style.width=`${i*2}px`,this._ringOutline.style.height=`${i*2}px`,this._outlineRenderKey=r);const s=`${r}:${Math.round(o)}`;s!==this._sunRenderKey&&(this._sunCtx.clearRect(0,0,this._sunCanvas.width,this._sunCanvas.height),qR(this._sunCtx,t,n,i,o,0),zp(this._sunCtx,t,n,i,0,"222, 190, 89",.56),this._sunRenderKey=s),r!==this._moonRenderKey&&(this._moonCtx.clearRect(0,0,this._moonCanvas.width,this._moonCanvas.height),WR(this._moonCtx,t,n,i,0),zp(this._moonCtx,t,n,i,0,"48, 201, 229",.42),this._moonRenderKey=r)}_draw(){if(!this.enabled||!this._sunCtx||!this._moonCtx)return;const t=performance.now();if(t0&&o>0))return;this._resize(i,o);const r=this._projectedEarthDisc(i,o),s=this.visible,a=r?Ud(r,s):!1;if(this.visible=a,this._root.classList.toggle("visible",a),this._root.dataset.globeVisible=String(a),this._root.dataset.ephemerisUpdates=String(this._ephemerisUpdateCount),!a||!r){this._clear(),this._debug={enabled:!0,visible:!1,disc:r},this._focusInProgress||this._autoDisable();return}s||(this._ephemerisDirty=!0);const c=Cesium.JulianDate.now();if(!this._updateEphemeris(c))return;this._root.dataset.ephemerisUpdates=String(this._ephemerisUpdateCount);const l=this.viewer.camera,u=Gd(Cesium.Cartesian3.dot(this._sunFixed,l.rightWC),Cesium.Cartesian3.dot(this._sunFixed,l.upWC),this._sunAngle),h=Gd(Cesium.Cartesian3.dot(this._moonFixed,l.rightWC),Cesium.Cartesian3.dot(this._moonFixed,l.upWC),this._moonAngle);u.stable&&(this._sunAngle=u.angle),h.stable&&(this._moonAngle=h.angle),this._sunOpacity=u.opacity,this._moonOpacity=h.opacity;const d=i*.5,f=o*.5,p=r.keyholeRadius-VR,g=Math.min(p-12,r.earthRadius+Math.max(38,p*.065));this._renderEffectLayers(d,f,p,g),this._sunCanvas.style.transform=`rotate(${this._sunAngle}rad)`,this._sunCanvas.style.opacity=String(this._sunOpacity),this._moonCanvas.style.transform=`rotate(${this._moonAngle}rad)`,this._moonCanvas.style.opacity=String(this._moonOpacity);const _=p-HR,m=sv(this._sunAngle,this._moonAngle)>>0}function ll(e,t){const n=(Number(t==null?void 0:t._cohortPriority)||0)-(Number(e==null?void 0:e._cohortPriority)||0);if(n)return n;const i=(Number(t==null?void 0:t._cohortBand)||0)-(Number(e==null?void 0:e._cohortBand)||0);if(i)return i;const o=(Number(e==null?void 0:e._cohortHash)>>>0)-(Number(t==null?void 0:t._cohortHash)>>>0);return o||String(e==null?void 0:e._cohortSourceId).localeCompare(String(t==null?void 0:t._cohortSourceId))}function Ru(e,t){return ll(e,t)>0}class hv{constructor(t=ms,n=ms){const i=Math.max(1,Math.floor(Number(n)||ms));this.maxSize=Math.max(1,Math.min(i,Math.floor(Number(t)||ms))),this.incumbents=[],this.heap=[]}consider(t,n=!1){if(t){if(n){this.incumbents.push(t);return}if(this.heap.length=0||(this.heap[0]=t,this._siftDown(0))}}values(t=this.maxSize){const n=Math.max(0,Math.min(this.maxSize,Math.floor(Number(t)||0))),i=this.incumbents.slice().sort(ll).slice(0,n),o=Math.max(0,n-i.length);if(o===0)return i;const r=this.heap.slice().sort(ll).slice(0,o);return i.concat(r)}_bubbleUp(t){let n=t;for(;n>0;){const i=Math.floor((n-1)/2);if(!Ru(this.heap[n],this.heap[i]))break;[this.heap[n],this.heap[i]]=[this.heap[i],this.heap[n]],n=i}}_siftDown(t){let n=t;for(;;){const i=n*2+1,o=i+1;let r=n;if(i0)||!Number.isFinite(i)?"front":in*2/3?"right":"front"}const JR=Object.freeze({street:Object.freeze({0:9,25:23,50:45,75:68,100:90}),city:Object.freeze({0:7,25:18,50:35,75:53,100:70}),metro:Object.freeze({0:6,25:14,50:28,75:41,100:55}),regional:Object.freeze({0:4,25:10,50:20,75:30,100:40}),global:Object.freeze({0:6,25:14,50:28,75:42,100:56})});function wt(e,t=50){const n=Number(e);if(!Number.isFinite(n))return wt(t,50);const i=Math.max(0,Math.min(100,n));return i<=25?i<12.5?0:25:i<75?50:i<87.5?75:100}function Eo(e){const t=wt(e);return t<=25?"SPARSE":t>=75?"DENSE":"BALANCED"}function $l(e){const t=Uf(e);return t==="SPARSE"?25:t==="DENSE"?75:50}function Uf(e){const t=String(e||"").trim().toUpperCase();return t==="OFF"?"OFF":t==="SPARSE"||t==="SURVEY"?"SPARSE":t==="BALANCED"||t==="NORMAL"?"BALANCED":t==="DENSE"||t==="PANOPTIC"||t==="GOD"||t==="ON"?"DENSE":null}function xo(e,t=Hi){const n=String(e||"").trim().toUpperCase();if(Hl.includes(n))return n;const i=String(t||"").trim().toUpperCase();return Hl.includes(i)?i:Hi}function zd(e){const t=Number.isFinite(Number(e))?Math.max(0,Number(e)):1e9;return t<1200?"street":t<4500?"city":t<2e4?"metro":t<15e4?"regional":"global"}function eL(e,t){const n=zd(e),i=wt(t);return JR[n][i]}function tL(e,t,n=50){const i=String(e).trim().toUpperCase(),o=Uf(i);if(o==="OFF"){const s=Number.isFinite(Number(t))?t:n,a=wt(s,n);return{enabled:!1,profile:Eo(a),densityPct:a}}if(i==="PANOPTIC"||i==="GOD"||i==="ON"){const s=Number.isFinite(Number(t))?Math.max(75,Number(t)):75;return{enabled:!0,profile:"DENSE",densityPct:wt(s)}}if(i==="SPARSE"||i==="SURVEY"){const s=Number.isFinite(Number(t))?Math.min(25,Number(t)):25;return{enabled:!0,profile:"SPARSE",densityPct:wt(s,25)}}if(o==="BALANCED"||o==="DENSE"){const s=Number.isFinite(Number(t))?wt(t):$l(o),a=Eo(s)===o?s:$l(o);return{enabled:!0,profile:o,densityPct:a}}const r=wt(t,n);return{enabled:!0,profile:Eo(r),densityPct:r}}const nL=32,jp=Object.freeze([]),fv=150,ps=300,jd=2500,qd=1200;function mv(e,t,n){return Math.max(t,Math.min(n,Math.floor(Number(e)||0)))}function pv(e){return(e instanceof Map?Array.from(e.entries()):Object.entries(e||{})).map(([n,i])=>[String(n),Math.max(0,Math.floor(Number(i)||0))]).filter(([,n])=>n>0).sort(([n],[i])=>n.localeCompare(i))}function qp(e,t,n,i){let o=Array.from(e.values()).reduce((r,s)=>r+s,0);for(;o=(t.get(s)||0))&&(e.set(s,a+1),o++,r=!0,o>=n))break}if(!r)break}return e}function iL(e,t,n,i,o,r,s,a,c,l){s.forEach((f,p)=>{e.has(p)||s.delete(p)});for(let f=0;f0?1:0);p>0&&p--;const C=Math.min(e.get(m)||0,b);s.set(m,C),g+=C}for(;g=(e.get(b)||0)||(s.set(b,C+1),g++,_=!0)}if(!_)break}return s}let u=0;for(let f=0;fp.weight-f.weight||f.layerId.localeCompare(p.layerId));let h=t;if(t>=r){for(let f=0;f0&&u>0){let f=0;for(let p=0;pg.fraction-p.fraction||g.weight-p.weight||p.layerId.localeCompare(g.layerId));for(let p=0;p0;p++){const g=l[p],_=s.get(g.layerId)||0;_>=(e.get(g.layerId)||0)||(s.set(g.layerId,_+1),h--)}}let d=0;for(let f=0;f=(e.get(g)||0)||(s.set(g,_+1),d++,f=!0)}if(!f)break}return s}function oL(e,t,n=Hi,i={}){const o=pv(e),r=o.reduce((_,[,m])=>_+m,0),s=mv(t,0,r),a=new Map(o.map(([_])=>[_,0]));if(s===0||o.length===0)return a;const c=new Map(o),l=o.map(([_])=>_);if(xo(n)===Hi){const _=Math.floor(s/l.length);let m=s%l.length;for(const b of l){const C=_+(m>0?1:0);m=Math.max(0,m-1),a.set(b,Math.min(c.get(b),C))}return qp(a,c,s,l)}const h=o.map(([_,m])=>{const b=Math.max(.05,Number(i[_])||1);return{layerId:_,count:m,weight:Math.sqrt(m)*b}}),d=h.slice().sort((_,m)=>m.weight-_.weight||_.layerId.localeCompare(m.layerId)).map(_=>_.layerId);let f=s;if(s>=l.length){for(const _ of l)a.set(_,1);f-=l.length}const p=h.reduce((_,m)=>_+m.weight,0),g=[];if(f>0&&p>0){let _=0;for(const m of h){const b=f*m.weight/p,C=m.count-(a.get(m.layerId)||0),y=Math.min(C,Math.floor(b));a.set(m.layerId,(a.get(m.layerId)||0)+y),_+=y,g.push({layerId:m.layerId,fraction:b-Math.floor(b),weight:m.weight})}f-=_,g.sort((m,b)=>b.fraction-m.fraction||b.weight-m.weight||m.layerId.localeCompare(b.layerId));for(const m of g){if(f<=0)break;const b=a.get(m.layerId)||0;b>=c.get(m.layerId)||(a.set(m.layerId,b+1),f--)}}return qp(a,c,s,d)}function Sr(e){return e&&Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.w)&&Number.isFinite(e.h)&&e.w>0&&e.h>0}function rL(e,t,n=4){return e.xt.x&&e.yt.y}const Wo=8192;class sL{constructor(t=nL){this.cellSize=t,this.cells=new Map,this.generation=0}reset(){this.generation++}clear(){this.cells.clear(),this.generation=0}_cellKey(t,n){const i=Math.max(-Wo,Math.min(Wo-1,t))+Wo,o=Math.max(-Wo,Math.min(Wo-1,n))+Wo;return i<<14|o}collides(t){const n=this.cellSize,i=Math.floor((t.x+t.w)/n),o=Math.floor((t.y+t.h)/n);for(let r=Math.floor(t.y/n);r<=o;r++)for(let s=Math.floor(t.x/n);s<=i;s++){const a=this.cells.get(this._cellKey(s,r));if(!(!a||a.generation!==this.generation)){for(let c=0;cu?1:-1;const d=Number(e.keyholeAlpha)||0,f=Number(t.keyholeAlpha)||0;if(d!==f)return f>d?1:-1;const p=Number(e.centerDistance)||0,g=Number(t.centerDistance)||0;return p!==g?p>g?1:-1:String(e.key).localeCompare(String(t.key))}function lL(e){let t=Number.NaN,n=Number.NaN;if(Number.isFinite(e==null?void 0:e.screenX)&&Number.isFinite(e==null?void 0:e.screenY))t=e.screenX,n=e.screenY;else{const i=Array.isArray(e==null?void 0:e.placements)?e.placements[0]:null;Number.isFinite(i==null?void 0:i.leadFromX)&&Number.isFinite(i==null?void 0:i.leadFromY)?(t=i.leadFromX,n=i.leadFromY):Sr(i==null?void 0:i.rect)&&(t=i.rect.x+i.rect.w*.5,n=i.rect.y+i.rect.h*.5)}e._anchorX=t,e._anchorY=n}function Wp(e){const t=Math.max(0,Math.min(1,Number(e==null?void 0:e.keyholeAlpha)||0));return t>=.999?8:Math.floor(t*8)}class cL{constructor(){this.candidates=null,this.count=0,this.anchorCount=0,this.distances=new Float64Array(0),this.anchorXs=new Float64Array(0),this.anchorYs=new Float64Array(0),this.placementMasks=new Uint8Array(0),this.placementXs=new Float64Array(0),this.placementYs=new Float64Array(0),this.placementWs=new Float64Array(0),this.placementHs=new Float64Array(0),this.seedAnchorXs=new Float64Array(0),this.seedAnchorYs=new Float64Array(0),this.attemptStamps=null,this.stamp=0,this.spatial=null,this.states=null}reset(t,n,i,o,r,s,a,c){var l;if(this.candidates=t,this.count=n,this.anchorCount=o,this.attemptStamps=r,this.stamp=s,this.spatial=a,this.states=c,this.distances.length4)continue;let f=0;for(let p=0;pp&&Ag&&(k&=~I)}if(c[b]=k,k===0&&this._dismissBlockedKey(b))continue}const y=s[b],v=a[b];if(!Number.isFinite(y)||!Number.isFinite(v))continue;const M=y-i,w=v-o,E=M*M+w*w;E0&&(i=s,o=r);continue}const c=Wp(s)-Wp(i);if(c!==0){c>0&&(i=s,o=r);continue}if(this.anchorCount>0){const l=this.distances[r]-this.distances[o];if(l!==0){l>0&&(i=s,o=r);continue}}String(s.key).localeCompare(String(i.key))<0&&(i=s,o=r)}return i}}function uL(e,t){const n=e==null?void 0:e.placements;if(!Array.isArray(n))return null;let i=null;for(let o=0;ot*4+64&&e.clear()}function hL(e){e.count=0}function fL(e,t,n,i){for(let o=1;o=0&&aL(e[s],r,n,i)>0;)e[s+1]=e[s],s--;e[s+1]=r}}function mL(e,t,n){const i=e==null?void 0:e.placements;if(!Array.isArray(i))return n;let o=null;for(let r=0;r0))continue;lL(G),c[h++]=G;let W=u.get(G.layerId);W||(W={list:[],count:0},u.set(G.layerId,W)),W.list[W.count++]=G}c.length=h,u.forEach(N=>{N.list.length=N.count,fL(N.list,N.count,this.states,i)});const d=this._demand;if(d.clear(),n.demandByLayer instanceof Map)n.demandByLayer.forEach((N,G)=>{const W=Math.max(0,Math.floor(Number(N)||0));W>0&&d.set(String(G),W)});else if(n.demandByLayer!=null){const N=pv(n.demandByLayer);for(let G=0;G{N.count>0&&!d.has(G)&&d.set(G,N.count)});const f=this._activeLayersScratch;let p=0,g=0;d.forEach((N,G)=>{g+=N,f[p++]=G}),f.length=p,f.sort();const _=mv(n.capacity,0,g),m=xo(n.strategy),b=iL(d,_,m,n.layerWeights,f,p,this._quotas,this._weightedQuotaScratch,this._quotaPriorityScratch,this._quotaRemainderScratch),C=this._spatial;C.reset();const y=this._queue,v=this._selectedCandidates,M=this._selectedPlacements;let w=0,E=p===this.lastActiveLayers.length;for(let N=0;E&&N{if(w>=_||s.get(N.key)===r)return!1;s.set(N.key,r);const W=this.states.get(N.key),V=N.stateless===!0;if(!V&&!(W!=null&&W.selected)&&(W==null?void 0:W.cooldownUntil)>i)return!1;const H=V||W==null?void 0:W.corner;let B=Wd(N,H,C);return!B&&G&&(B=uL(N,H)),B?(C.add(B.rect),a.set(N.key,r),v[w]=N,M[w]=B,w++,!0):!1};for(let N=0;Nps+qd&&(this.states.delete(G.key),this._stateListDirty=!0)}const O=this._droppedKeys;let D=0;this.selectedKeys.forEach(N=>{a.get(N)!==r&&(O[D++]=N)});for(let N=0;N[a.key,a])),r=this._refreshStateList();let s=0;for(let a=0;a=ps))continue;const r=o.lastCandidate;!(r!=null&&r.layerId)||r.sourceId==null||(i.has(r.layerId)||i.set(r.layerId,new Set),i.get(r.layerId).add(r.sourceId))}return i}diagnostics(){return this.lastDiagnostics?{...this.lastDiagnostics}:null}}const Yp=Object.freeze({fadeInMs:fv,fadeOutMs:ps,minimumLifetimeMs:jd,cooldownMs:qd}),He=Object.freeze({background:"rgba(4, 12, 16, 0.82)",selectedBackground:"rgba(5, 18, 24, 0.94)",border:"rgba(190, 232, 242, 0.18)",selectedBorder:"rgba(107, 232, 255, 0.72)",title:"rgba(232, 240, 244, 0.96)",detail:"rgba(147, 161, 173, 0.92)",leader:"rgba(147, 213, 228, 0.58)",accent:"#6be8ff",fontLabel:'500 10px "JetBrains Mono", monospace',fontTrack:'600 10px "JetBrains Mono", monospace',fontTitle:'600 12px "JetBrains Mono", monospace',fontDetail:'500 10.5px "JetBrains Mono", monospace',fontSelected:'600 13px "JetBrains Mono", monospace',fontTrackedTitle:'600 13px "JetBrains Mono", monospace',fontTrackedDetail:'500 11px "JetBrains Mono", monospace',radius:4}),Ht=Object.freeze({padding:4,titleHeight:13,titleChars:15,background:He.background,titleColor:"rgba(210, 236, 244, 0.95)",titleFont:'600 10px "JetBrains Mono", monospace',accent:"rgb(107, 232, 255)",leader:"rgba(107, 232, 255, 0.6)",rule:"rgba(107, 232, 255, 0.95)",ruleHeight:2,radius:4}),zf=Object.freeze({font:"10px JetBrains Mono, monospace",microFont:"9px JetBrains Mono, monospace",glowPx:3}),pL=.22,jf=Object.freeze({retro:{line:"rgba(255, 176, 56, 0.88)",label:"rgba(255, 216, 128, 0.95)",labelBg:"rgba(30, 12, 0, 0.72)",calloutPlate:"rgba(30, 12, 0, 0.48)",calloutPlateSpace:"rgba(30, 12, 0, 0.56)",glow:"rgba(255, 176, 56, 0.45)",dim:"rgba(230, 190, 140, 0.62)",cardBorder:"rgba(255, 210, 150, 0.16)",blend:"screen",filter:"contrast(1.08) saturate(1.04)",scanline:.085,tiers:{civil:"#ffd27a",military:"#ff8a3c",sea:"#ffc06a",space:"#ffe0a0",vehicle:"#d0a060",veh_jam:"#ff3b30",veh_slow:"#ffb300",veh_free:"#00ff66",veh_nodata:"#c9c9c9",transit_bus:"#5EF08A",transit_tram:"#FFC24A",transit_subway:"#FF4538",transit_rail:"#D9A6FF",transit_ferry:"#5FD6FF",transit_unknown:"#D8DDE5"}},surveillance:{line:"rgba(120, 255, 130, 0.9)",label:"rgba(225, 255, 210, 0.97)",labelBg:"rgba(6, 16, 6, 0.78)",calloutPlate:"rgba(6, 16, 6, 0.48)",calloutPlateSpace:"rgba(6, 16, 6, 0.56)",glow:"rgba(120, 255, 120, 0.42)",dim:"rgba(170, 205, 160, 0.62)",cardBorder:"rgba(190, 255, 190, 0.18)",blend:"screen",filter:"contrast(1.12) saturate(1.12)",scanline:.09,tiers:{civil:"#8fe89a",military:"#ff5a47",sea:"#a6f0c0",space:"#9fe8ff",vehicle:"#ffc24a",veh_jam:"#ff4538",veh_slow:"#ffc24a",veh_free:"#45d8ff",veh_nodata:"#dcdcdc",transit_bus:"#5EF08A",transit_tram:"#FFC24A",transit_subway:"#FF4538",transit_rail:"#D9A6FF",transit_ferry:"#5FD6FF",transit_unknown:"#D8DDE5"}},thermal:{line:"rgba(255, 224, 170, 0.95)",label:"rgba(255, 236, 208, 0.98)",labelBg:"rgba(20, 20, 20, 0.66)",calloutPlate:"rgba(20, 20, 20, 0.46)",calloutPlateSpace:"rgba(20, 20, 20, 0.54)",glow:"rgba(255, 224, 170, 0.42)",dim:"rgba(245, 222, 196, 0.74)",cardBorder:"rgba(255, 255, 255, 0.15)",blend:"screen",filter:"contrast(1.1) saturate(1.08)",scanline:.04,tiers:{civil:"#ffffff",military:"#ff7a5c",sea:"#ffd0b0",space:"#d0e0ff",vehicle:"#ffcf9f",veh_jam:"#ff4538",veh_slow:"#ffc24a",veh_free:"#2ecc71",veh_nodata:"#d8d8d8",transit_bus:"#5EF08A",transit_tram:"#FFC24A",transit_subway:"#FF4538",transit_rail:"#D9A6FF",transit_ferry:"#5FD6FF",transit_unknown:"#D8DDE5"}},_default:{line:"rgba(0, 244, 255, 0.9)",label:"rgba(200, 250, 255, 0.97)",labelBg:"rgba(2, 18, 26, 0.66)",calloutPlate:"rgba(2, 18, 26, 0.46)",calloutPlateSpace:"rgba(2, 18, 26, 0.54)",glow:"rgba(0, 244, 255, 0.4)",dim:"rgba(150, 200, 215, 0.66)",cardBorder:"rgba(255, 255, 255, 0.12)",blend:"screen",filter:"contrast(1.05) saturate(1.05)",scanline:.05,tiers:{civil:"#22e0ff",military:"#ffb347",sea:"#3fe0c8",space:"#bda4ff",vehicle:"#8fa6b4",veh_jam:"#e05252",veh_slow:"#f0b23e",veh_free:"#2ecc71",veh_nodata:"#c9c9c9",transit_bus:"#5EF08A",transit_tram:"#FFC24A",transit_subway:"#FF4538",transit_rail:"#D9A6FF",transit_ferry:"#5FD6FF",transit_unknown:"#D8DDE5"}}}),gL=1024,vr=new Map;let Gl=0,Kd=0,Ul=!1,Yd=0,Mn=null;function _L(){let e=null,t=null,n=Number.POSITIVE_INFINITY;if(vr.forEach((o,r)=>{o.forEach((s,a)=>{s.usedAt>=n||(n=s.usedAt,e=r,t=a)})}),e===null)return;const i=vr.get(e);i.delete(t),i.size===0&&vr.delete(e),Gl--}function zl(){vr.clear(),Gl=0,Kd=0}function bL(){var t;if(Ul||typeof document>"u"||!document.fonts)return;Ul=!0,Mn=document.fonts;const e=++Yd;Promise.resolve(document.fonts.ready).then(()=>{e===Yd&&zl()}).catch(()=>{}),(t=Mn.addEventListener)==null||t.call(Mn,"loadingdone",zl)}function CL(){var e;Yd++,(e=Mn==null?void 0:Mn.removeEventListener)==null||e.call(Mn,"loadingdone",zl),Mn=null,Ul=!1,zl()}function Pu(e,t,n){var c;Ul||bL();const i=String(t??""),o=String(n||He.fontLabel);let r=vr.get(o);const s=r==null?void 0:r.get(i);if(s)return s.usedAt=++Kd,s.width;e.font=o;const a=Number((c=e.measureText(i))==null?void 0:c.width)||0;return r||(r=new Map,vr.set(o,r)),r.set(i,{width:a,usedAt:++Kd}),Gl++,Gl>gL&&_L(),a}function xn(e,t,n,i,o,r=He.radius){if(typeof e.roundRect=="function"){e.roundRect(t,n,i,o,r);return}const s=Math.max(0,Math.min(Number(r)||0,i/2,o/2));e.moveTo(t+s,n),e.arcTo(t+i,n,t+i,n+o,s),e.arcTo(t+i,n+o,t,n+o,s),e.arcTo(t,n+o,t,n,s),e.arcTo(t,n,t+i,n,s),e.closePath()}function yL(e,{minDistance:t=0,maxDistance:n=Number.POSITIVE_INFINITY,fadeStartRatio:i=.7}={}){if(!Number.isFinite(e))return 0;const o=Number.isFinite(t)?Math.max(0,t):0;if(e=r)return 0;const s=Math.max(0,Math.min(1,Number(i)||0)),a=o+(r-o)*s;return e<=a||a>=r?1:1-(e-a)/(r-a)}function Xp(e,t=null){if(!t||!Number.isFinite(e))return 1;const n=Math.max(0,Number(t.near)||0),i=Math.max(n,Number(t.far)||n),o=Math.max(0,Number(t.nearValue)||0),r=Math.max(0,Number(t.farValue)||0);if(e<=n||i===n)return o;if(e>=i)return r;const s=(e-n)/(i-n);return o+(r-o)*s}function vL(e,{minAltitude:t=Number.NEGATIVE_INFINITY,fadeStart:n=Number.POSITIVE_INFINITY,fadeEnd:i=Number.POSITIVE_INFINITY}={}){if(!Number.isFinite(e))return 1;if(Number.isFinite(t)&&e=o||r===o?0:1-(e-r)/(o-r)}function _v(e){const t=(e==null?void 0:e.title)||"",n=Array.isArray(e==null?void 0:e.details)&&e.details[0]||"";return(e._overlayTrackDisplayTitle!==t||e._overlayTrackDisplayDetail!==n)&&(e._overlayTrackDisplayTitle=t,e._overlayTrackDisplayDetail=n,e._overlayTrackDisplayText=t&&n?`${t} · ${n}`:t||n),e._overlayTrackDisplayText||""}function ML(e,t,n={}){const i=t!=null&&t.selected?"selected":String((t==null?void 0:t.variant)||"label"),o=Array.isArray(t==null?void 0:t.details)?t.details:[],r=i==="selected",s=i==="tracked",a=(t==null?void 0:t.cardStyle)==="tactical",c=s?He.fontTrackedTitle:r?He.fontSelected:He.fontTitle;let l=Pu(e,(t==null?void 0:t.title)||"",i==="label"?He.fontLabel:c);i==="track"&&o[0]&&(l=Pu(e,_v(t),He.fontTrack));let u=0;for(let h=0;h=4?"above":"below",f=l?TL:EL,p=f[a]||f[d];let g=c,_=c;c!==0&&(g=Math.round(c),_=-g);for(let m=0;m>16&255}, ${r>>8&255}, ${r&255}, ${t})`}return n}function AL(e){const t=e.accent||He.accent;let n=e._overlayTacticalAccentColors;return(!n||n.accent!==t)&&(n={accent:t,leader:cl(t,.65),border:cl(t,.85),rule:cl(t,.95)},e._overlayTacticalAccentColors=n),n}function Cv(e,t){const n=Math.max(0,Number(e==null?void 0:e.leaderAnimationMs)||0);if(!n)return 1;const i=Number(e==null?void 0:e.leaderAnimationStartedAt);return Number.isFinite(i)?Math.max(0,Math.min(1,(t-i)/n)):1}function yv(e){const t=Number(e==null?void 0:e.leaderDrawRatio);return Number.isFinite(t)?Math.max(.1,Math.min(.9,t)):.68}function IL(e,t=(i=>(i=(n=>(n=globalThis.performance)==null?void 0:n.now)())==null?void 0:i.call(n))()??Date.now()){const o=Math.min(1,Cv(e,t)/yv(e));return 1-Math.pow(1-o,3)}function RL(e,t=(i=>(i=(n=>(n=globalThis.performance)==null?void 0:n.now)())==null?void 0:i.call(n))()??Date.now()){if(!(Math.max(0,Number(e==null?void 0:e.leaderAnimationMs)||0)>0))return 1;const o=yv(e),r=Math.max(0,Math.min(1,(Cv(e,t)-o)/Math.max(.1,1-o)));return r*r*(3-2*r)}function LL(e,t,n,i,o){if(e.strokeStyle=i,e.lineWidth=(t.leaderStyle==="elbow"?1.5:1)/(n.paintScale||1),e.lineJoin="round",e.lineCap="round",e.beginPath(),t.leaderStyle!=="elbow"||n.corner!=="above"&&n.corner!=="below"){n.leaderOffset===0?e.moveTo(n.leadFromX,n.leadFromY):n.corner==="above"||n.corner==="below"?e.moveTo(n.leadFromX,n.leadFromY+n.leaderOffset):e.moveTo(n.leadFromX+n.leaderOffset,n.leadFromY),e.lineTo(n.leadToX,n.leadToY),e.stroke();return}const{x:r,y:s,w:a,h:c}=n.rect,l=r+Math.max(18,Math.min(a-18,a*.22)),u=n.corner==="above"?s+c:s,h=Math.abs(n.leaderOffset),d=n.leadFromX-h,f=n.leadFromY,p=Math.abs(d-l),g=Math.abs(f-u);let _=IL(t,o)*(p+g);if(e.moveTo(d,f),_<=p){const m=Math.sign(l-d)||-1;e.lineTo(d+m*_,f)}else{e.lineTo(l,f),_-=p;const m=Math.sign(u-f)||-1;e.lineTo(l,f+m*Math.min(g,_))}e.stroke()}function PL(e,t,n,i=1){var p,g;const o=t.selected||t.variant==="selected",r=Array.isArray(t.details)?t.details:[],s=t._overlayLayout||{},{x:a,y:c,w:l,h:u}=n.rect,h=AL(t),d=((g=(p=globalThis.performance)==null?void 0:p.now)==null?void 0:g.call(p))??Date.now();e.save(),e.globalAlpha=i,LL(e,t,n,t.leaderStyle==="elbow"?cl(t.accent,.95):h.leader,d),e.globalAlpha=i*RL(t,d),e.beginPath(),xn(e,a,c,l,u,4),e.fillStyle=He.background,e.fill(),o&&(e.beginPath(),xn(e,a+.5,c+.5,l-1,u-1,4),e.strokeStyle=h.border,e.lineWidth=1,e.stroke()),e.beginPath(),xn(e,a,c,l,2,1),e.fillStyle=h.rule,e.fill(),e.textAlign="left",e.textBaseline="alphabetic",e.fillStyle=He.title,e.font=o?He.fontSelected:He.fontTitle;const f=c+s.padY+s.titleH-2;e.fillText(String(t.title||""),a+s.padX,f),e.fillStyle=He.detail,e.font=He.fontDetail;for(let _=0;_0&&(e.beginPath(),xn(e,r,s,a,m,Math.min(1,m)),e.fillStyle=t.thumbnailRuleColor||t.accent||He.accent,e.fill());const b=Math.max(0,Math.floor(Number(t.thumbnailTitleChars)||0)),C=t._overlayThumbnailTitle||String(t.title||"").toUpperCase();return e.textAlign="left",e.textBaseline="alphabetic",e.fillStyle=t.thumbnailTitleColor||He.title,e.font=t.thumbnailTitleFont||He.fontTitle,e.fillText(b>0?C.slice(0,b):C,g,_+d+f-3),e.restore(),n.rect}function DL(e,t,n,i=1){return e.save(),e.globalAlpha=i,Wc(e,t,n,!0),bv(e,t,n,!0),e.restore(),n.rect}function OL(e,t,n,i=1){const o=Array.isArray(t.details)?t.details:[],r=t._overlayLayout||{},{x:s,y:a,w:c,h:l}=n.rect,u=t.accent||He.accent;e.save(),e.globalAlpha=i,qf(e,n,u),e.beginPath(),xn(e,s,a,c,l,5),e.fillStyle=He.background,e.fill(),e.beginPath(),xn(e,s,a,c,2,1),e.fillStyle=u,e.fill(),e.textAlign="center",e.textBaseline="alphabetic";const h=s+c/2,d=a+r.padY+r.titleH-2;e.fillStyle=He.title,e.font=He.fontTrackedTitle,e.fillText(String(t.title||""),h,d),e.fillStyle=He.detail,e.font=He.fontTrackedDetail;for(let f=0;f[e,t])),Kc=Object.freeze(["#title-bar","#style-indicator","#top-center-actions","#traffic-sync-chip","#cctv-sync-chip","#left-panel-stack","#right-context-rail","#pp-toggles","#command-dock","#gev-voice-control","#cesium-credits",".hud-top-left",".hud-top-right",".hud-bottom-left",".hud-bottom-right",".hud-top-bar",".hud-bottom-bar","#space-mission-panel","#space-mission-panel-host","#military-awareness-panel","#cockpit-context","#cockpit-signal-stream"]);let tt=null,mt=null,dt=null,It=null,kt=null,$t=null,cn=null,jl="";const gs=new Map;let lt=null,ga=null,cr=null,_s=null,dn=null,vt=null,Mr=new WeakSet,wr=null,Rs=null,Ls=null,ql=!1,Dt=!1,_a=!0,ai=!0,li=!0,Ho=!0,$o=!0,Wl=Number.NEGATIVE_INFINITY,In=0,fn=0,Nr=1,Dr=0;const $i=new Map,Gi=[],Zi=new Map,Ft=[],Zd=new Map,Nt=[],Or=new Map,Ev=new Cesium.Matrix4,xt={},ta={width:0,height:0};let na=null,Jd=Number.NaN,eh=Number.NaN,th=Number.NaN,ul=null,nh=-1,ih=-1,oh=Number.NaN,rh=Number.NaN,Yc=0;const Ui=[],sh=[],Je={canvas:null,surface:null,ctx:null,width:0,height:0,dpr:1,timestamp:0,viewProjectionMatrix:Ev,viewProjection:xt,cameraPosition:null,occluder:null,keyhole:null,uiRects:Ui,uiRectCount:0,layoutRevision:0},Er=[],Tr=[],kr=[],Xc=new Map,Qc=[],Ei=Object.create(null),Ti=[];let ki=0,Ai=0,zi=0;const et={sourceCount:0,entryCount:0,candidateCount:0,projectedCount:0,selectedCount:0,fadingCount:0,paintedCount:0,hitRectCount:0,projectionMs:0,solveMs:0,paintMs:0,solveRevision:0,paintItemPoolSize:0,paintRectPoolSize:0,candidateIndexSize:0,entriesBySource:{},paintedBySource:Ei};function Ii(){var e,t;return((t=(e=globalThis.performance)==null?void 0:e.now)==null?void 0:t.call(e))??Date.now()}function ah(e,t=1){return Number.isFinite(Number(e))?Math.max(0,Math.min(1,Number(e))):t}function ba(e){if(typeof e!="string"||!e.trim())throw new TypeError("WorldOverlay sourceId must be a non-empty string");return e.trim()}function Yf(e,t){return`${e}\0${t}`}function Xf(e,t){return et?1:0}function HL(e,t){return t.priority-e.priority||Xf(e._overlayKey,t._overlayKey)}function $L(e,t){return t.priority-e.priority||Xf(e.key,t.key)}function GL(e,t){return e.lane-t.lane||e.zIndex-t.zIndex||Xf(e.key,t.key)}function Tv(e,t,n){for(let i=1;i=0&&n(e[r],o)>0;)e[r+1]=e[r],r--;e[r+1]=o}}function UL(e,t,n){n.set(t,0)}function zL(e,t){e.size>t*4+64&&e.clear()}function jL(e){return e==="label"?"ambient-label":e==="track"||e==="tracked"?"ambient-track":"ambient-card"}function Zc(e={}){return ln.has(e.paintLane)?ln.get(e.paintLane):e.tracked||e.variant==="tracked"?ln.get("tracked"):e.selected||e.variant==="selected"?ln.get("selected"):e.variant==="thumbnail"?ln.get("thumbnail"):e.variant==="card"?ln.get("ambient-card"):e.variant==="track"?ln.get("ambient-track"):ln.get("ambient-label")}function qL(e){let t;try{t=e.cullPosition}catch{return null}if(!t||typeof t!="object")return null;const{x:n,y:i,z:o}=t;return!Number.isFinite(n)||!Number.isFinite(i)||!Number.isFinite(o)?null:new Cesium.Cartesian3(n,i,o)}function Qf(e,t){const n=ba(e);if(!t||typeof t!="object")throw new TypeError("WorldOverlay entry must be an object");const i=typeof t.id=="string"?t.id.trim():"";if(!i)throw new TypeError("WorldOverlay entry.id must be a non-empty string");if(!(typeof t.position=="function"||t.position&&Number.isFinite(t.position.x)&&Number.isFinite(t.position.y)&&Number.isFinite(t.position.z)))throw new TypeError(`WorldOverlay entry ${n}:${i} requires a Cartesian position or getter`);const r=String(t.variant||"label");if(!VL.has(r))throw new TypeError(`Unsupported WorldOverlay variant: ${r}`);const s={id:i,source:n,position:t.position,cullPosition:qL(t),variant:r,title:String(t.title??""),details:Array.isArray(t.details)?t.details.map(a=>String(a)):[],accent:t.accent||He.accent,paintLane:t.paintLane,priority:Number.isFinite(Number(t.priority))?Number(t.priority):0,selected:t.selected===!0,pinned:t.pinned===!0,protected:t.protected===!0,tracked:t.tracked===!0||r==="tracked",active:t.active===!0,collisionGroup:String(t.collisionGroup||jL(r)),zIndex:Number.isFinite(Number(t.zIndex))?Number(t.zIndex):Zc({paintLane:t.paintLane,tracked:t.tracked,selected:t.selected,variant:r})*10,interactive:t.interactive===!0,accessibilityLabel:String(t.accessibilityLabel||"").trim(),activate:typeof t.activate=="function"?t.activate:null,minDistance:Number.isFinite(Number(t.minDistance))?Math.max(0,Number(t.minDistance)):0,maxDistance:Number.isFinite(Number(t.maxDistance))?Math.max(0,Number(t.maxDistance)):Number.POSITIVE_INFINITY,distanceFadeStartRatio:Number.isFinite(Number(t.distanceFadeStartRatio))?Math.max(0,Math.min(1,Number(t.distanceFadeStartRatio))):.7,distanceScale:og(t.distanceScale),altitudeScale:WL(t.altitudeScale),minAltitude:Number.isFinite(Number(t.minAltitude))?Number(t.minAltitude):Number.NEGATIVE_INFINITY,altitudeFadeStart:Number.isFinite(Number(t.altitudeFadeStart))?Number(t.altitudeFadeStart):Number.POSITIVE_INFINITY,altitudeFadeEnd:Number.isFinite(Number(t.altitudeFadeEnd))?Number(t.altitudeFadeEnd):Number.POSITIVE_INFINITY,edgeFade:t.edgeFade===!1||t.edgeFade==="none"?"none":"keyhole",horizonCull:t.horizonCull!==!1,terrainOcclusion:t.terrainOcclusion===!0,sourceAlpha:ah(t.sourceAlpha??t.alpha,1),temporalAlpha:ah(t.temporalAlpha,1),gapPx:Number.isFinite(Number(t.gapPx))?Math.max(0,Number(t.gapPx)):12,leaderOffsetPx:Number.isFinite(Number(t.leaderOffsetPx))?Math.max(0,Number(t.leaderOffsetPx)):0,leaderStyle:t.leaderStyle==="elbow"?"elbow":"straight",leaderAnimationMs:Number.isFinite(Number(t.leaderAnimationMs))?Math.max(0,Number(t.leaderAnimationMs)):0,leaderAnimationStartedAt:Number.isFinite(Number(t.leaderAnimationStartedAt))?Number(t.leaderAnimationStartedAt):0,leaderDrawRatio:Number.isFinite(Number(t.leaderDrawRatio))?Math.max(.1,Math.min(.9,Number(t.leaderDrawRatio))):.68,anchorRadiusPx:Number.isFinite(Number(t.anchorRadiusPx))?Math.max(0,Number(t.anchorRadiusPx)):0,anchorRadiusScale:og(t.anchorRadiusScale),minAnchorGapPx:Number.isFinite(Number(t.minAnchorGapPx))?Math.max(0,Number(t.minAnchorGapPx)):0,anchorGapPaddingPx:Number.isFinite(Number(t.anchorGapPaddingPx))?Math.max(0,Number(t.anchorGapPaddingPx)):0,verticalOnly:t.verticalOnly===!0,stateless:t.stateless===!0,minAnchorSeparationPx:Number.isFinite(Number(t.minAnchorSeparationPx))?Math.max(0,Number(t.minAnchorSeparationPx)):0,viewportMargin:Number.isFinite(Number(t.viewportMargin))?Math.max(0,Number(t.viewportMargin)):4,viewportPadding:Number.isFinite(Number(t.viewportPadding))?Math.max(0,Number(t.viewportPadding)):64,requireImage:t.requireImage===!0,safeTopRatio:Number.isFinite(Number(t.safeTopRatio))?Math.max(0,Number(t.safeTopRatio)):0,safeTopMaxPx:Number.isFinite(Number(t.safeTopMaxPx))?Math.max(0,Number(t.safeTopMaxPx)):Number.POSITIVE_INFINITY,pinnedBypassesSafeTop:t.pinnedBypassesSafeTop===!0,placement:String(t.placement||"auto"),cardStyle:t.cardStyle,image:t.image??null,metadata:t.metadata??null,thumbnailWidth:t.thumbnailWidth,thumbnailHeight:t.thumbnailHeight,thumbnailPadX:t.thumbnailPadX,thumbnailPadTop:t.thumbnailPadTop,thumbnailPadBottom:t.thumbnailPadBottom,thumbnailTitleGap:t.thumbnailTitleGap,thumbnailTitleHeight:t.thumbnailTitleHeight,thumbnailTitleChars:t.thumbnailTitleChars,thumbnailBackground:t.thumbnailBackground,thumbnailTitleColor:t.thumbnailTitleColor,thumbnailTitleFont:t.thumbnailTitleFont,thumbnailLeaderColor:t.thumbnailLeaderColor,thumbnailRuleColor:t.thumbnailRuleColor,thumbnailRuleHeight:t.thumbnailRuleHeight,thumbnailRadius:t.thumbnailRadius,_overlayTacticalAccentColors:null,_overlayTrackDisplayTitle:null,_overlayTrackDisplayDetail:null,_overlayTrackDisplayText:"",_overlayThumbnailTitle:r==="thumbnail"?String(t.title??"").toUpperCase().slice(0,Math.max(0,Math.floor(Number(t.thumbnailTitleChars)||0))||void 0):""};return s._overlayKey=Yf(n,i),s._cohortPriority=s.priority,s._cohortBand=0,s._cohortHash=dv(n,i),s._cohortSourceId=i,s._overlayImageSlot=s.requireImage&&s.image&&Object.prototype.hasOwnProperty.call(s.image,"frame")?s.image:null,s._overlayLayout={},s}function og(e){if(!e||typeof e!="object")return null;const t=[e.near,e.nearValue,e.far,e.farValue].map(Number);if(!t.every(Number.isFinite))return null;const n=Math.max(0,t[0]),i=Math.max(0,t[1]),o=Math.max(n,t[2]),r=Math.max(0,t[3]);return{near:n,nearValue:i,far:o,farValue:r}}function WL(e){if(!e||typeof e!="object")return null;const t=[e.fullEnd,e.midEnd,e.end,e.midValue,e.endValue].map(Number);if(!t.every(Number.isFinite))return null;const n=Math.max(0,t[0]),i=Math.max(n,t[1]),o=Math.max(i,t[2]);return{fullEnd:n,midEnd:i,end:o,midValue:Math.max(0,t[3]),endValue:Math.max(0,t[4]),smoothToMid:e.smoothToMid===!0}}function rg(e={},t={}){const n=Number(e.collisionCapacity??t.collisionCapacity);return{visible:e.visible!==void 0?e.visible!==!1:t.visible!==!1,hideInCockpit:e.hideInCockpit!==void 0?e.hideInCockpit===!0:t.hideInCockpit===!0,alpha:ah(e.alpha,t.alpha??1),cohortLimit:Math.max(1,Math.min(Qd,Math.floor(Number(e.cohortLimit??t.cohortLimit)||Xd))),collisionCapacity:Number.isFinite(n)?Math.max(0,Math.floor(n)):Mv,moving:e.moving!==void 0?e.moving===!0:t.moving===!0,solveIntervalMs:Math.max(0,Number(e.solveIntervalMs??t.solveIntervalMs??Wf)||0)}}function Kl(e){return e.selected||e.pinned||e.protected||e.tracked||Zc(e)>=ln.get("selected")}function kv(e,t=Xd,n=new Set){const i=Math.max(1,Math.min(Qd,Math.floor(Number(t)||Xd))),o=[],r=new hv(i,Qd);for(const s of Array.isArray(e)?e:[])if(s){if(Kl(s)){o.push(s);continue}r.consider(s,n.has(s._overlayKey)||n.has(s.id))}return o.sort(HL),o.concat(r.values(i))}function Jc(e){return e.options.visible&&!(ql&&e.options.hideInCockpit)}function Av(e){let t=Zd.get(e);return t||(t={id:e,arbiter:new gv,candidates:[],candidateCount:0,candidateMap:new Map,protectedCandidates:[],protectedCount:0,protectedRects:[],protectedRectCount:0,sepX:[],sepY:[],sepR:[],sepSource:[],sepCount:0,renderEntries:[],demandBySource:new Map,capacity:Mv,lastSolveAt:Number.NEGATIVE_INFINITY,moving:!1,solveIntervalMs:Wf},Zd.set(e,t),Nt.push(t)),t}function Zf(e){const t=new Map;e.demandByDomain.clear();for(const i of e.entries.values())t.has(i.collisionGroup)||t.set(i.collisionGroup,[]),t.get(i.collisionGroup).push(i),Kl(i)||e.demandByDomain.set(i.collisionGroup,(e.demandByDomain.get(i.collisionGroup)||0)+1);let n=0;for(const[i,o]of t){const r=Av(i).arbiter.selectedKeys;e.cohortDomainIds[n]=i,e.cohortLists[n]=kv(o,e.options.cohortLimit,r),n++}e.cohortCount=n,e.cohortDomainIds.length=n,e.cohortLists.length=n}function Jf(e,t={}){const n=ba(e);let i=$i.get(n);return i?t&&Object.keys(t).length>0&&(i.options=rg(t,i.options)):(i={id:n,entries:new Map,cohortDomainIds:[],cohortLists:[],cohortCount:0,demandByDomain:new Map,options:rg(t)},$i.set(n,i),Gi.push(i)),i}function Ut({solve:e=!0,layout:t=!1}={}){var n,i;e&&(li=!0),t&&(ai=!0),Ho=!0,Ai=0,zi=0,Xc.clear(),(i=(n=tt==null?void 0:tt.scene)==null?void 0:n.requestRender)==null||i.call(n)}function KL(){return{surface:null,setActive(){},requestPaint(){},unregister(){}}}function Yl(e,t,n={}){if(Dt)return KL();if(!ln.has(e))throw new TypeError(`Unsupported WorldOverlay paint lane: ${e}`);if(typeof t!="function")throw new TypeError("WorldOverlay custom paint lane requires a painter callback");const i=ba(n.id||e),o=Zi.get(i);if(o){const a=Ft.indexOf(o);a>=0&&Ft.splice(a,1)}const r={id:i,lane:ln.get(e),painter:t,active:n.active===!0,target:n.target===Is?Is:vv,shouldPaint:typeof n.shouldPaint=="function"?n.shouldPaint:null};return Zi.set(i,r),Ft.push(r),Ut({solve:!1}),{get surface(){return r.target===Is?lt:dt},setActive(a){if(Dt||Zi.get(i)!==r)return;const c=a===!0;r.active!==c&&(r.active=c,Ut({solve:!1}))},requestPaint(){Dt||Zi.get(i)!==r||Ut({solve:!1})},unregister:()=>{if(Zi.get(i)!==r)return;Zi.delete(i);const a=Ft.indexOf(r);a>=0&&Ft.splice(a,1),r.active=!1,Ut({solve:!1})}}}function Ca(e,t,n={}){if(Dt)return;if(!Array.isArray(t))throw new TypeError("WorldOverlay entries must be an array");const i=Jf(e,n),o=t.map(s=>Qf(i.id,s)),r=new Map;for(const s of o)r.set(s.id,s);for(const s of i.entries.values())r.has(s.id)||Or.delete(s._overlayKey);i.entries=r,Zf(i),Ma(),Ut()}function YL(e,t){if(Dt)return;const n=Jf(e),i=Qf(n.id,t);n.entries.set(i.id,i),Zf(n),Ma(),Ut()}function XL(e,t){if(Dt)return!1;const n=$i.get(ba(e));if(!n)return!1;const i=String(t);return n.entries.delete(i)?(Or.delete(Yf(n.id,i)),Zf(n),Ma(),Ut(),!0):!1}function ya(e){if(Dt)return!1;const t=$i.get(ba(e));if(!t)return!1;for(const n of t.entries.values())Or.delete(n._overlayKey);return t.entries.clear(),t.cohortDomainIds.length=0,t.cohortLists.length=0,t.cohortCount=0,t.demandByDomain.clear(),Ma(),Ut(),!0}function va(e,t){if(Dt)return;const n=Jf(e),i=t!==!1;n.options.visible!==i&&(n.options.visible=i,Ut())}function Ma(){const e={};let t=0;for(const[n,i]of $i)e[n]=i.entries.size,t+=i.entries.size;et.sourceCount=$i.size,et.entryCount=t,et.entriesBySource=e}function Iv(e,t){if(Dt)return null;const n=Yf(String(e),String(t)),i=Xc.get(n);return i&&i.key===n&&i.stamp===Dr?i:null}function Rv(e,t,n={}){if(Dt||!Number.isFinite(e)||!Number.isFinite(t))return null;for(let i=zi-1;i>=0;i--){const o=Qc[i];if(!(n.sourceId&&o.sourceId!==n.sourceId)&&!(n.collisionGroup&&o.entry.collisionGroup!==n.collisionGroup)&&!(typeof n.filter=="function"&&!n.filter(o.entry))&&!(eo.x+o.w||to.y+o.h))return{sourceId:o.sourceId,entryId:o.entryId,entry:o.entry,rect:o}}return null}function Lv(){const e={};for(let t=0;t0&&(e[n]=i)}return{...et,entriesBySource:{...et.entriesBySource},paintedBySource:e}}function Pv(e,t,n,i,o){if(!t||!Number.isFinite(t.x)||!Number.isFinite(t.y)||!Number.isFinite(t.z)||(e==null?void 0:e.horizonCull)!==!1&&(o!=null&&o.isPointVisible)&&!o.isPointVisible((e==null?void 0:e.cullPosition)||t))return!1;const r=n==null?void 0:n.x,s=n==null?void 0:n.y;if(!Number.isFinite(r)||!Number.isFinite(s))return!1;const a=Math.max(0,Number(e==null?void 0:e.viewportPadding)||0);return r>=-a&&r<=i.width+a&&s>=-a&&s<=i.height+a}function Xl(e,t,n=t.length){for(let i=0;io.x&&e.yo.y)return!0}return!1}function xv(e,t,n=t.length){for(let i=0;io.x&&e.yo.y)return!0}return!1}function QL(e,t,n){let i=null,o=Number.POSITIVE_INFINITY;for(let r=0;r0&&d>0&&(c+=h*d)}ct1}function o1(e,t,n=!1){const i=Ui.length,o=sh[i]||(sh[i]={});o.hard=n,o.x=e.left-t.left-Pa,o.y=e.top-t.top-Pa,o.w=e.width+Pa*2,o.h=e.height+Pa*2,Ui.push(o)}function r1(e,t=!1){var r,s,a,c,l;if(!dt||!ai)return!1;const n=e-Wl;if(!t&&n{var u,h;wr=null,(h=(u=tt==null?void 0:tt.scene)==null?void 0:u.requestRender)==null||h.call(u)},Math.max(0,ig-n))),!1;Wl=e,ai=!1,Ui.length=0;const i=((r=dt.getBoundingClientRect)==null?void 0:r.call(dt))||{left:0,top:0},o=new Set;for(const u of Kc){const h=((s=document.querySelectorAll)==null?void 0:s.call(document,u))||[(a=document.querySelector)==null?void 0:a.call(document,u)].filter(Boolean);for(const d of h){if(o.has(d)||!e1(d))continue;o.add(d),dn&&!Mr.has(d)&&(dn.observe(d),(c=vt==null?void 0:vt.observe)==null||c.call(vt,d,Fv),Mr.add(d));const f=(l=d.getBoundingClientRect)==null?void 0:l.call(d);!f||f.width<=0||f.height<=0||o1(f,i,!i1(d))}}return li=!0,Yc++,!0}function ag(){_a=!0,ai=!0,eu()&&Ut({solve:!0,layout:!0})}function lg(){ai=!0,eu()&&Ut({solve:!0})}const Fv=Object.freeze({attributes:!0,attributeFilter:Object.freeze(["class","style","hidden"])});function s1(e){if(!e||typeof e.matches!="function")return!1;for(const t of Kc)if(e.matches(t)||typeof e.querySelector=="function"&&e.querySelector(t))return!0;return!1}function cg(e){if(!e)return!1;for(let t=0;t0)||!(e.height>0)||((n=t.setTransform)==null||n.call(t,1,0,0,1,0,0),t.clearRect(0,0,e.width,e.height),(i=t.setTransform)==null||i.call(t,Nr,0,0,Nr,0,0))}function Ql(e=!0,t=!0){e&&(ug(dt,It),Ho=!1),t&&(ug(lt,ga),$o=!1)}function c1(){let e=0;for(let t=0;t0&&e-o.leaderAnimationStartedAt0||c1()>0)return!0;if(!li)return Sv(e)>0;for(let t=0;t0)return!0;return!1}function d1(){const e=tt.camera,t=Cesium.Matrix4.multiply(e.frustum.projectionMatrix,e.viewMatrix,Ev);return xt.m0=t[0],xt.m1=t[1],xt.m3=t[3],xt.m4=t[4],xt.m5=t[5],xt.m7=t[7],xt.m8=t[8],xt.m9=t[9],xt.m11=t[11],xt.m12=t[12],xt.m13=t[13],xt.m15=t[15],xt}function h1(e,t){const n=d1(),i=tt.camera.positionWC;return(i.x!==Jd||i.y!==eh||i.z!==th)&&(na.cameraPosition=i,Jd=i.x,eh=i.y,th=i.z),Je.canvas=dt,Je.surface=dt,Je.ctx=It,Je.width=In,Je.height=fn,Je.dpr=Nr,Je.timestamp=e,Je.cameraPosition=i,Je.occluder=na,Je.keyhole=t,Je.uiRectCount=Ui.length,Je.layoutRevision=Yc,n}function f1(e){let t=Or.get(e._overlayKey);return t||(t={key:e._overlayKey,entry:e,position:new Cesium.Cartesian3,screen:{x:0,y:0},layout:e._overlayLayout,placements:[],candidate:null,distanceAlpha:1,paintScale:1,altitudeAlpha:1,sourceAlpha:1,protectedPlacement:null,distanceOptions:{},altitudeOptions:{},placementInput:{},scaledPaintPlacement:{rect:{}}},t.candidate={key:t.key,layerId:e.source,sourceId:e.id,priority:e.priority,centerDistance:0,keyholeAlpha:1,placements:t.placements,screenX:0,screenY:0,frameStamp:0,_anchorX:0,_anchorY:0,_record:t},Or.set(t.key,t)),t.entry=e,t.layout=e._overlayLayout,t.candidate.layerId=e.source,t.candidate.sourceId=e.id,t.candidate.priority=e.priority,t.candidate.stateless=e.stateless,t.distanceOptions.minDistance=e.minDistance,t.distanceOptions.maxDistance=e.maxDistance,t.distanceOptions.fadeStartRatio=e.distanceFadeStartRatio,t.altitudeOptions.minAltitude=e.minAltitude,t.altitudeOptions.fadeStart=e.altitudeFadeStart,t.altitudeOptions.fadeEnd=e.altitudeFadeEnd,t}function m1(){for(let e=0;e0))return null;const u=1/l;if(o.screen.x=((n.m0*s+n.m4*a+n.m8*c+n.m12)*u*.5+.5)*In,o.screen.y=(.5-(n.m1*s+n.m5*a+n.m9*c+n.m13)*u*.5)*fn,e.safeTopRatio>0&&!(e.pinned&&e.pinnedBypassesSafeTop)){const w=Math.min(e.safeTopMaxPx,fn*e.safeTopRatio);if(o.screen.y=e.minDistance?1:0:yL(g,o.distanceOptions);const _=(M=tt.camera.positionCartographic)==null?void 0:M.height;o.paintScale=e.distanceScale?Xp(g,e.distanceScale):1;const m=e.altitudeScale;if(m&&Number.isFinite(_)){let w=1;if(_>m.fullEnd)if(_<=m.midEnd){const E=Math.max(1,m.midEnd-m.fullEnd);let k=Math.max(0,Math.min(1,(_-m.fullEnd)/E));m.smoothToMid&&(k=k*k*(3-2*k)),w=1+(m.midValue-1)*k}else if(_>=m.end)w=m.endValue;else{const E=(_-m.midEnd)/Math.max(1,m.end-m.midEnd);w=m.midValue+(m.endValue-m.midValue)*E}o.paintScale*=w}if(o.altitudeAlpha=e.altitudeFadeEnd===Number.POSITIVE_INFINITY?Number.isFinite(_)&&_0){const w=e.anchorRadiusScale?Xp(g,e.anchorRadiusScale):1,E=e.anchorRadiusPx*w;o.placementInput.gap=E+Math.max(e.minAnchorGapPx,E+e.anchorGapPaddingPx),o.placementInput.leaderOffset=E}else o.placementInput.gap=e.gapPx,o.placementInput.leaderOffset=e.leaderOffsetPx;o.placementInput.preferred=e.placement,o.placementInput.verticalOnly=e.verticalOnly,o.placementInput.viewportMargin=e.viewportMargin,kL(o.placementInput,o.placements);let b=0;for(let w=0;w0?e.minAnchorSeparationPx*o.paintScale:0,o.candidate.screenX=o.screen.x,o.candidate.screenY=o.screen.y,o}function g1(e,t){m1();let n=0,i=0;for(let r=0;r0)||!g.frame:!d.image)continue}const f=p1(d,s,t,e);if(!f)continue;const p=f.candidate.minAnchorSeparationPx;if(p>0&&!Kl(f.entry)){let g=!0;for(let m=0;mu.sepR[m]?p:u.sepR[m];if(b*b+C*C=s.solveIntervalMs;if(li||a){const l=Ii();s.arbiter.solve(s.candidates,{capacity:Math.min(s.capacity,s.candidates.length),demandByLayer:s.demandBySource,now:e,collectDiagnostics:!1}),t+=Ii()-l,s.lastSolveAt=e}for(let l=0;l=0;i--){const o=Qc[i],r=o.entry;!(r!=null&&r.accessibilityLabel)||typeof r.activate!="function"||gs.has(o.key)||(gs.set(o.key,r.activate),e.push({key:o.key,label:r.accessibilityLabel,selected:r.selected===!0}))}const t=e.map(i=>`${i.key}\0${i.label}\0${i.selected?"1":"0"}`).join("");if(t!==jl){if(jl=t,typeof $t.replaceChildren=="function")$t.replaceChildren();else for(;$t.firstChild;)$t.removeChild($t.firstChild);for(const i of e){const o=document.createElement("button");o.type="button",o.textContent=i.label,o.setAttribute("aria-label",i.label),o.setAttribute("aria-pressed",String(i.selected)),o.dataset.overlayActionKey=i.key,(n=o.addEventListener)==null||n.call(o,"click",()=>{const r=gs.get(i.key);if(!r)return;r()!==!1&&cn&&(cn.textContent=`Focusing ${i.label}`)}),$t.appendChild(o)}}}let Zl=!1;function y1(e){for(let t=0;t0||lh(vv)>0}function w1(e,t,n){const i=e.rect.x,o=e.rect.y;return n.corner=e.corner,n.rect.x=0,n.rect.y=0,n.rect.w=e.rect.w/t,n.rect.h=e.rect.h/t,n.centerX=(e.centerX-i)/t,n.centerY=(e.centerY-o)/t,n.anchorX=(e.anchorX-i)/t,n.anchorY=(e.anchorY-o)/t,n.leadFromX=(e.leadFromX-i)/t,n.leadFromY=(e.leadFromY-o)/t,n.paintScale=t,n.leaderOffset=e.leaderOffset,n.leaderOffset!==0&&(n.leaderOffset/=t),n.leadToX=(e.leadToX-i)/t,n.leadToY=(e.leadToY-o)/t,n}function hg(){et.candidateCount=0,et.projectedCount=0,et.selectedCount=0,et.fadingCount=0,et.paintedCount=0,et.hitRectCount=0,et.projectionMs=0,et.solveMs=0,et.paintMs=0;for(let e=0;e0&&((a=(s=tt.scene).requestRender)==null||a.call(s))}function Dv(e){var t,n,i,o,r,s,a;if(!((n=(t=e==null?void 0:e.scene)==null?void 0:t.postRender)!=null&&n.addEventListener))throw new TypeError("initWorldOverlay requires a Cesium viewer with scene.postRender");tt===e&&dt&&cr||(tt&&em(),Dt=!1,tt=e,ZL(),na=new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84,((i=e.camera)==null?void 0:i.positionWC)||new Cesium.Cartesian3),ql=!!((r=(o=document.body)==null?void 0:o.classList)!=null&&r.contains("cockpit-mode")),Rs=c=>{var l;ql=((l=c==null?void 0:c.detail)==null?void 0:l.active)===!0,Ut()},window.addEventListener("gev:cockpit-mode-changed",Rs),cr=e.scene.postRender.addEventListener(E1),(a=(s=e.camera)==null?void 0:s.moveEnd)!=null&&a.addEventListener&&(_s=e.camera.moveEnd.addEventListener(()=>Ut())),l1(),_a=!0,ai=!0,li=!0,Ho=!0,$o=!0,Ma())}function em(){var t,n,i,o,r,s;const e=tt!==null;cr==null||cr(),cr=null,_s==null||_s(),_s=null,Rs&&typeof window<"u"&&window.removeEventListener("gev:cockpit-mode-changed",Rs),Rs=null,Ls&&typeof window<"u"&&window.removeEventListener("resize",Ls),Ls=null,(t=dn==null?void 0:dn.disconnect)==null||t.call(dn),dn=null,Mr=new WeakSet,(n=vt==null?void 0:vt.disconnect)==null||n.call(vt),vt=null,CL(),wr!=null&&clearTimeout(wr),wr=null,(i=mt==null?void 0:mt.remove)==null||i.call(mt),(o=kt==null?void 0:kt.remove)==null||o.call(kt),(r=lt==null?void 0:lt.remove)==null||r.call(lt),typeof window<"u"&&((s=window.__gevWorldOverlay)==null?void 0:s.getDiagnostics)===Lv&&delete window.__gevWorldOverlay,$i.clear(),Gi.length=0;for(let a=0;ao.trim()).filter(Boolean);else{const o=n.split(" · ");i=o.length>1?[o[0].trim(),o.slice(1).join(" · ").trim()]:[n]}return{title:i[0]||"",details:i.slice(1),accent:t}}function Vv(e){if(!e||typeof e.gevDisplayPosition!="function")return null;try{return e.gevDisplayPosition()||null}catch{return null}}function Hv(e){if(e&&typeof e.gevVisualPosition=="function")try{const t=e.gevVisualPosition();if(t)return t}catch{}return Vv(e)}function A1(e){const t=String((e==null?void 0:e.gevTrackedId)||"").trim();if(t)return t;const n=String((e==null?void 0:e.id)||"").trim();return n?`entity:${n}`:null}function $v(){return(wn==null?void 0:wn.trackedEntity)||(Zt==null?void 0:Zt.entity)||null}function Gv(e){const t=e==null?void 0:e.gevLabelModel,n=A1(e);if(!n||!t||typeof e.gevDisplayPosition!="function")return null;const i=String(t.title||"").trim();return i?{id:n,position:()=>Hv(e),variant:"tracked",tracked:!0,protected:!0,paintLane:"tracked",collisionGroup:"ambient-card",priority:Number.MAX_SAFE_INTEGER,title:i,details:Array.isArray(t.details)?t.details.map(o=>String(o)):[],accent:t.accent||He.accent,cardStyle:t.cardStyle,selected:t.selected===!0,leaderStyle:t.leaderStyle,leaderAnimationMs:t.leaderAnimationMs,leaderAnimationStartedAt:t.leaderAnimationStartedAt,leaderDrawRatio:t.leaderDrawRatio,anchorRadiusPx:Number.isFinite(Number(t.anchorRadiusPx))?Math.max(0,Number(t.anchorRadiusPx)):10,anchorRadiusScale:Object.prototype.hasOwnProperty.call(t,"anchorRadiusScale")?t.anchorRadiusScale:T1,minAnchorGapPx:16,anchorGapPaddingPx:10,verticalOnly:!0,viewportMargin:6,edgeFade:"keyhole",horizonCull:!0,terrainOcclusion:!1,interactive:!1}:null}function nm(e){const t=Gv(e);if(!t){im();return}tm=t.id,Br.setEntries(Fo,[t],Ov),Br.setVisible(Fo,!0)}function im(){tm=null,Br.clearSource(Fo)}function xa(){nm($v())}function Uv(e){e&&e===$v()&&nm(e)}function zv(){return tm}const I1=new Set(["military-installations","alpr-cameras"]);function jv(e){var t,n;!e||wn===e||(wn&&om(),wn=e,Br.setVisible(Fo,!0),bs=((n=(t=e.trackedEntityChanged)==null?void 0:t.addEventListener)==null?void 0:n.call(t,()=>{e.trackedEntity&&(Zt=null),xa()}))||null,Ps=i=>{const o=i.detail;if(I1.has(o==null?void 0:o.layerId)){Zt=o,nm(o.entity);return}Zt&&(Zt=null,xa())},xs=i=>{var o;(!Zt||((o=i.detail)==null?void 0:o.layerId)===Zt.layerId)&&(Zt=null,xa())},Fs=()=>{Zt=null,wn!=null&&wn.trackedEntity||im()},window.addEventListener("gev:entity-selected",Ps),window.addEventListener("gev:entity-selection-cleared",xs),window.addEventListener("gev:awareness-subject-selected",Fs),xa(),console.log("[TrackedReadout] Initialized"))}function om(){bs==null||bs(),bs=null,Ps&&window.removeEventListener("gev:entity-selected",Ps),xs&&window.removeEventListener("gev:entity-selection-cleared",xs),Fs&&window.removeEventListener("gev:awareness-subject-selected",Fs),Ps=null,xs=null,Fs=null,Zt=null,im(),Br.setVisible(Fo,!1),wn=null}function R1(e=null){Br=e||Bv}const rm=Object.freeze(Object.defineProperty({__proto__:null,TRACKED_OVERLAY_SOURCE_ID:Fo,TRACKED_OVERLAY_SOURCE_OPTIONS:Ov,_setTrackedOverlayHostForTest:R1,cachedTrackedDisplayPosition:Vv,cachedTrackedVisualPosition:Hv,createTrackedOverlayEntry:Gv,destroyTrackedReadout:om,getActiveTrackedReadoutId:zv,initTrackedReadout:jv,refreshTrackedReadout:Uv,trackedLabelModelFromText:k1},Symbol.toStringTag,{value:"Module"})),Su="__gevContextStore";function L1(){return{entities:new Map,selectedEntityId:null,selectedAt:null}}function On(){return window[Su]||(window[Su]=L1()),window[Su]}function sm(){return typeof window<"u"&&!!window}function tu(e,t){if(!e||!(t!=null&&t.id))return null;const n=On(),i={...t,entity:e,updatedAt:Date.now()};return e.__gevContextId=t.id,n.entities.set(t.id,i),i}function qv(e){const t=On(),n=e==null?void 0:e.__gevContextId;if(!n||!t.entities.has(n))return null;t.selectedEntityId=n,t.selectedAt=Date.now();const i=t.entities.get(n);return window.dispatchEvent(new CustomEvent("gev:entity-selected",{detail:i})),i}function P1(e){var r;if(!sm()||!(e!=null&&e.id)||!(e!=null&&e.layerId))return null;const t=On(),n=String(e.id);for(const[s,a]of t.entities)(a==null?void 0:a.layerId)===e.layerId&&s!==n&&t.entities.delete(s);const i=((r=t.entities.get(n))==null?void 0:r.entity)||{__gevContextId:n},o=tu(i,{...e,id:n});return o?(t.selectedEntityId=n,t.selectedAt=Date.now(),o):null}function x1(e){if(!sm()||!(e!=null&&e.id)||!(e!=null&&e.layerId))return null;const t=On(),n=String(e.id),i=t.entities.get(n);return!i||i.layerId!==e.layerId?null:tu(i.entity,{...e,id:n})}function F1(e){if(!sm()||!e)return;const t=On();for(const[n,i]of t.entities)(i==null?void 0:i.layerId)===e&&t.entities.delete(n);t.selectedEntityId&&!t.entities.has(t.selectedEntityId)&&(t.selectedEntityId=null,t.selectedAt=null)}function am({dataManager:e=null}={}){const t=On();if(!t.selectedEntityId)return null;const n=t.entities.get(t.selectedEntityId);return!n||!lm(n,e)?(t.selectedEntityId=null,t.selectedAt=null,null):n}function Wv(e,{evicted:t=!1}={}){const n=On();if(!n.selectedEntityId)return;const i=n.entities.get(n.selectedEntityId);(i==null?void 0:i.layerId)===e&&(n.selectedEntityId=null,n.selectedAt=null,window.dispatchEvent(new CustomEvent("gev:entity-selection-cleared",{detail:{layerId:e,reason:t?"evicted":"deliberate"}})))}function Kv(e,{retainIds:t}={}){const n=On();for(const[i,o]of n.entities)(o==null?void 0:o.layerId)===e&&!(t!=null&&t.has(i))&&n.entities.delete(i);n.selectedEntityId&&!n.entities.has(n.selectedEntityId)&&(n.selectedEntityId=null,n.selectedAt=null,window.dispatchEvent(new CustomEvent("gev:entity-selection-cleared",{detail:{layerId:e,reason:"evicted"}})))}function lm(e,t=null){var n;return!(!e||((n=e.entity)==null?void 0:n.show)===!1||e.dataSource&&e.dataSource.show===!1||t&&e.layerId&&!t.isEnabled(e.layerId))}const Go=Object.freeze(Object.defineProperty({__proto__:null,clearSelectedEntityContextForLayer:Wv,clearTrackedSubjectContext:F1,getContextStore:On,getSelectedEntityContext:am,isContextRecordActive:lm,refreshTrackedSubjectContext:x1,registerEntityContext:tu,removeEntityContextsForLayer:Kv,selectEntityContext:qv,selectTrackedSubjectContext:P1},Symbol.toStringTag,{value:"Module"})),nu=Object.freeze({startLimbRatio:.5,scaleFloor:.45,alphaFloor:.35,combinedAlphaFloor:.2,globeViewBlendStartM:35e5,globeViewBlendEndM:45e5,earthRadiusM:6378137,writeEpsilon:.005});let Ri={...nu};const Yv={scale:1,alpha:1,limbRatio:null},as={scale:1,alpha:1,scaleWrites:0,alphaWrites:0,factors:Yv};function ao(e,t,n){return Math.min(n,Math.max(t,e))}function cm(e){return!e||e===Ri?Ri:{...Ri,...e}}function Xv(e,t,n,i){if(!Number.isFinite(e)||e<0||!Number.isFinite(t)||t<=0||t>=n.globeViewBlendEndM)return i.scale=1,i.alpha=1,i.limbRatio=null,i;const o=Qv(t,n.earthRadiusM);if(!Number.isFinite(o)||o<=0)return i.scale=1,i.alpha=1,i.limbRatio=null,i;const r=e/o;if(r<=n.startLimbRatio)return i.scale=1,i.alpha=1,i.limbRatio=r,i;const s=(r-n.startLimbRatio)/(1-n.startLimbRatio),a=ao(s,0,1),c=a*a*(3-2*a),l=(t-n.globeViewBlendStartM)/(n.globeViewBlendEndM-n.globeViewBlendStartM),u=ao(l,0,1),d=1-u*u*(3-2*u);return i.scale=1+(n.scaleFloor-1)*c*d,i.alpha=1+(n.alphaFloor-1)*c*d,i.limbRatio=r,i}function S1(e={}){const t={...Ri};return Number.isFinite(e.startLimbRatio)&&(t.startLimbRatio=ao(e.startLimbRatio,0,.99)),Number.isFinite(e.scaleFloor)&&(t.scaleFloor=ao(e.scaleFloor,.05,1)),Number.isFinite(e.alphaFloor)&&(t.alphaFloor=ao(e.alphaFloor,.05,1)),Number.isFinite(e.combinedAlphaFloor)&&(t.combinedAlphaFloor=ao(e.combinedAlphaFloor,.05,1)),Number.isFinite(e.globeViewBlendStartM)&&(t.globeViewBlendStartM=Math.max(1,e.globeViewBlendStartM)),Number.isFinite(e.globeViewBlendEndM)&&(t.globeViewBlendEndM=Math.max(t.globeViewBlendStartM+1,e.globeViewBlendEndM)),Number.isFinite(e.globeViewHeightM)&&(t.globeViewBlendEndM=Math.max(t.globeViewBlendStartM+1,e.globeViewHeightM)),t.globeViewBlendStartM>=t.globeViewBlendEndM&&(t.globeViewBlendStartM=Math.max(1,t.globeViewBlendEndM-1)),Number.isFinite(e.earthRadiusM)&&(t.earthRadiusM=Math.max(1,e.earthRadiusM)),Number.isFinite(e.writeEpsilon)&&(t.writeEpsilon=Math.max(0,e.writeEpsilon)),Ri=t,{...Ri}}function N1(){return Ri}function D1(){Ri={...nu}}function Qv(e,t=nu.earthRadiusM){return!Number.isFinite(e)||e<=0?Number.NaN:Math.sqrt(e*(2*t+e))}function O1({cameraDistanceM:e,cameraHeightM:t},n){const i=cm(n);return Xv(e,t,i,{scale:1,alpha:1,limbRatio:null})}function B1({billboard:e,baseScale:t,baseAlpha:n,baseColor:i,focusFactor:o,cameraDistanceM:r,cameraHeightM:s,params:a}){var g;const c=cm(a),l=Xv(r,s,c,Yv),u=t*l.scale,h=Math.max(c.combinedAlphaFloor,ao(o,0,1)*l.alpha),d=n*h;let f=0,p=0;return(!Number.isFinite(e.scale)||Math.abs(e.scale-u)>c.writeEpsilon)&&(e.scale=u,f=1),(!Number.isFinite((g=e.color)==null?void 0:g.alpha)||Math.abs(e.color.alpha-d)>c.writeEpsilon)&&(e.color=i.withAlpha(d),p=1),as.scale=u,as.alpha=d,as.scaleWrites=f,as.alphaWrites=p,as}function V1({model:e,baseColor:t,alpha:n,params:i}){var r;const o=cm(i);return!e||!t||!Number.isFinite(n)||Number.isFinite((r=e.color)==null?void 0:r.alpha)&&Math.abs(e.color.alpha-n)<=o.writeEpsilon?0:(e.color=t.withAlpha(n),1)}const Zv=Object.freeze(Object.defineProperty({__proto__:null,DEFAULT_AIRCRAFT_RECESSION_PARAMS:nu,aircraftRecessionFactors:O1,applyAircraftBillboardTreatment:B1,applyAircraftModelTreatment:V1,cameraLimbDistanceM:Qv,getAircraftRecessionParams:N1,resetAircraftRecessionParams:D1,setAircraftRecessionParams:S1},Symbol.toStringTag,{value:"Module"}));function H1({surface:e,source:t,militaryRegistry:n,resolveAsset:i=o=>`/${o.replace(/^\//,"")}`}){const{groundFloor:o,meshFloor:r,groundSnap:s}=e;return qI({source:t,resolveAsset:i,services:{picking:rn,sprites:Ki,trails:Df,aircraftPresentation:xy,camera:Dy,militaryRegistry:n,labels:Bf,groundFloor:o,meshFloor:r,geoid:wf,focus:ma,readout:rm,context:Go,render:Pt,groundSnap:s,recession:Zv}})}const $1=4500,fg=5,G1=1,U1=3,z1=2e4,ia=.7,lo=Cesium.Color.fromCssColorString("#FFB800"),oa=Cesium.Color.fromCssColorString("#FFD166"),um=.8,dl="/models/jet.glb",j1=8e5,q1=24,Jv=40,ch=200,W1=29.83,K1=1,Y1=150,X1=350,Q1=15e4,Z1=185e3,J1=60,eP=4e5,tP=45e4,mg=180,pg=.94,Nu="/models/airplane.glb",nP=1,iP=34.41,oP=6.719,rP=5.631,eM=lo.withAlpha(0),gg=6,sP=new Cesium.NearFarScalar(1e3,3,8e6,.5),Du="#FFB800",Fa=400,aP=500,lP=23,cP=80,uP=1e3,tM=60,nM=.25,Ou=900,_g=3,dP=1500,hP=40;function fP({flightState:e,records:t,groundFloor:n,meshFloor:i,militaryRegistry:o,rendering:r,tracking:s,queries:a}){const{warmGroundFloor:c,cachedGroundFloor:l,GROUND_FLOOR_LIFT_M:u}=n,{sampleMeshFloorCells:h}=i,{registerMilitaryIcaos:d}=o;return function(p,g){var C,y,v;const _=new Set,m=p.observedAtMs,b=[];for(const M of p.records){const w=M.id;_.add(w);const{prevMeta:E,meta:k,groundFlipped:T,fixEpochMs:I}=t.receive(M,{observedAtMs:m,floorWarmPoints:b,modelOwnsVisual:M.onGround?r._modelOwnsVisual(w):!1}),R=Cesium.Cartesian3.fromDegrees(k.rawLon,k.rawLat,k.renderAltitudeM);T&&e._groundSnap.forget(w),e._cullPositions.set(w,k.renderAltitudeM<10?Cesium.Cartesian3.fromDegrees(k.rawLon,k.rawLat,12):null);const S=w===e._trackedIcao,A=Cesium.JulianDate.fromDate(new Date(I));e._positionHistory.has(w)||e._positionHistory.set(w,[]);const L=e._positionHistory.get(w),F=L[L.length-1];if(!F||Cesium.JulianDate.greaterThan(A,F.time))L.push({time:A,epochMs:I,position:R.clone(),velocity:k.speedMps,track:k.track}),L.length>fg&&L.shift(),k.turnRateDps=Fl(L),S&&s._appendTrailFix(R.clone());else if(r._modelOwnsVisual(w)||ny(F,R,k.onGround),F.velocity!==k.speedMps||F.track!==k.track){const D=sy(F,{epochMs:Date.now(),velocity:k.speedMps,track:k.track,turnRateDps:k.turnRateDps});D&&(L.push(D),L.length>fg&&L.shift(),k.turnRateDps=Fl(L),S&&s._appendTrailFix(D.position.clone()))}if(e._billboards.has(w)){const P=e._billboards.get(w);((E==null?void 0:E.klass)!==k.klass||T||e._cockpitContactMode)&&r._applyFleetBillboardPresentation(w,P),(E==null?void 0:E.klass)!==k.klass&&r._syncModelToClass(w)}else{const P=e._billboardCollection.add({position:R,image:Nn(r._iconKind(w,k.klass)),width:S?24:20,height:S?24:20,scale:ia*(Oi[k.klass]||1)*(k.onGround?um:1),rotation:0,alignedAxis:Cesium.Cartesian3.ZERO,color:S?oa:lo,sizeInMeters:!1,scaleByDistance:r._normalBillboardScaleByDistance(),disableDepthTestDistance:r._groundDepthDistance(),id:w,show:!S});e._billboards.set(w,P),r._applyFleetBillboardPresentation(w,P)}S&&T&&!k.onGround&&s._startTrail(w),S&&e._trackedEntity&&(e.records.data.get(w),s._updateTrackedLabelModel(w))}c(b);for(const[M,w]of e.records.data){if(!(w!=null&&w.onGround)||_.has(M)||r._modelOwnsVisual(M)||!Number.isFinite(w.rawLat)||!Number.isFinite(w.rawLon))continue;const E=l(w.rawLat,w.rawLon);if(!Number.isFinite(E))continue;const k=E+u;if(Number.isFinite(w.renderAltitudeM)&&w.renderAltitudeM>=E-1)continue;w.renderAltitudeM=k,e._cullPositions.delete(M);const T=Cesium.Cartesian3.fromDegrees(w.rawLon,w.rawLat,k),I=e._positionHistory.get(M),R=I==null?void 0:I[I.length-1];R&&(R.position=Cesium.Cartesian3.clone(T,R.position));const S=e._billboards.get(M);S&&(S.position=T)}{const M=((y=(C=e._viewer)==null?void 0:C.camera)==null?void 0:y.positionCartographic)||null;h((v=e._viewer)==null?void 0:v.scene,b,{excludeObjects:[...e._billboards.values(),...e._models.values(),e._trackedModel].filter(Boolean),viewerLat:M?Cesium.Math.toDegrees(M.latitude):void 0,viewerLon:M?Cesium.Math.toDegrees(M.longitude):void 0})}for(const[M,w]of e._billboards){if(_.has(M))continue;const E=t.absence(M,{complete:p.complete,likelyLanded:a._likelyLanded(M)});if(E!=="retain"){if(E==="stale"){M===e._trackedIcao&&e._trackedEntity&&s._updateTrackedLabelModel(M);continue}M===e._trackedIcao&&s._clearTracking(!1,{evicted:!0}),e._billboardCollection.remove(w),e._billboards.delete(M),r._releaseModel(M),t.forget(M),e._cullPositions.delete(M),e._positionHistory.delete(M),e._displayCourse.delete(M),e._groundSnap.forget(M)}}return e._lastCamPoseSig="",d(_),{count:e._billboards.size,ids:_}}}class mP{constructor({geoidHeight:t,cachedGroundFloor:n,floorAltitudeM:i}){this.services={geoidHeight:t,cachedGroundFloor:n,floorAltitudeM:i},this.data=new Map,this.missingPolls=new Map,this.geoidNCache=new Map,this.geoidReady=!1}receive(t,{observedAtMs:n,floorWarmPoints:i,modelOwnsVisual:o}){const{geoidHeight:r,cachedGroundFloor:s,floorAltitudeM:a}=this.services,{id:c,longitude:l,latitude:u}=t;this.missingPolls.delete(c);const h=this.data.get(c),d=t.onGround,f=t.baroAltitudeM==null?null:t.baroAltitudeM/.3048,p=t.baroAltitudeM??(d?Number.isFinite(h==null?void 0:h.altitudeFt)?h.altitudeFt*.3048:0:3048),g=t.courseDeg||0,_=t.speedMps??0,m=t.verticalRateMps,b=t.callsign,C=t.typeCode,y=t.registration,v=t.operator,M=t.ellipsoidAltitudeM,w=t.baroAltitudeM;let E=this.geoidNCache.get(c);E===void 0&&this.geoidReady&&(E=r(u,l),this.geoidNCache.set(c,E));const k=ay({geoAltM:M,baroAltM:w,onGround:d,surfaceM:null,geoidN:E});let T=k??p;if(!d&&T<$1)T=a(T,s(u,l)),i.push({lat:u,lon:l});else if(d&&(i.push({lat:u,lon:l}),!o)){const A=s(u,l);Number.isFinite(A)&&(T=a(T,A))}const I=!!h&&h.onGround===!0!==d,R=lr(C,h==null?void 0:h.type),S={sourceReference:t.reference,observedReceiptMs:Date.now(),callsign:lr(b,h==null?void 0:h.callsign),type:R,klass:Lf({typeCode:R,category:t==null?void 0:t.category}),registration:lr(y,h==null?void 0:h.registration),operator:lr(v,h==null?void 0:h.operator),altitudeFt:un(f,h==null?void 0:h.altitudeFt,null),geoAltitudeM:M,renderAltitudeM:T,speedMps:un(_,h==null?void 0:h.speedMps,null),track:un(g,h==null?void 0:h.track,null),verticalRateMps:un(m,h==null?void 0:h.verticalRateMps,null),lastContactEpochMs:un(t.contactTimeMs,h==null?void 0:h.lastContactEpochMs,null),turnRateDps:(h==null?void 0:h.turnRateDps)||0,onGround:d,wasAirborne:(h==null?void 0:h.wasAirborne)===!0||!d,rawLat:u,rawLon:l};return this.data.set(c,S),{prevMeta:h,meta:S,groundFlipped:I,fixEpochMs:t.positionTimeMs??n}}absence(t,{complete:n,likelyLanded:i}){var s;if(!n&&Date.now()-(((s=this.data.get(t))==null?void 0:s.observedReceiptMs)??0)<3e5)return"retain";const o=(this.missingPolls.get(t)||0)+1;return o<(i?G1:U1)?(this.missingPolls.set(t,o),"stale"):(this.missingPolls.delete(t),"remove")}forget(t){this.data.delete(t),this.missingPolls.delete(t),this.geoidNCache.delete(t)}}function pP({feed:e,applySnapshot:t,setSourceLabel:n,applyPendingTrackingRestore:i}){return{methods:{async update(r,{signal:s=null}={}){const a=Date.now(),c=++e._trackingRefreshEpoch;if(e._lastTrackingRefreshOutcome={epoch:c,status:"source-unavailable",ids:new Set,source:e._lastSource},e._retryAt&&ar(B,q,{hot:e._irBoost});function v(B){return B===e._trackedIcao?oa:lo}function M(){var q,z,j;return e._models3dEnabled?(((j=(z=(q=e._viewer)==null?void 0:q.camera)==null?void 0:z.positionCartographic)==null?void 0:j.height)??1/0){const q=g(B);return`${q.url}@${q.scale}`};function P(B){var j;const q=F((j=e.records.data.get(B))==null?void 0:j.klass),z=e._models.get(B);if(z&&z._gevSpecKey!==q||!z&&e._modelPending.has(B)){const ne=e._billboards.get(B);ne&&B!==e._trackedIcao&&(ne.show=!0),x(B)}B===e._trackedIcao&&e._trackedModel&&e._trackedModel._gevSpecKey!==q&&W()}function O(){e._irReloadQueue=[...e._models.keys()];for(const B of e._modelPending)e._models.has(B)||e._modelGen.set(B,(e._modelGen.get(B)||0)+1);W()}function D(){if(!e._irReloadQueue)return;const B=e._irReloadQueue.splice(0,hP);for(const q of B){const z=e._models.get(q);if(!z||z._gevIrBoost===e._irBoost)continue;const j=e._billboards.get(q);j&&q!==e._trackedIcao&&(j.show=!0),x(q)}e._irReloadQueue.length===0&&(e._irReloadQueue=null)}async function $(B){var se,me,be;if(B===e._trackedIcao||e._models.has(B)||e._modelPending.has(B)||e._models.size+e._modelPending.size>=w())return;const q=e._modelEpoch,z=e._modelGen.get(B)||0;e._modelPending.add(B);let j=null;const ne=F((se=e.records.data.get(B))==null?void 0:se.klass),ee=e._irBoost;try{const J=g((me=e.records.data.get(B))==null?void 0:me.klass);j=await Cesium.Model.fromGltfAsync({url:o(J.url),asynchronous:!1,minimumPixelSize:q1,scale:J.scale,color:e._irBoost?Cesium.Color.WHITE:v(B),colorBlendMode:Cesium.ColorBlendMode.MIX,colorBlendAmount:e._irBoost?1:pg,customShader:e._irBoost?e._IR_UNLIT_SHADER:void 0,id:B})}catch{q===e._modelEpoch&&(e._modelPending.delete(B),N(B));return}if(q!==e._modelEpoch){try{j.destroy()}catch{}return}if(e._modelPending.delete(B),(e._modelGen.get(B)||0)!==z||!M()||!e._modelCollection||e._modelCollection.isDestroyed()||!e.records.data.has(B)||B===e._trackedIcao||e._models.has(B)||e._models.size>=w()||F((be=e.records.data.get(B))==null?void 0:be.klass)!==ne||e._irBoost!==ee){try{j.destroy()}catch{}N(B);return}j.id=B,j._gevSpecKey=ne,j._gevIrBoost=ee,j.show=!1,e._modelCollection.add(j),e._models.set(B,j),e._planeModelLoaded=!0}function x(B){const q=e._models.get(B),z=e._modelPending.has(B);if((q||z)&&e._modelGen.set(B,(e._modelGen.get(B)||0)+1),q){if(e._modelCollection&&!e._modelCollection.isDestroyed())try{e._modelCollection.remove(q)}catch{}e._models.delete(B)}N(B)}function N(B){!e._modelPending.has(B)&&!e._models.has(B)&&e._modelGen.delete(B)}function G(){e._irReloadQueue=null;for(const B of e._modelPending)e._modelGen.set(B,(e._modelGen.get(B)||0)+1);if(e._modelCollection&&!e._modelCollection.isDestroyed())for(const B of e._models.values())try{e._modelCollection.remove(B)}catch{}e._models.clear()}function W(){if(e._trackedModelGen++,e._trackedModelLoading=!1,e._trackedModel){if(e._modelCollection&&!e._modelCollection.isDestroyed())try{e._modelCollection.remove(e._trackedModel)}catch{}e._trackedModel=null}}function V(){var z,j,ne,ee;if(!(e._trackedIcao&&n.tracking._trackedModelRegimeActive()&&e._modelCollection&&!e._modelCollection.isDestroyed())){e._trackedModel&&(e._trackedModel.show=!1);return}const q=n.motion._trackedDisplayPosition(e._trackedIcao)||((z=e._billboards.get(e._trackedIcao))==null?void 0:z.position);if(!q){e._trackedModel&&(e._trackedModel.show=!1);return}if(!e._trackedModel&&!e._trackedModelLoading&&n.tracking._trackedModelLoadAllowed()){e._trackedModelLoading=!0;const re=e._trackedModelGen,se=g((j=e.records.data.get(e._trackedIcao))==null?void 0:j.klass),me=F((ne=e.records.data.get(e._trackedIcao))==null?void 0:ne.klass),be=e._irBoost;Cesium.Model.fromGltfAsync({url:o(se.url),asynchronous:!1,minimumPixelSize:Jv,scale:se.scale,color:e._irBoost?Cesium.Color.WHITE:oa,colorBlendMode:Cesium.ColorBlendMode.MIX,colorBlendAmount:e._irBoost?1:pg,customShader:e._irBoost?e._IR_UNLIT_SHADER:void 0,id:e._trackedIcao}).then(J=>{var ae,oe;if(re!==e._trackedModelGen||!e._modelCollection||e._modelCollection.isDestroyed()){try{J.destroy()}catch{}return}if(F((ae=e.records.data.get(e._trackedIcao))==null?void 0:ae.klass)!==me||e._irBoost!==be){try{J.destroy()}catch{}e._trackedModelLoading=!1;return}J.id=e._trackedIcao,J._gevSpecKey=me,J.show=!1;const Z=n.motion._trackedDisplayCached()||((oe=e._billboards.get(e._trackedIcao))==null?void 0:oe.position);if(Z){const le=R(e._trackedIcao,Z,e._scratchGroundPos);le&&T(le,n.motion._trackedDisplayCourse(),J.modelMatrix,se.headingOffsetDeg)}e._trackedModel=J,e._trackedModelLoading=!1,e._trackedModelFailIcao=null,e._trackedModelFailCount=0,e._trackedModelRetryAtMs=0,e._modelCollection.add(J),e._planeModelLoaded=!0}).catch(J=>{re===e._trackedModelGen&&(e._trackedModelLoading=!1,n.tracking._noteTrackedModelLoadFailure(se.url,J))});return}if(e._trackedModel){const re=R(e._trackedIcao,q,e._scratchGroundPos);if(!re){e._trackedModel.show=!1;return}const se=g((ee=e.records.data.get(e._trackedIcao))==null?void 0:ee.klass);if(T(re,n.motion._trackedDisplayCourse(),e._trackedModel.modelMatrix,se.headingOffsetDeg),!e._trackedModel.ready)return;e._trackedModel.scale=a({baseScale:se.scale,nativeRadiusM:se.nativeRadiusM,rangeM:Cesium.Cartesian3.distance(e._viewer.camera.positionWC,re),viewportHeightPx:e._viewer.scene.canvas.clientHeight,fovyRad:e._viewer.camera.frustum.fovy,maximumPixelSize:ch}),e._trackedModel.show=!0}}function H(){var J,Z,ae;if(!e._viewer||!e._billboardCollection||!e._billboardCollection.show)return;const B=e._viewer.scene,q=e._viewer.camera,z=c(Date.now());if(z-e._lastFleetTickMs=uP;ee&&(e._lastCamPoseSig=ne,e._lastRotPassMs=z);const re=Vo(q),se=l(),me=M();!me&&(e._models.size||e._modelPending.size)&&G();let be=null;if(me){const oe=w(),le=q.positionWC,Y=E(),K=Y*Y,_e=k(),he=_e*_e,Ce=q.frustum.computeCullingVolume(le,q.directionWC,q.upWC),ye=[];for(const[pe,te]of e._billboards){if(pe===e._trackedIcao||s(pe))continue;const de=Cesium.Cartesian3.distanceSquared(le,te.position);de>he||(Cesium.Cartesian3.clone(te.position,e._scratchModelBS.center),ye.push([pe,de,Ce.computeVisibility(e._scratchModelBS)!==Cesium.Intersect.OUTSIDE]))}ye.sort((pe,te)=>pe[1]-te[1]),ye.length>oe&&z-e._lastModelCapWarnMs>5e3&&(console.warn(`[Data:Military] ${ye.length} planes in 3D range; capped at ${oe} (${e._models3dMode}). On-screen prioritized.`),e._lastModelCapWarnMs=z),be=new Set;for(const[pe,,te]of ye){if(be.size>=oe)break;te&&e._models.has(pe)&&be.add(pe)}for(const[pe,te,de]of ye){if(be.size>=oe)break;de&&te<=K&&!be.has(pe)&&be.add(pe)}for(const[pe,,te]of ye){if(be.size>=oe)break;!te&&e._models.has(pe)&&be.add(pe)}for(const[pe,te,de]of ye){if(be.size>=oe)break;!de&&te<=K&&!be.has(pe)&&be.add(pe)}const ve=[];for(const pe of e._models.keys())pe!==e._trackedIcao&&!be.has(pe)&&ve.push(pe);for(const pe of ve)x(pe)}for(const[oe,le]of e._billboards){if(oe===e._trackedIcao)continue;const Y=n.motion._deadReckon(oe,e._scratchFleetPos);Y&&Cesium.Cartesian3.distanceSquared(Y,le.position)>1&&(le.position=Y);const K=!re.isPointVisible(((J=e.records.data.get(oe))==null?void 0:J.cullPosition)||le.position),_e=!K&&!le.show;if(le.show===K&&(le.show=!K),K){const ke=e._models.get(oe);ke&&ke.show&&(ke.show=!1);continue}const he=e.records.data.get(oe),Ce=Cesium.Cartesian3.distance(q.positionWC,le.position),ye=u(le.scaleByDistance,Ce),ve=h(le,le.position,B,q,z,se,void 0,(le.width||20)*(le.scale||1)*ye*.5,(le.height||20)*(le.scale||1)*ye*.5),pe=e._cockpitContactMode&&e._cockpitNearContacts.has(oe),te=d({billboard:le,baseScale:e._cockpitContactMode&&!pe?1:b(oe),baseAlpha:e.records.missingPolls.get(oe)?.45:1,baseColor:lo,focusFactor:ve.factor,cameraDistanceM:Ce,cameraHeightM:(Z=q.positionCartographic)==null?void 0:Z.height});if(e._billboardLimbScale.set(le,te.factors.scale),!e._cockpitContactMode||pe){const ke=(le.width||20)*(le.scale||1)*ye*(globalThis.devicePixelRatio||1),Ne=le._gevIconLarge?ke>56:ke>76;Ne!==!!le._gevIconLarge&&(le._gevIconLarge=Ne,le.image=Nn(y(oe,(ae=e.records.data.get(oe))==null?void 0:ae.klass),Ne?Di:void 0))}const de=e._drCourseDeg!=null?e._drCourseDeg:he&&he.track||0,U=e._displayCourse.get(oe),Le=e._drCourseHold&&U!=null?U:Uc(U,de,Gc(e._drSpeedMps!=null?e._drSpeedMps:(he&&he.speedMps)??NaN,tM),j);if(e._displayCourse.set(oe,Le),me&&Y&&be.has(oe)&&!s(oe)){$(oe);const ke=e._models.get(oe);if(S(oe,ke,le,Y,Le,()=>{f({model:ke,baseColor:e._irBoost?Cesium.Color.WHITE:v(oe),alpha:e._irBoost?1:te.alpha})}))continue}if((!e._cockpitContactMode||pe)&&(ee||_e)){const ke=ri(B,le.position,Le,le.rotation);ke!==null&&Math.abs(ke-le.rotation)>.002&&(le.rotation=ke)}}}return{_groundDepthDistance:p,_modelSpec:g,_normalBillboardScaleByDistance:_,_cockpitBillboardScaleByDistance:m,_militaryBillboardScale:b,_applyFleetBillboardPresentation:C,_iconKind:y,_modelColor:v,_modelRegimeActive:M,_modelCap:w,_modelAddDistM:E,_modelKeepDistM:k,_modelMatrix:T,_groundSampleExclusions:I,_modelDisplayPosition:R,_driveFleetModelHandoff:S,_modelOwnsVisual:A,_modelIsRendering:L,_specKeyFor:F,_syncModelToClass:P,_reloadModelsForIrBoost:O,_drainIrReloadQueue:D,_ensureModel:$,_releaseModel:x,_cleanupModelGen:N,_releaseModels:G,_releaseTrackedModel:W,_updateTrackedModel:V,_fleetTick:H}}function CP({flightState:e,services:t,parts:n,layer:i,resolveAsset:o}){const{trackedModelScaleForPixelCap:r}=t.camera,{nearFarScalarValueAtDistance:s,clearFocusTarget:a,publishFocusTargetFromCachedPosition:c}=t.focus;function l(v,M){const w=e._positionHistory.get(v),E=e.records.data.get(v);if(!w||w.length===0)return e._drCourseDeg=null,e._drSpeedMps=null,e._drCourseHold=!1,null;const k=M||new Cesium.Cartesian3,T=Cesium.JulianDate.addSeconds(Cesium.JulianDate.now(),-15,e._scratchRenderTime);for(let A=w.length-1;A>=1;A--){const L=w[A-1],F=w[A];if(Cesium.JulianDate.lessThanOrEquals(L.time,T)&&Cesium.JulianDate.lessThanOrEquals(T,F.time)){const P=Cesium.JulianDate.secondsDifference(F.time,L.time),O=P>0?Cesium.JulianDate.secondsDifference(T,L.time)/P:1,D=Cesium.Cartesian3.distance(L.position,F.position),$=P>0?D/P:E&&E.speedMps||0,x=E&&E.track||0,N=Number.isFinite(L.track)?L.track:x,G=Number.isFinite(F.track)?F.track:N,W=xl(N,G,O),V=E&&E.klass==="helicopter"?0:Rf($),H=V>0?iy(L.position,F.position):null;return e._drCourseDeg=H!=null?xl(W,H,V):W,e._drSpeedMps=$,e._drCourseHold=$N&&(Cesium.Cartesian3.subtract(e._drPrevDisplay,E,e._drCorrection),e._drCorrectionStartMs=k)}else Cesium.Cartesian3.fromElements(0,0,0,e._drCorrection),e._drCorrectionStartMs=k-Ou;const I=k-e._drCorrectionStartMs,R=I>=Ou?0:1-I/Ou,S=Cesium.Cartesian3.multiplyByScalar(e._drCorrection,R,e._trackedPosHolder);Cesium.Cartesian3.add(E,S,S),Cesium.Cartesian3.clone(E,e._drPrevRaw),Cesium.Cartesian3.clone(S,e._drPrevDisplay),e._drPrevMs=k,e._drReconcileValid=!0,e._cachedDRPosition=S;const A=d(v,e._cachedDRPosition);return c({ownerLayer:"militaryFlights",id:v,scene:(O=e._viewer)==null?void 0:O.scene,camera:(D=e._viewer)==null?void 0:D.camera,displayPosition:e._cachedDRPosition,widthPx:A,heightPx:A}),S}function p(){return e._drReconcileValid&&e._drReconcileIcao===e._trackedIcao?e._cachedDRPosition:null}function g(){var v;if(e._trackedIcao&&n.rendering._modelOwnsVisual(e._trackedIcao)){const M=n.rendering._modelSpec((v=e.records.data.get(e._trackedIcao))==null?void 0:v.klass);return jc(e._trackedModel.modelMatrix,M.visualCenterNative,Number.isFinite(e._trackedModel.computedScale)?e._trackedModel.computedScale:M.scale,e._trackedVisualPos)}return p()}function _(){return!e._trackedIcao||!e._trackedModel||!n.rendering._modelOwnsVisual(e._trackedIcao)?null:Cesium.Matrix4.getTranslation(e._trackedModel.modelMatrix,e._scratchTrailClip)}function m(){var w;if(!e._trackedIcao||!e._trackedModel||!n.rendering._modelOwnsVisual(e._trackedIcao))return 0;const v=n.rendering._modelSpec((w=e.records.data.get(e._trackedIcao))==null?void 0:w.klass),M=Number.isFinite(e._trackedModel.computedScale)?e._trackedModel.computedScale:v.scale;return v.nativeRadiusM*M}function b(){var v;if(e._trackedIcao&&n.rendering._modelOwnsVisual(e._trackedIcao)){const M=n.rendering._modelSpec((v=e.records.data.get(e._trackedIcao))==null?void 0:v.klass);return py(e._trackedModel,M.trailAnchorNative,e._trackedTrailPos)}return p()}function C(){const v=e.records.data.get(e._trackedIcao),M=v&&v.track||0,w=e._drReconcileValid&&e._drReconcileIcao===e._trackedIcao&&e._cachedDRCourse!=null,E=w?e._cachedDRCourse:M,k=Date.now(),T=e._trackedCourseMs?Math.min(nM,(k-e._trackedCourseMs)/1e3):0;e._trackedCourseMs=k;const I=e._displayCourse.get(e._trackedIcao);if(w&&e._cachedDRHold&&I!=null)return I;const R=Gc(w?e._cachedDRSpeedMps:(v&&v.speedMps)??NaN,tM),S=Uc(I,E,R,T);return e._displayCourse.set(e._trackedIcao,S),S}function y(){e._drReconcileValid=!1,e._drReconcileIcao=null,e._cachedDRFrame=-1,e._cachedDRPosition=null,e._cachedDRCourse=null,e._cachedDRSpeedMps=null,e._cachedDRHold=!1,e._trackedCourseMs=0}return{_deadReckon:l,_extrapolateFix:u,_isTrackWarmingUp:h,_trackedFocusSizePx:d,_trackedDisplayPosition:f,_trackedDisplayCached:p,_trackedVisualCached:g,_trackedModelCenterWorld:_,_trackedModelEnvelopeM:m,_trackedTrailCached:b,_trackedDisplayCourse:C,_resetTrackedDisplay:y}}function yP({flightState:e,services:t,parts:n,layer:i,resolveAsset:o}){const{selectTrackedSubjectContext:r,refreshTrackedSubjectContext:s,clearTrackedSubjectContext:a}=t.context,{tr3bTypeLabel:c,isTr3b:l,tr3bConvertedIds:u}=t.aircraftPresentation,{trackedLabelModelFromText:h,refreshTrackedReadout:d}=t.readout,{floorAltitudeM:f,cachedGroundFloor:p,resolveGroundFloorCellsBounded:g}=t.groundFloor,{createTrail:_}=t.trails,{ensureGeoidReady:m,geoidHeight:b}=t.geoid,{clearFocusTarget:C}=t.focus,{applyTrackedCameraFrame:y}=t.camera,{resolvePickId:v,isOwnedByOtherLayer:M}=t.picking;function w(J,Z){typeof window>"u"||!window.dispatchEvent||typeof CustomEvent>"u"||window.dispatchEvent(new CustomEvent(J,{detail:Z}))}function E(J,Z="programmatic"){const ae=e._billboards.get(J),oe=e.records.data.get(J);return!(ae!=null&&ae.position)||!oe?!1:(e._trackedEntity&&(e._trackedEntity.gevSelectionOrigin=Z),w("gev:awareness-subject-selected",{layerId:"military",id:J,label:n.queries._toCleanText(oe.callsign)||n.queries._toCleanText(oe.registration)||J,position:Cesium.Cartesian3.clone(ae.position),origin:Z}),r(k(J)),!0)}function k(J){const Z=n.queries._describeFlight(J);if(!Z)return null;const ae=e.records.data.get(J),oe=Z.callsign||Z.registration||J;return{id:J,layerId:"military",layerName:"Military Flights",source:e.feed._lastSource,label:oe,latitude:Z.latitude,longitude:Z.longitude,properties:{name:oe,operator:n.queries._toCleanText(ae==null?void 0:ae.operator)||"",callsign:Z.callsign||"",registration:Z.registration||"",type:c(J,n.queries._toCleanText(ae==null?void 0:ae.type)||""),altitude:Z.onGround?"on ground":n.queries._formatAltitude(ae==null?void 0:ae.altitudeFt),speed:Number.isFinite(Z.velocityMps)?`${Math.round(Z.velocityMps*1.944)} kt`:"",heading:Number.isFinite(Z.track)?`${Math.round(Z.track)}°`:"",icao24:J,status:Z.stale?"stale (missed polls)":"live"}}}function T(J){return J==="user"||J==="voice"||J==="tool"}function I(){var le,Y;if(!e._cockpitContactMode||!((Y=(le=e._viewer)==null?void 0:le.camera)!=null&&Y.positionWC)){e._cockpitNearContacts.size&&(e._cockpitNearContacts=new Set);return}const J=e._cockpitNearContacts,Z=[];for(const[K,_e]of e._billboards)K===e._trackedIcao||!(_e!=null&&_e.position)||Z.push([K,Cesium.Cartesian3.distanceSquared(e._viewer.camera.positionWC,_e.position)]);const ae=by(J,Z,n.rendering._modelAddDistM(),n.rendering._modelKeepDistM());e._cockpitNearContacts=ae;let oe=!1;for(const[K,_e]of e._billboards)J.has(K)!==ae.has(K)&&(n.rendering._applyFleetBillboardPresentation(K,_e),oe=!0);oe&&(e._lastCamPoseSig="")}function R(J){var ae;const Z=J===!0;if(e._cockpitContactMode!==Z){e._cockpitContactMode=Z,Z?I():e._cockpitNearContacts=new Set,e._modelCollection&&(e._modelCollection.show=!0),(ae=e._trail)==null||ae.setVisible(!Z),e._trailHeadEntity&&(e._trailHeadEntity.show=!Z);for(const[oe,le]of e._billboards)n.rendering._applyFleetBillboardPresentation(oe,le);e._lastCamPoseSig="",e._lastFleetTickMs=0}}function S(J={}){const Z=(J==null?void 0:J.active)===!0;e._cockpitSubjectId=Z&&String((J==null?void 0:J.subjectId)||"").trim().toLowerCase()||null,R(Z)}function A(J,Z){const ae=e.records.missingPolls.get(Z)||e.feed._backoff?" · STALE":"",oe=(n.queries._toCleanText(J==null?void 0:J.callsign)||n.queries._toCleanText(J==null?void 0:J.registration)||Z)+ae,le=c(Z,n.queries._toCleanText(J==null?void 0:J.type)||"Type unknown"),Y=n.queries._toCleanText(J==null?void 0:J.registration)||"Reg unknown",K=n.queries._toCleanText(J==null?void 0:J.operator)||"Operator unknown",_e=n.queries._formatAltitude(J==null?void 0:J.altitudeFt),he=J!=null&&J.speedMps?Math.round(J.speedMps*1.944):null,Ce=he?`${_e} · ${he} kt`:_e;return[oe,`${le} · ${Y}`,`${K} · ${Ce}`].join(` +`)}function L(J){!e._trackedEntity||J!==e._trackedIcao||(e._trackedEntity.gevLabelModel=h(A(e.records.data.get(J),J),"#ffd166"),d(e._trackedEntity),s(k(J)))}function F(){var J,Z;!e._trackedIcao||!((J=e._trackedEntity)!=null&&J.billboard)||(e._trackedEntity.billboard.image=Nn(n.rendering._iconKind(e._trackedIcao,(Z=e.records.data.get(e._trackedIcao))==null?void 0:Z.klass),Di))}function P(J){var oe,le,Y;const Z=String(J||"").trim().toLowerCase();if(!Z)return!1;if(l(Z)){(e._models.has(Z)||e._modelPending.has(Z))&&n.rendering._releaseModel(Z);const K=e._billboards.get(Z);K&&Z!==e._trackedIcao&&(K.show=!0),Z===e._trackedIcao&&(n.rendering._releaseTrackedModel(),G())}const ae=e._billboards.get(Z);return ae&&n.rendering._applyFleetBillboardPresentation(Z,ae),Z===e._trackedIcao&&(F(),L(Z)),(Y=(le=(oe=e._viewer)==null?void 0:oe.scene)==null?void 0:le.requestRender)==null||Y.call(le),e._billboards.has(Z)||Z===e._trackedIcao}function O(){for(const J of u())(e._billboards.has(J)||J===e._trackedIcao)&&P(J)}function D(){e._trackedZoomLatched=!1,e._trackedZoomLatchIcao=null,e._trackedModelFailIcao=null,e._trackedModelFailCount=0,e._trackedModelRetryAtMs=0}function $(J=Date.now()){return e._trackedModelFailIcao!==e._trackedIcao?!0:e._trackedModelFailCount>=_g?!1:J>=e._trackedModelRetryAtMs}function x(J,Z){e._trackedModelFailIcao!==e._trackedIcao&&(e._trackedModelFailIcao=e._trackedIcao,e._trackedModelFailCount=0),e._trackedModelFailCount+=1,e._trackedModelRetryAtMs=Date.now()+dP,e._trackedModelFailCount>=_g&&console.warn(`[Data:Military] tracked 3D model gave up after ${e._trackedModelFailCount} failed loads of ${J} — this contact stays 2D until another is selected`,Z)}function N(){var J,Z,ae;return e._trackedZoomLatchIcao!==e._trackedIcao&&(e._trackedZoomLatchIcao=e._trackedIcao,e._trackedZoomLatched=!1),!e._trackedIcao||e._cockpitContactMode||l(e._trackedIcao)?(e._trackedZoomLatched=!1,!1):(e._trackedZoomLatched=yy((ae=(Z=(J=e._viewer)==null?void 0:J.camera)==null?void 0:Z.positionCartographic)==null?void 0:ae.height,e._trackedZoomLatched),e._trackedZoomLatched)}function G(){var oe;if(!e._trackedIcao||!e._viewer)return;const J=n.motion._trackedDisplayCached()||((oe=e._billboards.get(e._trackedIcao))==null?void 0:oe.position);if(!J)return;const Z=ri(e._viewer.scene,J,n.motion._trackedDisplayCourse(),e._lastTrackedRotation),ae=Dl(e._lastTrackedRotation,Z,0);ae!==null&&(e._lastTrackedRotation=ae)}function W(J){const Z=Cesium.Cartographic.fromCartesian(J,Cesium.Ellipsoid.WGS84,e._scratchTrailCarto);if(!Z)return J;const ae=Cesium.Math.toDegrees(Z.latitude),oe=Cesium.Math.toDegrees(Z.longitude),le=f(Z.height,p(ae,oe));return le==null||le===Z.height?J:Cesium.Cartesian3.fromDegrees(oe,ae,le)}function V(J){e._trailPositions.push(W(J)),e._trailPositions.length>Fa&&e._trailPositions.shift(),H()}function H(){e._trail&&e._trail.setPositions(e._trailPositions.length>1?e._trailPositions.slice(0,-1):e._trailPositions)}function B(J){var le;e._trailBackfillToken+=1,e._trailPositions=[];const Z=e._positionHistory.get(J)||[],ae=Cesium.JulianDate.addSeconds(Cesium.JulianDate.now(),-15,e._scratchWarmupTime);for(const Y of Z)Cesium.JulianDate.lessThanOrEquals(Y.time,ae)&&e._trailPositions.push(W(Cesium.Cartesian3.clone(Y.position)));!e._trail&&e._viewer&&(e._trail=_(e._viewer,{color:Du,width:2.5})),(le=e._trail)==null||le.setVisible(!e._cockpitContactMode),!e._trailHeadEntity&&e._viewer&&(e._trailHeadEntity=e._viewer.entities.add({id:`gev-trail:mil-head-${++e._trailHeadSeq}`,show:!e._cockpitContactMode,polyline:{positions:new Cesium.CallbackProperty(()=>{if(!e._trackedIcao||e._trailPositions.length<2||n.motion._isTrackWarmingUp())return[];const Y=n.motion._trackedTrailCached()||n.motion._trackedDisplayPosition(e._trackedIcao);if(!Y)return[];const K=e._trailPositions[e._trailPositions.length-2],_e=W(Cesium.Cartesian3.clone(Y)),he=gy(K,_e,n.motion._trackedModelCenterWorld(),n.motion._trackedModelEnvelopeM(),e._scratchTrailHead);return he?[he,_e]:[]},!1),width:2.5,material:Cesium.Color.fromCssColorString(Du).withAlpha(.9),depthFailMaterial:Cesium.Color.fromCssColorString(Du).withAlpha(.45),arcType:Cesium.ArcType.GEODESIC}})),H();const oe=Z.length?Cesium.JulianDate.toDate(Z[0].time).getTime()/1e3:1/0;q(J,e._trailBackfillToken,oe)}async function q(J,Z,ae){var he,Ce,ye;let oe=null;try{const ve=await((ye=(Ce=e.feed._source).getTrack)==null?void 0:ye.call(Ce,((he=e.records.data.get(J))==null?void 0:he.sourceReference)??J,{signal:AbortSignal.any([e.lifetime.signal,AbortSignal.timeout(8e3)])}));oe=(ve==null?void 0:ve.records)??null}catch{return}if(!oe||Z!==e._trailBackfillToken||J!==e._trackedIcao)return;await m();const le=[];for(const ve of oe){const pe=ve.observedAtMs/1e3,te=ve.latitude,de=ve.longitude;!Number.isFinite(te)||!Number.isFinite(de)||!Number.isFinite(pe)||pe>=ae||le.push({lat:te,lon:de,baroAltitudeM:ve.baroAltitudeM})}if(!le.length||(await g(le),Z!==e._trailBackfillToken||J!==e._trackedIcao))return;let Y=[],K=null;for(const{lat:ve,lon:pe,baroAltitudeM:te}of le){const de=te==null?null:te+b(ve,pe);let U=f(de,p(ve,pe));U==null&&(U=K??50),K=U,Y.push(Cesium.Cartesian3.fromDegrees(pe,ve,U))}const _e=Math.max(1,Fa-e._trailPositions.length);if(Y.length>_e){const ve=Math.ceil(Y.length/_e),pe=[];for(let te=0;teFa&&(e._trailPositions=e._trailPositions.slice(e._trailPositions.length-Fa)),H()}function z(){if(e._trailBackfillToken+=1,e._trailPositions=[],e._trail&&e._trail.clear(),e._trailHeadEntity&&e._viewer&&!e._viewer.isDestroyed())try{e._viewer.entities.remove(e._trailHeadEntity)}catch{}e._trailHeadEntity=null}function j(){z(),e._trail&&(e._trail.destroy(),e._trail=null)}function ne(J=!1,{evicted:Z=!1,origin:ae="programmatic"}={}){var le;if((le=e._trackedCameraFrameStop)==null||le.call(e),e._trackedCameraFrameStop=null,!e._trackedIcao){C("militaryFlights");return}const oe=e._trackedIcao;if(C("militaryFlights",oe),e._billboards.has(e._trackedIcao)){const Y=e._billboards.get(e._trackedIcao),K=e.records.data.get(e._trackedIcao);Y.show=!0,Y.width=20,Y.height=20,Y.scale=ia*(Oi[K==null?void 0:K.klass]||1)*(K!=null&&K.onGround?um:1),Y.color=lo,Y.rotation=e._lastTrackedRotation}e._lastCamPoseSig="",e._viewer&&!J&&(e._viewer.trackedEntity=void 0),e._trackedEntity&&(e._viewer.entities.remove(e._trackedEntity),e._trackedEntity=null),n.rendering._releaseTrackedModel(),D(),e._trackedIcao=null,n.rendering._applyFleetBillboardPresentation(oe,e._billboards.get(oe)),a("military"),w("gev:awareness-subject-cleared",{layerId:"military",id:oe,origin:ae,reason:Z?"evicted":"deliberate"}),n.motion._resetTrackedDisplay(),z()}function ee(){var Z;const J=e._pendingTrackingRestore;return!J||J.generation!==e._trackingIntentGeneration||!((Z=e._billboardCollection)!=null&&Z.show)||!e._billboards.has(J.id)?!1:(e._pendingTrackingRestore=null,se(J.id,{origin:J.origin}),!0)}function re(){e._trackingIntentGeneration+=1,e._pendingTrackingRestore=null}function se(J,{origin:Z="programmatic"}={}){var Ce,ye;ne(!1,{origin:Z});const ae=e._billboards.get(J),oe=e.records.data.get(J);if(!ae||!oe)return;e._trackedIcao=J,D(),e._cachedDRFrame=-1,e._lastTrackedRotation=ae.rotation||0,n.rendering._releaseModel(J),ae.show=!1;const le=()=>n.motion._trackedDisplayPosition(J)||ae.position,Y=new Cesium.CallbackProperty(()=>le(),!1);e._trackedEntity=e._viewer.entities.add({position:Y,trackingReferenceFrame:Cesium.TrackingReferenceFrame.ENU,billboard:{image:Nn(n.rendering._iconKind(e._trackedIcao,(Ce=e.records.data.get(e._trackedIcao))==null?void 0:Ce.klass),Di),width:28,height:28,scale:ia*(Oi[(ye=e.records.data.get(e._trackedIcao))==null?void 0:ye.klass]||1),color:new Cesium.CallbackProperty(()=>n.rendering._modelOwnsVisual(e._trackedIcao)?eM:oa,!1),sizeInMeters:!1,scaleByDistance:new Cesium.NearFarScalar(1e3,3,8e6,.5),alignedAxis:Cesium.Cartesian3.ZERO,disableDepthTestDistance:Number.POSITIVE_INFINITY,rotation:new Cesium.CallbackProperty(()=>{const ve=e.records.data.get(e._trackedIcao),pe=le();if(!ve||!pe||!e._viewer)return e._lastTrackedRotation;const te=ri(e._viewer.scene,pe,n.motion._trackedDisplayCourse(),e._lastTrackedRotation),de=Dl(e._lastTrackedRotation,te);return de!==null&&(e._lastTrackedRotation=de),e._lastTrackedRotation},!1)}}),e._trackedEntity.gevSelectionOrigin=Z,e._trackedEntity.gevTrackedId=`military:${J}`,e._trackedEntity.gevLabelModel=h(A(oe,J),"#ffd166");const K=oe!=null&&oe.altitudeFt?oe.altitudeFt*.3048:1500,_e=Math.min(Math.max(K*1.1+2500,3e3),3e4);e._trackedEntity.viewFrom=new Cesium.Cartesian3(0,-_e*.8,_e*.55),e._trackedEntity.gevDisplayPosition=n.motion._trackedDisplayCached,e._trackedEntity.gevVisualPosition=n.motion._trackedVisualCached,d(e._trackedEntity),e._viewer.camera.cancelFlight(),e._viewer.trackedEntity=e._trackedEntity,e._trackedCameraFrameStop=y(e._viewer,e._trackedEntity,e._trackedEntity.viewFrom)||null,B(J);const he=n.queries._toCleanText(oe.callsign)||n.queries._toCleanText(oe.registration)||J;E(J,Z),console.log(`[Data:Military] Tracking ${he} (${J})`)}function me(J){J.key==="Escape"&&e._trackedIcao&&(re(),ne(!1,{origin:"user"}))}function be(J){e._clickHandler||(e._trackedEntityChangedRemove||(e._trackedEntityChangedRemove=J.trackedEntityChanged.addEventListener(()=>{var Z;e._trackedIcao&&e._viewer&&e._viewer.trackedEntity&&e._viewer.trackedEntity!==e._trackedEntity&&ne(!0,{origin:((Z=e._viewer.trackedEntity)==null?void 0:Z.gevSelectionOrigin)||"programmatic"})})),e._clickHandler=new Cesium.ScreenSpaceEventHandler(J.scene.canvas),Ff(e._clickHandler,(Z,ae)=>{var le;if(!Pf(ae)||document.body.classList.contains("cockpit-mode"))return;const oe=J.scene.pick(Z.position);if(oe){if(oe.id===e._trackedEntity)return;if(e._trackedIcao){const K=typeof oe.id=="string"?oe.id:(le=oe.primitive)==null?void 0:le.id;if(oe.primitive===e._trackedModel||K===e._trackedIcao)return}const Y=oe.primitive;if(Y&&Y.id&&e._billboards.has(Y.id)){re(),se(Y.id,{origin:"user"});return}if(oe.id&&typeof oe.id=="string"&&e._billboards.has(oe.id)){re(),se(oe.id,{origin:"user"});return}}if(oe){const Y=v(oe);if(Y&&M("military",Y))return}xf(ae)&&e._trackedIcao&&(re(),ne(!1,{origin:"user"}))}),document.addEventListener("keydown",me))}return{_emitAwarenessEvent:w,_publishTrackedSelection:E,_contextSubjectMetadata:k,_isExplicitTrackingOrigin:T,_refreshCockpitNearContacts:I,_setCockpitContactMode:R,_applyCockpitState:S,_buildTrackedLabel:A,_updateTrackedLabelModel:L,_syncTrackedBillboardImage:F,_refreshTr3bContact:P,_refreshTr3bForStyle:O,_resetTrackedSelectionState:D,_trackedModelLoadAllowed:$,_noteTrackedModelLoadFailure:x,_trackedModelRegimeActive:N,_syncTracked2dRotation:G,_trailFloorPosition:W,_appendTrailFix:V,_refreshTrailDisplay:H,_startTrail:B,_backfillTrail:q,_clearTrail:z,_destroyTrail:j,_clearTracking:ne,_applyPendingTrackingRestore:ee,_cancelPendingTrackingRestore:re,_trackFlight:se,_onKeyDown:me,_installClickHandler:be}}function vP({flightState:e,services:t,parts:n,layer:i,resolveAsset:o}){function r(){for(const s of e.feed._activeUpdateControllers)s.abort();e.feed._activeUpdateControllers.clear()}return{_abortActiveUpdates:r}}function MP({flightState:e,services:t,parts:n,layer:i,resolveAsset:o}){const{clearFocusTarget:r}=t.focus,{registerSpriteCollection:s,restoreSpriteOrder:a}=t.sprites,{holdContinuousRender:c,releaseContinuousRender:l}=t.render,{ensureGeoidReady:u}=t.geoid,{registerPickOwner:h,unregisterPickOwner:d}=t.picking,{setMilitaryLayerActive:f}=t.militaryRegistry;return{methods:{setSource(g){if(e._viewer)throw new Error("Configure the source before layer initialization");if(typeof(g==null?void 0:g.getSnapshot)!="function")throw new TypeError("A snapshot source is required");e.feed._source=g,e.feed._lastSource=g.label||e.feed._lastSource,this.source=e.feed._lastSource},init(g){var _;if(e._viewer)throw new Error("Flight layer is already initialized");if(typeof((_=e.feed._source)==null?void 0:_.getSnapshot)!="function")throw new TypeError("A snapshot source is required");if(e.lifetime.signal.aborted&&(e.lifetime=new AbortController),r("militaryFlights"),e._viewer=g,e._billboardCollection=new Cesium.BillboardCollection,g.scene.primitives.add(e._billboardCollection),s("military",e._billboardCollection),e._modelCollection=new Cesium.PrimitiveCollection,g.scene.primitives.add(e._modelCollection),!e._preloadModel){const m=e._modelEpoch;Cesium.Model.fromGltfAsync({url:o(dl),asynchronous:!1}).then(b=>{if(m===e._modelEpoch)e._preloadModel=b,e._planeModelLoaded=!0;else try{b.destroy()}catch{}}).catch(()=>{})}e._billboards=new Map,e._cullPositions.clear(),e._detectionObjects=new Map,e.records.data=new Map,e._positionHistory=new Map,e._displayCourse.clear(),e._groundSnap.clear(),e.feed._count=0,e.feed._lastUpdate=null,e.feed._backoff=!1,e.feed._retryAt=0,e.feed._lastError=null,e.feed._lastStatus=null,e._trackedIcao=null,n.tracking._resetTrackedSelectionState(),e._trackedEntity=null,e._cockpitSubjectId=null,e._cockpitContactMode=document.body.classList.contains("cockpit-mode"),e._cockpitNearContacts=new Set,e._cockpitModeListener||(e._cockpitModeListener=m=>n.tracking._applyCockpitState(m==null?void 0:m.detail),window.addEventListener("gev:cockpit-mode-changed",e._cockpitModeListener)),n.tracking._installClickHandler(g),a(g),console.log("[Data:Military] Initialized with billboard icons")},enable(g){if(e._billboardCollection&&(e._billboardCollection.show=!0),c("military"),e._modelCollection&&(e._modelCollection.show=!0),n.tracking._setCockpitContactMode(document.body.classList.contains("cockpit-mode")),!e.records.geoidReady){const _=e.lifetime;u().then(()=>{_.signal.aborted||(e.records.geoidReady=!0)}).catch(()=>{})}n.tracking._installClickHandler(g),h("military",_=>e._billboards.has(_)),f(!0),e._lastCamPoseSig="",!e._preRenderRemove&&(g!=null&&g.scene)&&(e._preRenderRemove=g.scene.preRender.addEventListener(n.rendering._fleetTick)),!e._trackedModelPreUpdateRemove&&(g!=null&&g.scene)&&(e._trackedModelPreUpdateRemove=g.scene.preUpdate.addEventListener(n.rendering._updateTrackedModel)),!e._moveEndRemove&&(g!=null&&g.camera)&&(e._moveEndRemove=g.camera.moveEnd.addEventListener(()=>{e._lastCamPoseSig="",e._lastFleetTickMs=0})),a(g)},disable(g){n.controller._abortActiveUpdates(),n.tracking._cancelPendingTrackingRestore(),e._billboardCollection&&(e._billboardCollection.show=!1),l("military"),n.rendering._releaseModels(),e._modelCollection&&(e._modelCollection.show=!1),n.tracking._clearTracking(),n.tracking._destroyTrail(),e._clickHandler&&(e._clickHandler.destroy(),e._clickHandler=null),e._trackedEntityChangedRemove&&(e._trackedEntityChangedRemove(),e._trackedEntityChangedRemove=null),document.removeEventListener("keydown",n.tracking._onKeyDown),d("military"),f(!1),e._preRenderRemove&&(e._preRenderRemove(),e._preRenderRemove=null),e._trackedModelPreUpdateRemove&&(e._trackedModelPreUpdateRemove(),e._trackedModelPreUpdateRemove=null),e._moveEndRemove&&(e._moveEndRemove(),e._moveEndRemove=null)},destroy(g){if(e.lifetime.abort(),n.controller._abortActiveUpdates(),l("military"),n.tracking._clearTracking(),n.tracking._destroyTrail(),n.tracking._cancelPendingTrackingRestore(),e._clickHandler&&(e._clickHandler.destroy(),e._clickHandler=null),e._trackedEntityChangedRemove&&(e._trackedEntityChangedRemove(),e._trackedEntityChangedRemove=null),document.removeEventListener("keydown",n.tracking._onKeyDown),e._cockpitModeListener&&(window.removeEventListener("gev:cockpit-mode-changed",e._cockpitModeListener),e._cockpitModeListener=null),d("military"),e._preRenderRemove&&(e._preRenderRemove(),e._preRenderRemove=null),e._trackedModelPreUpdateRemove&&(e._trackedModelPreUpdateRemove(),e._trackedModelPreUpdateRemove=null),e._moveEndRemove&&(e._moveEndRemove(),e._moveEndRemove=null),n.rendering._releaseModels(),e._billboardCollection&&(g.scene.primitives.remove(e._billboardCollection),e._billboardCollection=null),e._modelCollection&&(g.scene.primitives.remove(e._modelCollection),e._modelCollection=null),e._modelEpoch+=1,e._modelPending.clear(),e._modelGen.clear(),e._preloadModel){try{e._preloadModel.destroy()}catch{}e._preloadModel=null}e._planeModelLoaded=!1,e._billboards.clear(),e._cullPositions.clear(),e._detectionObjects.clear(),e.records.data.clear(),e._positionHistory.clear(),e._displayCourse.clear(),e._groundSnap.clear(),e.records.missingPolls.clear(),e.feed._count=0,e.feed._lastUpdate=null,e._cockpitContactMode=!1,e._cockpitNearContacts=new Set,e._cockpitSubjectId=null,e.feed._trackingRefreshEpoch+=1,e.feed._lastTrackingRefreshOutcome={epoch:e.feed._trackingRefreshEpoch,status:"destroyed",ids:new Set,source:e.feed._lastSource},n.tracking._resetTrackedSelectionState(),e._viewer=null}}}}function wP({flightState:e,services:t,parts:n,layer:i,resolveAsset:o}){function r({icao24:_,entity:m,meta:b,billboard:C,billboardCollection:y,viewer:v,history:M=[],tracked:w=!0,models:E=[],modelCollection:k=null}){e._viewer=v,e._modelCollection=k,e._billboardCollection=y,e._billboards=new Map([[_,C]]),e._cullPositions.clear(),e._models.clear();for(const[T,I]of E)e._models.set(T,I);e._detectionObjects=new Map,e.records.data=new Map([[_,b]]),e._positionHistory=new Map([[_,M]]),e.records.missingPolls=new Map,e._displayCourse.clear(),e.records.geoidNCache.clear(),e._trackedIcao=w?_:null,e._trackedEntity=w?m:null,e._trackedModel=null,n.tracking._cancelPendingTrackingRestore(),e._trackedModelLoading=!1,e.feed._backoff=!1,e.feed._retryAt=0}function s({status:_="accepted",ids:m=[],source:b=e.feed._lastSource}={}){const C=++e.feed._trackingRefreshEpoch;e.feed._lastTrackingRefreshOutcome={epoch:C,status:_,ids:new Set(m.map(y=>String(y).trim().toLowerCase())),source:b}}function a({icao24:_,meta:m,billboard:b,history:C=[]}){e._billboards.set(_,b),e.records.data.set(_,m),e._positionHistory.set(_,C)}function c(){var _;return((_=e._pendingTrackingRestore)==null?void 0:_.id)??null}function l(){return n.tracking._applyPendingTrackingRestore()}function u(_,m=null){n.tracking._applyCockpitState({active:_,subjectId:m})}function h(){return n.tracking._trackedModelRegimeActive()}function d(){return n.rendering._updateTrackedModel()}function f(){return n.rendering._modelOwnsVisual(e._trackedIcao)?eM:oa}function p({icao24:_,position:m,course:b=0}){return n.rendering._driveFleetModelHandoff(_,e._models.get(_),e._billboards.get(_),m,b)}async function g(_){return await n.rendering._ensureModel(_),e._models.get(_)||null}return{_setTrackedMilitaryRefreshStateForTest:r,_setMilitaryTrackingRefreshOutcomeForTest:s,_addMilitaryTrackingCandidateForTest:a,_pendingMilitaryTrackingRestoreForTest:c,_applyPendingMilitaryTrackingRestoreForTest:l,_setCockpitDetectionSubjectForTest:u,_trackedModelRegimeActiveForTest:h,_updateTrackedModelForTest:d,_trackedBillboardColorForTest:f,_driveFleetModelHandoffForTest:p,_ensureFleetModelForTest:g}}function EP({flightState:e,services:t,parts:n,layer:i,resolveAsset:o}){const{tr3bAircraftClass:r,tr3bTypeLabel:s}=t.aircraftPresentation,{formatFlightLevel:a}=t.labels,{applyTrackedCameraFrame:c}=t.camera;function l(m){if(typeof m=="number"&&Number.isFinite(m))return m;if(typeof m=="string"){const b=Number.parseFloat(m.trim());return Number.isFinite(b)?b:null}return null}function u(m){return String(m||"").trim()}function h(m){return Number.isFinite(m)?`${Math.round(m)} ft`:"Alt unknown"}function d(m){const b=e.records.data.get(m);return!b||b.wasAirborne!==!0?!1:b.onGround?!0:Number.isFinite(b.altitudeFt)&&b.altitudeFtNumber.isFinite(M)?M:null,y=M=>String(M??"").trim()||null,v=y(b==null?void 0:b.callsign);return{id:v||y(b==null?void 0:b.registration)||m,icao24:m,callsign:v,lat:C(b==null?void 0:b.rawLat),lon:C(b==null?void 0:b.rawLon),altitudeM:Number.isFinite(b==null?void 0:b.altitudeFt)?b.altitudeFt*.3048:null,speedMps:C(b==null?void 0:b.speedMps),heading:C(b==null?void 0:b.track),verticalRateMps:C(b==null?void 0:b.verticalRateMps),onGround:(b==null?void 0:b.onGround)===!0,military:!0,aircraftClass:r(m,y(b==null?void 0:b.klass)),originCountry:null,operator:y(b==null?void 0:b.operator),routeOrigin:null,routeDestination:null}}const _={mapAnalystRecord:g,id:"military",name:"Military Flights",icon:"🎖️",source:e.feed._lastSource,updateInterval:15e3,show(m){this.enable(m)},hide(m){this.disable(m)},setParams(m={},{origin:b="programmatic"}={}){if(Mo(b)&&!Object.hasOwn(m,"selectedMilitaryTrackingId")&&n.tracking._cancelPendingTrackingRestore(),typeof m.models3d=="boolean"&&m.models3d!==e._models3dEnabled&&(e._models3dEnabled=m.models3d,!e._models3dEnabled&&(n.rendering._releaseModels(),n.tracking._syncTracked2dRotation(),e._billboardCollection)))for(const[C,y]of e._billboards)C!==e._trackedIcao&&(y.show=!0);if((m.models3dMode==="proximity"||m.models3dMode==="all")&&m.models3dMode!==e._models3dMode&&(e._models3dMode=m.models3dMode,e._cockpitContactMode&&(n.tracking._refreshCockpitNearContacts(),e._lastFleetTickMs=0)),typeof m.irBoost=="boolean"&&m.irBoost!==e._irBoost&&(e._irBoost=m.irBoost,n.rendering._reloadModelsForIrBoost(),n.tracking._refreshTr3bForStyle()),Object.hasOwn(m,"selectedMilitaryTrackingId")){const C=p(m.selectedMilitaryTrackingId);if(C===e._trackedIcao)e._pendingTrackingRestore=null;else if(C===null)n.tracking._cancelPendingTrackingRestore(),e._trackedIcao&&n.tracking._clearTracking(!1,{origin:b});else{const y=++e._trackingIntentGeneration;e._pendingTrackingRestore={id:C,generation:y,origin:b},e._trackedIcao&&n.tracking._clearTracking(!1,{origin:b}),n.tracking._applyPendingTrackingRestore()}}return!0},getParams(){return{models3d:e._models3dEnabled,models3dMode:e._models3dMode,irBoost:e._irBoost,selectedMilitaryTrackingId:e._trackedIcao}},refreshTr3b(m){return n.tracking._refreshTr3bContact(m)},getNearby(m,b,C=50,{includeHidden:y=!1}={}){var E,k;if(!m||!e._billboardCollection||!e._billboardCollection.show)return[];const v=Number.isFinite(C)?Math.max(1,Math.floor(C)):50,M=Number.isFinite(b)&&b>0?b:Number.POSITIVE_INFINITY;Cesium.JulianDate.now();const w=[];for(const[T,I]of e._billboards){const R=T===e._trackedIcao;if(!Ty({isTracked:R,billboardShown:I.show,modelRendering:n.rendering._modelOwnsVisual(T),includeHidden:y}))continue;const A=(R?n.motion._trackedDisplayCached():null)||I.position;if(!A)continue;const L=Cesium.Cartesian3.distance(m,A);if(L>M)continue;const F=e.records.data.get(T);w.push({id:((E=F==null?void 0:F.callsign)==null?void 0:E.trim())||((k=F==null?void 0:F.registration)==null?void 0:k.trim())||T,icao24:T,position:A,distance:L,aircraftClass:r(T,String((F==null?void 0:F.klass)||(F==null?void 0:F.type)||"").trim().toLowerCase()||null),track:(F==null?void 0:F.track)??null,type:s(T,(F==null?void 0:F.type)||null),registration:(F==null?void 0:F.registration)||null,operator:(F==null?void 0:F.operator)||null,altitudeFt:(F==null?void 0:F.altitudeFt)??null})}return w.sort((T,I)=>T.distance-I.distance),w.slice(0,v)},getDetectableObjects(m={}){var E,k;if(!e._billboardCollection||!e._billboardCollection.show)return[];const b=Number.isFinite(m.maxCount)?Math.max(1,Math.floor(m.maxCount)):e._billboards.size,C=Number.isFinite(m.seed)?Math.floor(m.seed):0,y=Math.max(1,Math.ceil(e._billboards.size/b)),v=C%y,M=[];let w=0;for(const[T,I]of e._billboards){const R=(w-v)%y===0;if(w++,!R||e._cockpitContactMode&&T.toLowerCase()===e._cockpitSubjectId)continue;const S=T===e._trackedIcao,A=e._models.get(T),L=n.rendering._modelOwnsVisual(T);if(!S&&!I.show&&!L)continue;const F=e.records.data.get(T),P=(E=F==null?void 0:F.callsign)==null?void 0:E.trim(),O=(k=F==null?void 0:F.registration)==null?void 0:k.trim();let D=e._detectionObjects.get(T);D||(D={sourceId:T,type:"AIR",tier:"military",_weldPos:new Cesium.Cartesian3},e._detectionObjects.set(T,D));const $=L?n.rendering._modelSpec(F==null?void 0:F.klass):null,x=S?n.motion._trackedVisualCached()||I.position:L?jc(A.modelMatrix,$.visualCenterNative,Number.isFinite(A.computedScale)?A.computedScale:$.scale,D._weldPos||(D._weldPos=new Cesium.Cartesian3)):I.position;if(!x)continue;D.position=x,D.skipLabel=S;const N=P||O||T;D.id!==N&&(D.id=N);const G=s(T,(F==null?void 0:F.type)||"MIL");D.klass!==G&&(D.klass=G);const W=(F==null?void 0:F.altitudeFt)??0;if(D._altitudeFt!==W&&(D._altitudeFt=W,D.metric=a(W*.3048)),M.push(D),M.length>=b)break}if(e._detectionObjects.size>e._billboards.size+512)for(const T of e._detectionObjects.keys())e._billboards.has(T)||e._detectionObjects.delete(T);return M},findByQuery(m){if(!e.records.data||e.records.data.size===0)return null;const b=String(m||"").trim().toLowerCase();if(!b)return null;let C=null;for(const[y,v]of e.records.data){const M={tier:wy({query:b,hex:y,callsign:v==null?void 0:v.callsign,registration:v==null?void 0:v.registration}),id:y};if(Ey(M,C)&&(C=M,M.tier===Qt.HEX_EXACT))break}return C?f(C.id):null},hasContact(m){if(!e._billboardCollection||!e._billboardCollection.show||e._billboards.size===0)return null;if(!m)return!1;const b=String(m).trim();return e._billboards.has(b)||e._billboards.has(b.toLowerCase())},getAllPositions(m=500){if(!e._billboardCollection||e._billboards.size===0)return[];const b=Number.isFinite(m)?Math.max(1,Math.floor(m)):500,C=[];for(const[y,v]of e._billboards){const M=v.position;if(!M)continue;const w=Cesium.Cartographic.fromCartesian(M,Cesium.Ellipsoid.WGS84,e._scratchCarto);if(!w)continue;const E=e.records.data.get(y);if(C.push({id:y,label:u(E==null?void 0:E.callsign)||u(E==null?void 0:E.registration)||y,position:M,latitude:Cesium.Math.toDegrees(w.latitude),longitude:Cesium.Math.toDegrees(w.longitude),altitudeM:w.height}),C.length>=b)break}return C},getAnalystRecords(m=2e3){if(!e._billboardCollection||!e._billboardCollection.show||e.records.data.size===0)return[];const b=Number.isFinite(m)?Math.max(1,Math.floor(m)):2e3,C=[];for(const[y,v]of e.records.data)if(C.push(g(y,v)),C.length>=b)break;return C},trackById(m,{origin:b="programmatic"}={}){if(!m)return!1;let C=String(m).trim();return e._billboards.has(C)||(C=C.toLowerCase()),e._billboards.has(C)?(n.tracking._isExplicitTrackingOrigin(b)&&n.tracking._cancelPendingTrackingRestore(),e._trackedIcao===C?n.tracking._publishTrackedSelection(C,b):(n.tracking._trackFlight(C,{origin:b}),!0)):!1},async resolveTrackingRestoreTarget(m,{signal:b=null,origin:C="share-restore"}={}){if(b!=null&&b.aborted)return{status:"cancelled",reason:String(b.reason||"aborted")};const y=String(m??"").trim().toLowerCase();if(!y)return{status:"missing",reason:"invalid-target"};const v=e.feed._lastTrackingRefreshOutcome;return v.status!=="accepted"?{status:"source-unavailable",reason:`${e.feed._lastSource} snapshot unavailable`,refreshEpoch:v.epoch,source:v.source}:v.ids.has(y)?b!=null&&b.aborted?{status:"cancelled",reason:String(b.reason||"aborted")}:this.trackById(y,{origin:C})?{status:"found",refreshEpoch:v.epoch,source:v.source}:{status:"source-unavailable",reason:"target-not-renderable",refreshEpoch:v.epoch}:{status:"missing",reason:"target-absent-from-snapshot",refreshEpoch:v.epoch,source:v.source}},refocusTrackedById(m,{origin:b="programmatic"}={}){var y,v,M;if(!m||e._cockpitContactMode||!e._viewer||!e._trackedEntity)return!1;let C=String(m).trim();return e._billboards.has(C)||(C=C.toLowerCase()),C!==e._trackedIcao||!((v=(y=e._viewer.entities)==null?void 0:y.contains)!=null&&v.call(y,e._trackedEntity))||e._viewer.trackedEntity!==e._trackedEntity?!1:((M=e._trackedCameraFrameStop)==null||M.call(e),e._viewer.camera.cancelFlight(),e._viewer.trackedEntity=e._trackedEntity,e._trackedCameraFrameStop=c(e._viewer,e._trackedEntity,e._trackedEntity.viewFrom)||null,n.tracking._publishTrackedSelection(C,b),!0)},stopTracking({origin:m="programmatic"}={}){return n.tracking._cancelPendingTrackingRestore(),n.tracking._clearTracking(!1,{origin:m}),!0},cancelPendingTrackingRestore(){n.tracking._cancelPendingTrackingRestore()},getTrackedInfo(){if(!e._trackedIcao)return null;const m=f(e._trackedIcao);if(!m)return null;const{position:b,...C}=m;return C},getTrackedSubject(){if(!e._trackedIcao)return null;const m=f(e._trackedIcao);return m!=null&&m.position?{layerId:"military",id:m.icao24,label:m.callsign||m.registration||m.icao24,position:Cesium.Cartesian3.clone(m.position)}:null},getStats(){const m=e.feed._retryAt?Math.max(0,Math.ceil((e.feed._retryAt-Date.now())/1e3)):0;return{count:e.feed._count,lastUpdate:e.feed._lastUpdate,stale:e.feed._backoff,error:e.feed._lastError,status:e.feed._lastStatus,retryInSec:m,source:e.feed._lastSource,fallback:!1}}};return{_toFiniteNumber:l,_toCleanText:u,_formatAltitude:h,_likelyLanded:d,_describeFlight:f,_normalizeTrackedIcao:p,mapAnalystRecord:g,methods:_}}function TP({source:e,services:t,resolveAsset:n=i=>i}={}){const i=_P({source:e,services:t}),o={},r={},s={flightState:i,services:t,parts:o,layer:r,resolveAsset:n};o.rendering=bP(s),o.motion=CP(s),o.tracking=yP(s),o.controller=vP(s),o.lifecycle=MP(s),o.testing=wP(s),o.queries=EP(s);const a=fP({flightState:i,records:i.records,groundFloor:t.groundFloor,meshFloor:t.meshFloor,militaryRegistry:t.militaryRegistry,rendering:o.rendering,tracking:o.tracking,queries:o.queries});return o.ingestion=pP({feed:i.feed,applySnapshot:a,setSourceLabel:c=>{r.source=c},applyPendingTrackingRestore:()=>o.tracking._applyPendingTrackingRestore()}),Object.assign(r,o.queries.methods,o.lifecycle.methods,o.ingestion.methods),Object.defineProperty(r,"testing",{value:o.testing}),r}function kP({surface:e,source:t,militaryRegistry:n,resolveAsset:i=o=>`/${o.replace(/^\//,"")}`}){const{groundFloor:o,meshFloor:r,groundSnap:s}=e;return TP({source:t,resolveAsset:i,services:{picking:rn,sprites:Ki,trails:Df,aircraftPresentation:xy,camera:Dy,militaryRegistry:n,labels:Bf,groundFloor:o,meshFloor:r,geoid:wf,focus:ma,readout:rm,context:Go,render:Pt,groundSnap:s,recession:Zv}})}const AP=300*1e3,IP=3,Jl="awaiting first AIS position…";function RP({feed:e,readSource:t,readViewer:n,getRowLimit:i,readCount:o,applyRows:r,classifySnapshot:s,isDefinitiveTransportFailure:a,isGraceEligibleTransport:c,markUnavailable:l,settleFirstConnect:u,now:h,setSourceLabel:d}){async function f(b){if(!b||e.loading)return;e.loading=!0,e.loadingLabel=e.loaded?"refreshing...":"loading...";const C=new AbortController,y=e.sessionId;e.abort=C;try{const v=typeof AbortSignal.any=="function"?AbortSignal.any([C.signal,AbortSignal.timeout(1e4)]):C.signal,M=await t().getSnapshot({maxRows:i()},{signal:v});if(!p(C,y))return;d(M.source),g(b,{rows:M.records.map(_),observedAtMs:M.observedAtMs,freshness:M.freshness,complete:M.complete,rawRowCount:M.rawRowCount,reason:M.reason,status:M.transportStatus,lastMessageAt:M.lastMessageAt,nextAttemptAt:M.nextAttemptAt,refreshing:M.stale,newestPositionAt:M.observedAtMs==null?null:new Date(M.observedAtMs).toISOString(),silentForMs:M.silentForMs,reconnectAttempt:M.reconnectAttempt})}catch(v){p(C,y)&&(v==null?void 0:v.name)!=="AbortError"&&(l((v==null?void 0:v.message)||"AIS live load failed"),console.warn("[Data:ais-live-vessels]",e.error,v))}finally{e.abort===C&&e.sessionId===y&&(e.loading=!1,e.loadingLabel=e.firstConnectPhase==="loading"?Jl:"",e.abort=null)}}function p(b,C){return e.enabled&&e.sessionId===C&&e.abort===b&&!b.signal.aborted}function g(b,C){const y=s(C);return e.loaded=!0,e.loadingLabel="",e.transportStatus=y.transportStatus,e.nextAttemptAt=Number(C==null?void 0:C.nextAttemptAt)||null,e.lastMessageAt=y.lastMessageAt,e.rawRowCount=y.rawRowCount,e.acceptedRowCount=y.acceptedRowCount,y.acceptedRowCount===0?(e.count=o(),e.stale=e.count>0||!!(C!=null&&C.refreshing),a(y.transportStatus)?(l(y.error),{reconciled:!1,...y}):e.firstConnectPhase==="loading"&&c(y.transportStatus)?(e.error=null,e.loadingLabel=Jl,{reconciled:!1,...y}):e.firstConnectPhase==="loading"?(l(y.error),{reconciled:!1,...y}):(e.error=y.error,{reconciled:!1,...y})):(u("ready"),r(b,y.acceptedRows,{complete:(C==null?void 0:C.complete)!==!1}),e.count=o(),e.stale=!!(C!=null&&C.refreshing)||(C==null?void 0:C.complete)===!1||(C==null?void 0:C.freshness)==="unknown",e.newestPositionAt=(C==null?void 0:C.newestPositionAt)||null,e.error=y.error||(C==null?void 0:C.reason)||null,e.lastUpdate=Object.hasOwn(C,"observedAtMs")?C.observedAtMs:h(),{reconciled:!0,...y})}function _(b){return{mmsi:b.id,reference:b.reference,lat:b.latitude,lon:b.longitude,name:b.name,imo:b.imo,type:b.type,destination:b.destination,speed:b.speedMps==null?null:b.speedMps/.514444,course:b.courseDeg,heading:b.headingDeg,last_position_epoch:b.observedAtMs==null?null:b.observedAtMs/1e3,last_position_UTC:b.observedAtMs==null?"":new Date(b.observedAtMs).toISOString()}}return{loadLivePositions:f,ownsAisRequest:p,applyAisFeedSnapshot:g,vesselDisplayRow:_,methods:{update(b){return e.enabled?f(b||n()):Promise.resolve()}}}}function LP(){return{enabled:!1,loading:!1,loaded:!1,stale:!1,error:null,loadingLabel:"",lastUpdate:null,count:0,newestPositionAt:null,transportStatus:null,nextAttemptAt:null,lastMessageAt:null,rawRowCount:0,acceptedRowCount:0,sessionId:0,firstConnectPhase:"idle",firstConnectStartedAt:null,firstConnectDeadline:null,firstConnectTimer:null,abort:null}}function PP(e){const t=Number(e.lat),n=Number(e.lon);return!Number.isFinite(t)||!Number.isFinite(n)?null:{lat:t,lon:n,name:String(e.name||e.mmsi||"VESSEL"),mmsi:String(e.mmsi||"").trim(),reference:e.reference??String(e.mmsi||"").trim(),imo:String(e.imo||""),type:String(e.type||""),destination:String(e.destination||""),speed:Sa(e.speed),course:Sa(e.course),heading:Sa(e.heading),lastPositionUtc:String(e.last_position_UTC||""),lastPositionEpoch:Sa(e.last_position_epoch),missedRefreshes:0}}function Sa(e){if(e==null||e==="")return null;const t=Number(e);return Number.isFinite(t)?t:null}class xP{constructor({now:t=()=>Date.now()}={}){this.now=t,this.byMmsi=new Map,this.unkeyed=[],this.all=[]}reconcile(t,{complete:n=!0,selectedRecord:i=null,cap:o=1/0},r){const s=this.now();for(const c of this.unkeyed)r.remove(c,!1);this.unkeyed=[];const a=new Set;for(const c of t){const l=PP(c);if(!l)continue;if(l.receivedAtMs=s,!l.mmsi){r.add(l),this.unkeyed.push(l);continue}if(a.has(l.mmsi))continue;a.add(l.mmsi);const u=this.byMmsi.get(l.mmsi);if(u){const h=r.beforeUpdate(u);u.reference=l.reference,u.receivedAtMs=l.receivedAtMs,u.lat=l.lat,u.lon=l.lon,u.name=l.name,u.imo=l.imo,u.type=l.type,u.destination=l.destination,u.speed=l.speed,u.course=l.course,u.heading=l.heading,u.lastPositionUtc=l.lastPositionUtc,u.lastPositionEpoch=l.lastPositionEpoch,u.missedRefreshes=0,r.updated(u,h)}else r.add(l),this.byMmsi.set(l.mmsi,l)}for(const[c,l]of this.byMmsi)if(!a.has(c)){if(!n&&Number.isFinite(l.receivedAtMs)&&s-l.receivedAtMso)for(const[c,l]of this.byMmsi){if(this.byMmsi.size+this.unkeyed.length<=o)break;a.has(c)||l===i||(r.remove(l,!1),this.byMmsi.delete(c),r.removed(c))}this.all=[...this.byMmsi.values(),...this.unkeyed]}}const co="ais-live-vessels",uh=118,iM=900,FP=iM,oM=5e6,SP=[{pattern:/tanker/i,css:"#ffb347",accent:"255, 179, 71"},{pattern:/cargo|container|bulk|carrier/i,css:"#39d5ff",accent:"57, 213, 255"},{pattern:/passenger|ferry|cruise/i,css:"#ff7adf",accent:"255, 122, 223"},{pattern:/fishing/i,css:"#7cff9b",accent:"124, 255, 155"},{pattern:/tug|tow|pilot|supply|service/i,css:"#f7f0a3",accent:"247, 240, 163"}],NP={css:"#39d5ff",accent:"57, 213, 255"},bg={30:"FISHING",31:"TOWING",32:"TOWING",33:"DREDGER",34:"DIVE OPS",35:"MILITARY",36:"SAILING",37:"PLEASURE",50:"PILOT",51:"SAR",52:"TUG",53:"PORT TENDER",54:"ANTI-POLLUTION",55:"LAW ENFORCE",58:"MEDICAL"},DP={4:"HIGH-SPEED",6:"PASSENGER",7:"CARGO",8:"TANKER",9:"OTHER"};function rM(e){const t=String(e||"").trim();if(!t||!/^\d{1,2}$/.test(t))return t;const n=Number(t);return n<=0?"":bg[n]?bg[n]:DP[Math.floor(n/10)]||"OTHER"}function OP(e){return sM(e).css}function Cg(e){return sM(e).accent}function sM(e){const t=rM(e);return SP.find(n=>n.pattern.test(t))||NP}function BP(e,t,n=iM){const i=Number(e),o=Number(t),r=Number(n);if(!(i>0)||!(o>0)||!(r>0))return 0;const s=Math.ceil(i/uh)*Math.ceil(o/uh);return Math.min(FP,Math.floor(r),s)}function VP(e,t=oM){const n=(e==null?void 0:e.selected)===!0,i=Number(e==null?void 0:e.gapPx)||10,o=Math.max(12,i+8);return{...e,variant:n?"selected":"card",protected:n,collisionGroup:"ambient-card",cardStyle:"tactical",gapPx:o,leaderOffsetPx:Math.max(2,o-6),verticalOnly:!0,viewportMargin:4,maxDistance:n?Number.POSITIVE_INFINITY:t,distanceFadeStartRatio:.7,edgeFade:"keyhole",horizonCull:!0,terrainOcclusion:!1,interactive:(e==null?void 0:e.actionable)===!0}}const HP=12e3,$P=900,GP=6e4,yg=3e4,UP=800,zP=80,vg=uh,jP=150,qP="#39ffd5",Mg=3,aM=3,Bu=400,WP=25,lM=Object.freeze({now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)}),wg={"missing-key":"AISSTREAM_API_KEY not set",unsupported:"live feed unsupported",connecting:"connecting to feed…",closed:"feed disconnected",error:"feed down",idle:"feed idle"},cM=new Set(["live","open"]),KP=new Set(["stale","reconnecting","down","auth-failed"]);function YP({source:e,services:t}){const{setOverlayEntries:n,setOverlaySourceVisible:i,clearOverlaySource:o,hitTestWorldOverlay:r}=t.overlay,s={};return s._source=e,s._lastCamPoseSig="",s._scratchFocusScreen=new Cesium.Cartesian2,s.DEFAULT_VESSEL_OVERLAY_HOST=Object.freeze({setEntries:n,setVisible:i,clearSource:o,hitTest:r}),s._vesselOverlayHost=s.DEFAULT_VESSEL_OVERLAY_HOST,s._aisRuntime=lM,s._aisSessionSequence=0,s._geoidReady=!1,s.shipIconCache=new Map,s.state={feed:LP(),records:new xP({now:()=>s._aisRuntime.now()}),viewer:null,billboardCollection:null,clickHandler:null,keyTarget:null,keydownHandler:null,trackedEntityRemover:null,interactionHandlerFactory:null,interactionKeyTarget:null,preRenderRemover:null,lastVisibilityUpdate:0,lastFocusUpdate:0,activeFocusCount:0,activeLabelCount:0,selectedRecord:null,trail:null,trailPositions:[],trailMmsi:null,trailBackfillToken:0,trailAbort:null},s}function XP({vesselState:e,services:t,parts:n,layer:i,options:o}){const{state:r}=e,{restoreSpriteOrder:s,restoreSpriteOrderOnEnable:a}=t.sprites,{holdContinuousRender:c,releaseContinuousRender:l}=t.render,{ensureGeoidReady:u}=t.geoid,{registerPickOwner:h,unregisterPickOwner:d}=t.picking;function f(){r.feed.firstConnectTimer!==null&&(e._aisRuntime.clearTimeout(r.feed.firstConnectTimer),r.feed.firstConnectTimer=null)}function p(){f(),r.feed.sessionId=++e._aisSessionSequence,r.feed.firstConnectPhase="idle",r.feed.firstConnectStartedAt=null,r.feed.firstConnectDeadline=null}function g(){f();const w=++e._aisSessionSequence,E=e._aisRuntime.now();r.feed.sessionId=w,r.feed.firstConnectPhase="loading",r.feed.firstConnectStartedAt=E,r.feed.firstConnectDeadline=E+yg,r.feed.error=null,r.feed.loadingLabel=Jl,_(w,yg)}function _(w,E){r.feed.firstConnectTimer=e._aisRuntime.setTimeout(()=>{if(!r.feed.enabled||r.feed.sessionId!==w||r.feed.firstConnectPhase!=="loading")return;const k=r.feed.firstConnectDeadline-e._aisRuntime.now();if(k>0){_(w,k);return}r.feed.firstConnectTimer=null,r.feed.firstConnectPhase="unavailable",r.feed.loadingLabel="",r.feed.error=r.feed.lastMessageAt?"awaiting usable AIS positions…":"awaiting first AIS message…",r.feed.stale=r.feed.count>0},E)}function m(w){f(),r.feed.firstConnectPhase=w,r.feed.loadingLabel=""}function b(w){return cM.has(w)||w==="connecting"}function C(w){return!!w&&!b(w)}function y(w){m("unavailable"),r.feed.error=w||"AIS live load failed",r.feed.stale=r.feed.count>0}function v(){var w,E;n.rendering.resetRecordVisuals(),(w=r.feed.abort)==null||w.abort(),(E=r.trailAbort)==null||E.abort(),r.trailAbort=null,f(),r.viewer=null,r.feed.enabled=!1,r.feed.loading=!1,r.feed.loaded=!1,r.feed.stale=!1,r.feed.error=null,r.feed.loadingLabel="",r.feed.lastUpdate=null,r.feed.count=0,r.feed.newestPositionAt=null,r.feed.transportStatus=null,r.feed.nextAttemptAt=null,r.feed.lastMessageAt=null,r.feed.rawRowCount=0,r.feed.acceptedRowCount=0,r.feed.sessionId=++e._aisSessionSequence,r.feed.firstConnectPhase="idle",r.feed.firstConnectStartedAt=null,r.feed.firstConnectDeadline=null,r.feed.firstConnectTimer=null,r.feed.abort=null,r.billboardCollection=null,r.records.all=[],r.records.byMmsi=new Map,r.records.unkeyed=[],r.clickHandler=null,r.keyTarget=null,r.keydownHandler=null,r.trackedEntityRemover=null,r.interactionHandlerFactory=null,r.interactionKeyTarget=null,r.preRenderRemover=null,r.lastVisibilityUpdate=0,r.lastFocusUpdate=0,r.activeFocusCount=0,r.activeLabelCount=0,r.selectedRecord=null,r.trail=null,r.trailPositions=[],r.trailMmsi=null,r.trailBackfillToken=0}return{clearFirstConnectTimer:f,invalidateAisSession:p,beginAisSession:g,scheduleFirstConnectExpiry:_,settleFirstConnectPhase:m,isGraceEligibleTransport:b,isDefinitiveTransportFailure:C,markAisUnavailable:y,resetState:v,methods:{setSource(w){if(r.viewer)throw new Error("Configure the source before layer initialization");if(typeof(w==null?void 0:w.getSnapshot)!="function")throw new TypeError("A snapshot source is required");e._source=w,this.source=w.label||this.source},init(w){var E;if(typeof((E=e._source)==null?void 0:E.getSnapshot)!="function")throw new TypeError("A snapshot source is required");r.viewer=w,n.rendering.ensureCollections(w),e._vesselOverlayHost.setVisible(co,!1),n.selection.installInteraction(w),n.rendering.installRuntime(w),s(w)},enable(w){const E=r.feed.enabled;r.feed.enabled=!0,E||g(),c("ais-vessels");const k=w||r.viewer;if(n.rendering.ensureCollections(k),n.selection.installInteraction(k),n.rendering.setVisible(!0),!e._geoidReady){const T=r.feed.sessionId;u().then(()=>{!r.feed.enabled||r.feed.sessionId!==T||(e._geoidReady=!0,n.tracking.refloorVesselRecords())}).catch(()=>{})}return h("ais-live-vessels",T=>r.records.byMmsi.has(T)),a("ais",k),n.ingestion.loadLivePositions(k)},disable(){r.feed.enabled=!1,p(),l("ais-vessels"),d("ais-live-vessels"),n.rendering.setVisible(!1),e._vesselOverlayHost.clearSource(co),n.selection.clearVesselInspection(),n.tracking.destroySelectedVesselTrail(),n.selection.removeVesselInteraction(),r.feed.abort&&(r.feed.abort.abort(),r.feed.abort=null),r.feed.loading=!1,r.feed.loadingLabel=""},destroy(w){var k;const E=w||r.viewer;p(),l("ais-vessels"),r.feed.abort&&r.feed.abort.abort(),d("ais-live-vessels"),n.selection.clearVesselInspection(),n.tracking.destroySelectedVesselTrail(),r.billboardCollection&&((k=E==null?void 0:E.scene)!=null&&k.primitives)&&E.scene.primitives.remove(r.billboardCollection),e._vesselOverlayHost.clearSource(co),e._vesselOverlayHost.setVisible(co,!1),n.selection.removeVesselInteraction(),r.preRenderRemover&&r.preRenderRemover(),v()}}}}function QP({state:e,records:t,rendering:n,tracking:i,selection:o,cards:r}){function s(a,c,{complete:l=!0}={}){n.ensureCollections(a);const u=n.makeOccluder();t.reconcile(c,{complete:l,selectedRecord:e.selectedRecord,cap:n.renderRowLimit()},{add(h){n.prepareRecordVisual(h),n.addRecordPrimitives(h,u)},beforeUpdate(h){return n.shipIcon(h,h===e.selectedRecord)},updated(h,d){const f=h===e.selectedRecord,p=n.prepareRecordVisual(h);if(p.billboard){p.billboard.position=p.position,p.billboard.scale=n.shipScale(h)*(f?1.2:1);const g=n.shipIcon(h,f);g!==d&&(p.billboard.image=g)}h.mmsi===e.trailMmsi&&i.appendSelectedVesselTrailFix(h),f&&(r.updateSelectedVesselHud(h),o.registerSelectedContext(h))},remove(h,d){d&&o.clearVesselInspection({evicted:!0}),n.removeRecordPrimitives(h)},removed(h){e.trailMmsi===h&&i.clearSelectedVesselTrail()},staleSelected(h){r.updateSelectedVesselHud(h)}}),e.lastVisibilityUpdate=0,n.updateVisibility(!0)}return{reconcileVessels:s}}function ZP({vesselState:e,services:t,parts:n,layer:i,options:o}){const{state:r}=e;let s=new WeakMap;function a(D){return s.get(D)||D}function c(D){let $=s.get(D);$||($={billboard:D.billboard||null},s.set(D,$));const x=n.queries.vesselDatumHeightM(n.tracking.currentGeoidN(D.lat,D.lon),aM);return $.position=Cesium.Cartesian3.fromDegrees(D.lon,D.lat,x),$.surfacePosition=Cesium.Cartesian3.fromDegrees(D.lon,D.lat,0),$.normal=Cesium.Ellipsoid.WGS84.geodeticSurfaceNormal($.position,new Cesium.Cartesian3),$}function l(){s=new WeakMap}const{registerSpriteCollection:u}=t.sprites,{forgetSpriteFocus:h,focusNowMs:d,getFocusTarget:f,focusPassIsNeeded:p,advanceSpriteFocus:g,focusAlphaNeedsWrite:_}=t.focus;function m(){const D=Number(o.maxRows);return Number.isFinite(D)&&D>0?Math.max(500,Math.min(5e4,Math.round(D))):HP}function b(){const D=Number(o.maxLabels);return Number.isFinite(D)&&D>=0?Math.max(0,Math.min(m(),Math.round(D))):Math.min($P,m())}function C(D){!D||r.billboardCollection||(r.billboardCollection=new Cesium.BillboardCollection({blendOption:Cesium.BlendOption.TRANSLUCENT}),r.billboardCollection.show=r.feed.enabled,D.scene.primitives.add(r.billboardCollection),u("ais",r.billboardCollection))}function y(D,$){const x=r.feed.enabled&&S(a(D).surfacePosition,$);a(D).billboard=r.billboardCollection.add({position:a(D).position,show:x,image:E(D,!1),scale:M(D),rotation:0,alignedAxis:Cesium.Cartesian3.ZERO,horizontalOrigin:Cesium.HorizontalOrigin.CENTER,verticalOrigin:Cesium.VerticalOrigin.CENTER,disableDepthTestDistance:Number.POSITIVE_INFINITY,id:D})}function v(D){D&&(a(D).billboard&&r.billboardCollection&&(h(a(D).billboard),r.billboardCollection.remove(a(D).billboard)),a(D).billboard=null)}function M(D){const $=Number(D.speed||0);return $>=18?.78:$>=8?.68:.6}function w(D){const $=D.heading??D.course;return Number.isFinite($)?$:0}function E(D,$){const x=$?"#ffffff":OP(D.type),N=`${x}:${$?"selected":"normal"}`;if(e.shipIconCache.has(N))return e.shipIconCache.get(N);const V=` + + + + `,H="data:image/svg+xml;base64,"+btoa(V);return e.shipIconCache.set(N,H),H}function k(D){r.preRenderRemover||!D||(r.preRenderRemover=D.scene.preRender.addEventListener(()=>T()))}function T(D=!1){var H,B;if(!r.feed.enabled)return;const $=d(performance.now()),x=f(),N=D||$-r.lastVisibilityUpdate>=UP,G=p(x,r.activeFocusCount)&&(D||$-r.lastFocusUpdate>=zP);if(!N&&!G)return;if(N&&(r.lastVisibilityUpdate=$),G&&(r.lastFocusUpdate=$),!r.records.all.length){N&&A([]),G&&(r.activeFocusCount=0);return}const W=(H=r.viewer)==null?void 0:H.scene,V=(B=r.viewer)==null?void 0:B.camera;if(N){const q=V?qc(V):"",z=D||q!==e._lastCamPoseSig;z&&(e._lastCamPoseSig=q);const j=R(),ne=[];for(const ee of r.records.all){const re=a(ee),se=S(re.surfacePosition,j);if(re.billboard&&(re.billboard.show=se,se&&z&&W)){const me=ri(W,re.position,w(ee),re.billboard.rotation);me!==null&&Math.abs(me-re.billboard.rotation)>.002&&(re.billboard.rotation=me)}se&&ne.push(ee)}A(ne)}if(G&&W&&V){const q=I({records:r.records.all,target:x,previousActiveCount:r.activeFocusCount,nowMs:$,screenPositionFor:z=>Cesium.SceneTransforms.worldToWindowCoordinates(W,z,e._scratchFocusScreen),cameraDistanceFor:z=>Cesium.Cartesian3.distance(V.positionWC,z)});r.activeFocusCount=q.activeCount}}function I({records:D,target:$,previousActiveCount:x=0,nowMs:N,screenPositionFor:G,cameraDistanceFor:W,params:V}){var z;if(!p($,x))return{writes:0,transitioning:!1,activeCount:0,ran:!1};let H=0,B=!1,q=0;for(const j of D||[]){const ne=a(j),ee=ne==null?void 0:ne.billboard,re=(ee==null?void 0:ee.position)||(ne==null?void 0:ne.position);if(!ee||!re)continue;const se=g(ee,{screenPosition:ee.show===!1?null:G(re),cameraDistance:W(re),nowMs:N,target:$,params:V,spriteHalfWidthPx:(ee.width||32)*(ee.scale||1)*.5,spriteHalfHeightPx:(ee.height||32)*(ee.scale||1)*.5});if(B||(B=se.transitioning),se.active&&(q+=1),_((z=ee.color)==null?void 0:z.alpha,se.factor,V)){const me=ee.color||Cesium.Color.WHITE;ee.color=me.withAlpha(se.factor),H+=1}}return{writes:H,transitioning:B,activeCount:q,ran:!0}}function R(){var $,x;const D=(x=($=r.viewer)==null?void 0:$.camera)==null?void 0:x.positionWC;return D?new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84,D):null}function S(D,$){return!D||!$?!0:$.isPointVisible(D)}function A(D){var q;const $=r.viewer,x=$==null?void 0:$.scene,N=r.selectedRecord,G=N?[n.cards.buildSelectedVesselCard(N)]:[],W=b();if(!x||!D.length||W<=0){r.activeLabelCount=G.length,L(G);return}const V=new Map;for(const z of D){const j=a(z);if(z===N)continue;const ne=Cesium.SceneTransforms.worldToWindowCoordinates(x,j.position);if(!ne)continue;const ee=`${Math.floor(ne.x/vg)}:${Math.floor(ne.y/vg)}`,re={record:z,score:F(z,N),x:ne.x,y:ne.y},se=V.get(ee);(!se||re.score>se.score)&&V.set(ee,re)}const H=[];if(N){const z=Cesium.SceneTransforms.worldToWindowCoordinates(x,((q=a(N).billboard)==null?void 0:q.position)||a(N).position);z&&H.push({x:z.x,y:z.y})}const B=[...V.values()].sort((z,j)=>j.score-z.score);for(const z of B){if(G.length>=W)break;n.cards.cardScreenSeparated(H,z,jP)&&(H.push({x:z.x,y:z.y}),G.push(n.cards.buildVesselCard(z.record)))}r.activeLabelCount=G.length,L(G)}function L(D){var W,V,H;const $=((V=(W=r.viewer)==null?void 0:W.scene)==null?void 0:V.canvas)||((H=r.viewer)==null?void 0:H.canvas),x=Number($==null?void 0:$.clientWidth)||0,N=Number($==null?void 0:$.clientHeight)||0,G=BP(x,N,b());e._vesselOverlayHost.setEntries(co,D.map(B=>{const q=VP(B,oM);if(!q.interactive)return q;const z=String(q.id||"").startsWith("vessel:")?q.id.slice(7):"";return{...q,accessibilityLabel:`Focus vessel ${q.title}, MMSI ${z}`,activate:()=>{const j=r.records.byMmsi.get(z);return j?(n.selection.selectAndFocusVessel(j),!0):!1}}}),{cohortLimit:Math.max(1,G),collisionCapacity:G,moving:!1})}function F(D,$){if(D===$)return 1e5;let x=0;return P(D)&&(x+=1e3),D.speed!==null&&(x+=Math.min(400,Math.max(0,D.speed)*20)),(D.heading!==null||D.course!==null)&&(x+=80),D.type&&(x+=40),x}function P(D){const $=String(D.name||"").trim();return!!($&&$!=="VESSEL"&&!/^MMSI\s*\d+$/i.test($)&&$!==D.mmsi)}function O(D){r.billboardCollection&&(r.billboardCollection.show=D),e._vesselOverlayHost.setVisible(co,D)}return{getVisual:a,prepareRecordVisual:c,resetRecordVisuals:l,renderRowLimit:m,labelRowLimit:b,ensureCollections:C,addRecordPrimitives:y,removeRecordPrimitives:v,shipScale:M,vesselCourseDeg:w,shipIcon:E,installRuntime:k,updateVisibility:T,applyVesselFocusDeemphasis:I,makeOccluder:R,isVisible:S,updateClusteredLabels:A,publishVesselOverlayEntries:L,labelPriority:F,hasUsefulName:P,setVisible:O}}function JP({vesselState:e,services:t,parts:n,layer:i,options:o}){const{state:r}=e,{resolvePickId:s,isOwnedByOtherLayer:a}=t.picking,{requestWorldFocus:c}=t.worldFocus,{selectEntityContext:l,registerEntityContext:u,clearSelectedEntityContextForLayer:h}=t.context,d=i;function f(M){if(r.clickHandler||!M)return;const w=r.interactionHandlerFactory?r.interactionHandlerFactory(M):new Cesium.ScreenSpaceEventHandler(M.scene.canvas);p(M,w,r.interactionKeyTarget||document)}function p(M,w,E){r.clickHandler=w,w.setInputAction(k=>{var F,P,O,D,$,x;if(!Bt()||!r.feed.enabled)return;const T=M.scene.pick(k.position),I=s(T);let R=I?r.records.byMmsi.get(I):null;const S=(T==null?void 0:T.id)??((F=T==null?void 0:T.primitive)==null?void 0:F.id);if(S&&typeof S=="object"&&Object.hasOwn(S,"mmsi")&&(!I||!R)||I&&!R&&String(I).startsWith("gev-trail:")||I&&a("ais-live-vessels",I))return;const L=R?null:($=(D=e._vesselOverlayHost).hitTest)==null?void 0:$.call(D,(P=k.position)==null?void 0:P.x,(O=k.position)==null?void 0:O.y,{sourceId:co});if(!R&&L){const N=String(L.entryId||"").startsWith("vessel:")?L.entryId.slice(7):null;if(R=N&&r.records.byMmsi.get(N)||null,!R)return}R?g(R):n.queries.reduceVesselSelection({selectedMmsi:(x=r.selectedRecord)==null?void 0:x.mmsi,pickedMmsi:null,gesture:"click"}).action==="deselect"&&v()},Cesium.ScreenSpaceEventType.LEFT_CLICK),r.keyTarget=E,r.keydownHandler=m,E.addEventListener("keydown",r.keydownHandler),r.trackedEntityRemover=M.trackedEntityChanged.addEventListener(()=>{M.trackedEntity&&r.selectedRecord&&v()})}function g(M){var E,k;return M!=null&&M.mmsi?(n.queries.reduceVesselSelection({selectedMmsi:(E=r.selectedRecord)==null?void 0:E.mmsi,pickedMmsi:M.mmsi,gesture:"click"}).action==="select"&&b(M),c({kind:"vessel",id:M.mmsi,label:M.name||M.mmsi,position:((k=n.rendering.getVisual(M).billboard)==null?void 0:k.position)||n.rendering.getVisual(M).position}),!0):!1}function _(){r.clickHandler&&(r.clickHandler.destroy(),r.clickHandler=null),r.keyTarget&&r.keydownHandler&&r.keyTarget.removeEventListener("keydown",r.keydownHandler),r.keyTarget=null,r.keydownHandler=null,r.trackedEntityRemover&&(r.trackedEntityRemover(),r.trackedEntityRemover=null)}function m(M){var E;if(!r.feed.enabled||M.key!=="Escape")return;n.queries.reduceVesselSelection({selectedMmsi:(E=r.selectedRecord)==null?void 0:E.mmsi,gesture:"escape"}).action==="deselect"&&v()}function b(M){if(!(M!=null&&M.mmsi))return;const w=r.trailMmsi===M.mmsi;y({preserveTrail:w}),r.selectedRecord=M,M.missedRefreshes=0,n.rendering.getVisual(M).billboard&&(n.rendering.getVisual(M).billboard.image=n.rendering.shipIcon(M,!0),n.rendering.getVisual(M).billboard.scale=n.rendering.shipScale(M)*1.2),n.rendering.updateVisibility(!0),n.cards.updateSelectedVesselHud(M),C(M)&&l(M),w?n.tracking.appendSelectedVesselTrailFix(M):n.tracking.startSelectedVesselTrail(M)}function C(M){if(!(M!=null&&M.mmsi))return null;try{return u(M,{id:`ais-${M.mmsi}`,layerId:"ais-live-vessels",layerName:"Live AIS Vessels",source:d.source,label:n.cards.displayVesselName(M),latitude:M.lat,longitude:M.lon,properties:{mmsi:M.mmsi,type:M.type,speedKt:M.speed,course:M.course,destination:M.destination}})}catch(w){return console.warn("[Data:ais-live-vessels] context register failed",w),null}}function y({preserveTrail:M=!1,evicted:w=!1}={}){var k;const E=r.selectedRecord;(k=n.rendering.getVisual(E))!=null&&k.billboard&&(n.rendering.getVisual(E).billboard.image=n.rendering.shipIcon(E,!1),n.rendering.getVisual(E).billboard.scale=n.rendering.shipScale(E)),r.selectedRecord=null,E&&r.feed.enabled&&n.rendering.updateVisibility(!0),M||n.tracking.clearSelectedVesselTrail();try{h("ais-live-vessels",{evicted:w})}catch(T){console.warn("[Data:ais-live-vessels] context clear failed",T)}}function v({evicted:M=!1}={}){y({evicted:M}),n.cards.resetSelectedVesselHud()}return{installInteraction:f,bindVesselInteraction:p,selectAndFocusVessel:g,removeVesselInteraction:_,onVesselKeyDown:m,selectVessel:b,registerSelectedContext:C,clearSelection:y,clearVesselInspection:v}}function ex({vesselState:e,services:t,parts:n,layer:i,options:o}){const{state:r}=e,{geoidHeight:s}=t.geoid,{createTrail:a}=t.trails;function c(_,m){return e._geoidReady?s(_,m):null}function l(_){if(!Number.isFinite(_==null?void 0:_.lat)||!Number.isFinite(_==null?void 0:_.lon))return null;const m=n.queries.vesselDatumHeightM(c(_.lat,_.lon),Mg);return Cesium.Cartesian3.fromDegrees(_.lon,_.lat,m)}function u(){if(r.records.all.length)for(const _ of r.records.all){const m=n.rendering.getVisual(_);if(!Number.isFinite(_.lat)||!Number.isFinite(_.lon))continue;const b=n.queries.vesselDatumHeightM(c(_.lat,_.lon),aM);m.position=Cesium.Cartesian3.fromDegrees(_.lon,_.lat,b),m.billboard&&(m.billboard.position=m.position)}}function h(_){var b;(b=r.trailAbort)==null||b.abort(),r.trailAbort=new AbortController,r.trailBackfillToken+=1,r.trailMmsi=_.mmsi,r.trailPositions=[];const m=l(_);m&&r.trailPositions.push(m),!r.trail&&r.viewer&&(r.trail=a(r.viewer,{color:qP,width:2.5})),r.trail&&r.trail.setPositions(r.trailPositions),d(_.mmsi,r.trailBackfillToken,_.reference)}async function d(_,m,b=_){var w,E;const C=r.trailAbort,y=C?AbortSignal.any([C.signal,AbortSignal.timeout(8e3)]):AbortSignal.timeout(8e3);let v=null;try{const k=await((E=(w=e._source).getTrack)==null?void 0:E.call(w,b,{signal:y}));v=(k==null?void 0:k.records)??null}catch{return}if(y.aborted||C!==r.trailAbort||!v||m!==r.trailBackfillToken||r.trailMmsi!==_)return;const M=[];for(const k of v){const T=Number(k==null?void 0:k.latitude),I=Number(k==null?void 0:k.longitude);if(!Number.isFinite(T)||!Number.isFinite(I))continue;const R=n.queries.vesselDatumHeightM(c(T,I),Mg);M.push(Cesium.Cartesian3.fromDegrees(I,T,R))}M.length&&(r.trailPositions=M.concat(r.trailPositions),r.trailPositions.length>Bu&&(r.trailPositions=r.trailPositions.slice(r.trailPositions.length-Bu)),r.trail&&r.trail.setPositions(r.trailPositions))}function f(_){if(!r.trail)return;const m=l(_);if(!m)return;const b=r.trailPositions[r.trailPositions.length-1];b&&Cesium.Cartesian3.distance(b,m)<=WP||(r.trailPositions.push(m),r.trailPositions.length>Bu&&r.trailPositions.shift(),r.trail.setPositions(r.trailPositions))}function p(){var _;(_=r.trailAbort)==null||_.abort(),r.trailAbort=null,r.trailBackfillToken+=1,r.trailMmsi=null,r.trailPositions=[],r.trail&&r.trail.clear()}function g(){p(),r.trail&&(r.trail.destroy(),r.trail=null)}return{currentGeoidN:c,vesselTrailPosition:l,refloorVesselRecords:u,startSelectedVesselTrail:h,backfillVesselTrail:d,appendSelectedVesselTrailFix:f,clearSelectedVesselTrail:p,destroySelectedVesselTrail:g}}function tx({vesselState:e,services:t,parts:n,layer:i,options:o}){const{state:r}=e;function s(b){const C=document.getElementById("hud-ais-vessel");if(!C)return;const y=(b.missedRefreshes||0)>0;C.classList.add("active"),C.textContent=[`AIS: ${c(b.name,32)}`,`${c(b.type||"VESSEL",24)} SPD: ${g(b.speed)} HDG: ${_(b.heading??b.course)}`,`MMSI: ${b.mmsi||"--"} ${m(b)}${y?" · STALE":""}`].join(` +`)}function a(){const b=document.getElementById("hud-ais-vessel");b&&(b.classList.remove("active"),b.textContent="AIS: --")}function c(b,C){const y=String(b||"--").trim()||"--";return y.length>C?`${y.slice(0,C-3)}...`:y}function l(b){var M;const C=[],y=d(b);y&&C.push(y),b.speed!==null&&b.speed!==void 0&&C.push(g(b.speed));const v=b.heading??b.course;return Number.isFinite(v)&&C.push(`${Math.round(v)}°`),{id:h(b),actionable:!!(b!=null&&b.mmsi),position:((M=n.rendering.getVisual(b).billboard)==null?void 0:M.position)||n.rendering.getVisual(b).position,gapPx:10,accent:Cg(b.type),title:c(p(b),26),details:C.length?[C.join(" · ")]:[],selected:!1,priority:n.rendering.labelPriority(b,null)}}function u(b){var w;const C=b.heading??b.course,y=[[d(b)||"VESSEL",g(b.speed),Number.isFinite(C)?`${Math.round(C)}°`:"--°"].join(" · ")],v=String(b.destination||"").trim();v&&y.push(`→ ${c(v,24)}`);const M=(b.missedRefreshes||0)>0;return y.push(`MMSI ${b.mmsi||"--"} · ${m(b)}${M?" · STALE":""}`),{id:h(b),actionable:!!(b!=null&&b.mmsi),position:((w=n.rendering.getVisual(b).billboard)==null?void 0:w.position)||n.rendering.getVisual(b).position,gapPx:12,accent:Cg(b.type),title:c(p(b),32),details:y,selected:!0,priority:1e5}}function h(b){const C=String((b==null?void 0:b.mmsi)||"").trim();if(C)return`vessel:${C}`;const y=String((b==null?void 0:b.name)||"VESSEL").trim()||"VESSEL",v=Number.isFinite(b==null?void 0:b.lat)?b.lat.toFixed(5):"x",M=Number.isFinite(b==null?void 0:b.lon)?b.lon.toFixed(5):"x";return`vessel:unkeyed:${y}:${v}:${M}`}function d(b){return rM(b.type).toUpperCase().slice(0,14)}function f(b,C,y){const v=y*y;for(let M=0;My==null?void 0:y.mmsi).map(y=>[y.mmsi,y])),r.selectedRecord=b.selectedRecord||null,r.billboardCollection=b.billboardCollection||{remove(){}},r.trail=b.trail||null,r.trailMmsi=b.trailMmsi||null,r.trailPositions=Array.isArray(b.trailPositions)?[...b.trailPositions]:[],r.feed.transportStatus=b.transportStatus||null,r.feed.lastMessageAt=b.lastMessageAt??null,r.feed.rawRowCount=Number.isFinite(b.rawRowCount)?b.rawRowCount:0,r.feed.acceptedRowCount=Number.isFinite(b.acceptedRowCount)?b.acceptedRowCount:C.length,r.feed.firstConnectPhase=b.firstConnectPhase||"idle",r.feed.firstConnectStartedAt=b.firstConnectStartedAt??null,r.feed.firstConnectDeadline=b.firstConnectDeadline??null,r.interactionHandlerFactory=b.interactionHandlerFactory||null,r.interactionKeyTarget=b.interactionKeyTarget||null}function l(b=null){e._vesselOverlayHost=b||e.DEFAULT_VESSEL_OVERLAY_HOST}function u(b=[]){n.rendering.updateClusteredLabels(b)}function h(b,C){n.snapshots.reconcileVessels(b,C)}function d(b,C){return n.ingestion.applyAisFeedSnapshot(b,C)}function f(b){return n.ingestion.loadLivePositions(b)}function p(){n.lifecycle.beginAisSession()}function g(b=null){n.lifecycle.clearFirstConnectTimer(),e._aisRuntime=b?{now:b.now,setTimeout:b.setTimeout,clearTimeout:b.clearTimeout}:lM}function _(){var C;const b=s.getStats();return{count:r.feed.count,loaded:r.feed.loaded,loading:b.loading,loadingLabel:b.loadingLabel,stale:r.feed.stale,error:r.feed.error,status:b.status,lastUpdate:r.feed.lastUpdate,transportStatus:r.feed.transportStatus,lastMessageAt:r.feed.lastMessageAt,rawRowCount:r.feed.rawRowCount,acceptedRowCount:r.feed.acceptedRowCount,selectedMmsi:((C=r.selectedRecord)==null?void 0:C.mmsi)||null,trailMmsi:r.trailMmsi,trailPositionCount:r.trailPositions.length,sessionId:r.feed.sessionId,firstConnectPhase:r.feed.firstConnectPhase,firstConnectStartedAt:r.feed.firstConnectStartedAt,firstConnectDeadline:r.feed.firstConnectDeadline}}function m(){return{trailMmsi:r.trailMmsi,trailPositionCount:r.trailPositions.length,vesselCount:r.records.byMmsi.size}}return{_bindVesselInteractionForTest:a,_setVesselStateForTest:c,_setVesselOverlayHostForTest:l,_updateVesselCardsForTest:u,_reconcileVesselsForTest:h,_applyAisFeedSnapshotForTest:d,_loadLivePositionsForTest:f,_beginAisSessionForTest:p,_setAisRuntimeForTest:g,_getVesselFeedStateForTest:_,_getVesselStateForTest:m}}function ix({vesselState:e,services:t,parts:n,layer:i,options:o}){const{state:r}=e;function s(c=[]){return{ok:!1,count:0}}function a(){return[]}return{_setFocusEvidenceVessels:s,_focusEvidenceVesselSnapshot:a}}function ox({vesselState:e,services:t,parts:n,layer:i,options:o}){const{state:r}=e,{formatKnots:s}=t.labels;function a(){if(r.feed.transportStatus==="auth-failed")return 0;const m=Number(r.feed.nextAttemptAt);return!Number.isFinite(m)||m<=0?0:Math.max(0,Math.ceil((m-e._aisRuntime.now())/1e3))}function c(m,b){if(m==="auth-failed")return"API key rejected — check AISSTREAM_API_KEY";if(m==="stale"){const v=Math.round(Number(b==null?void 0:b.silentForMs)/1e3);return Number.isFinite(v)&&v>0?`feed silent ${v}s — no AIS data`:"feed silent — no AIS data"}const C=Number(b==null?void 0:b.reconnectAttempt),y=Number.isFinite(C)&&C>=1?` (attempt ${C})`:"";return m==="down"?`feed down — retrying slowly${y}`:`reconnecting to feed…${y}`}function l(m,b){const C=m&&typeof m.status=="string"?m.status:null;if(C&&KP.has(C))return c(C,m);if(b>0)return null;if(cM.has(C))return m!=null&&m.lastMessageAt?"awaiting usable AIS positions…":"awaiting first AIS message…";if(!C)return null;const y=typeof m.error=="string"&&m.error.trim()?m.error.trim():"",v=wg[C]||"feed unavailable";return y&&!wg[C]?`${v} (${y})`:v}function u(m){return Number.isFinite(Number(m==null?void 0:m.lat))&&Number.isFinite(Number(m==null?void 0:m.lon))}function h(m){const b=Array.isArray(m==null?void 0:m.rows)?m.rows:[],C=b.filter(u),y=typeof(m==null?void 0:m.status)=="string"?m.status:null,v=(m==null?void 0:m.lastMessageAt)??null,M=C.length;return{transportStatus:y,lastMessageAt:v,rawRows:b,acceptedRows:C,rawRowCount:Number.isInteger(m==null?void 0:m.rawRowCount)&&m.rawRowCount>=b.length?m.rawRowCount:b.length,acceptedRowCount:M,error:l(m,M)||(M===0?"awaiting usable AIS positions…":null)}}function d(m){const b=M=>Number.isFinite(M)?M:null,C=M=>String(M??"").trim()||null,y=C(m==null?void 0:m.mmsi),v=C(m==null?void 0:m.name);return{id:v||y,mmsi:y,name:v,lat:b(m==null?void 0:m.lat),lon:b(m==null?void 0:m.lon),speedKts:b(m==null?void 0:m.speed),courseDeg:b(m==null?void 0:m.course),shipType:C(m==null?void 0:m.type),destination:C(m==null?void 0:m.destination),navStatus:null}}function f(m,b){return(Number.isFinite(m)?m:0)+b}function p(m={}){const b=g(m.selectedMmsi),C=g(m.pickedMmsi),y=m.gesture||"click";return y==="escape"?b?{action:"deselect"}:{action:"none"}:y!=="click"?{action:"none"}:C?C===b?{action:"none"}:{action:"select"}:b?{action:"deselect"}:{action:"none"}}function g(m){return m==null?null:String(m).trim()||null}return{aisRetryInSec:a,describeDegradedAisFeed:c,deriveAisFeedError:l,hasUsableVesselCoordinates:u,classifyAisFeedSnapshot:h,mapAnalystRecord:d,vesselDatumHeightM:f,reduceVesselSelection:p,normalizeSelectionMmsi:g,methods:{mapAnalystRecord:d,deriveAisFeedError:l,classifyAisFeedSnapshot:h,vesselDatumHeightM:f,reduceVesselSelection:p,id:"ais-live-vessels",name:"Live AIS Vessels",icon:"◭",source:"AISStream",updateInterval:GP,statsRefreshInterval:1e3,findByQuery(m){var M;if(m==null)return null;const b=r.records.all;if(!Array.isArray(b)||!b.length)return null;const C=String(m).trim();if(!C)return null;let y=null;if(/^\d+$/.test(C)&&(y=r.records.byMmsi.get(C)||null),!y){const w=C.toLowerCase();y=b.find(E=>String(E.name||"").toLowerCase().includes(w))||null}if(!y)return null;const v=((M=n.rendering.getVisual(y).billboard)==null?void 0:M.position)||n.rendering.getVisual(y).position;return v?{mmsi:y.mmsi,name:y.name,position:v,latitude:y.lat,longitude:y.lon,speedKt:y.speed,course:y.course,type:y.type}:null},getNearby(m,b,C=25){var E;const y=r.records.all;if(!m||!Array.isArray(y)||!y.length)return[];const v=Number.isFinite(b)&&b>0?b:1/0,M=Number.isFinite(C)&&C>0?Math.floor(C):25,w=[];for(const k of y){const T=n.rendering.getVisual(k);if(!Number.isFinite(k.lat)||!Number.isFinite(k.lon))continue;const I=((E=T.billboard)==null?void 0:E.position)||T.position;if(!I)continue;const R=Cesium.Cartesian3.distance(m,I);!Number.isFinite(R)||R>v||w.push({mmsi:k.mmsi,name:k.name,position:I,distanceM:R})}return w.sort((k,T)=>k.distanceM-T.distanceM),w.slice(0,M)},hasContact(m){return!r.feed.enabled||!r.records.byMmsi||r.records.byMmsi.size===0?null:m?r.records.byMmsi.has(String(m).trim()):!1},getAllPositions(m=800){var v;const b=[],C=r.records.all;if(!Array.isArray(C))return b;const y=Number.isFinite(m)&&m>0?Math.floor(m):800;for(const M of C){const w=n.rendering.getVisual(M);if(b.length>=y)break;const E=((v=w.billboard)==null?void 0:v.position)||w.position;E&&b.push({id:M.mmsi,label:M.name||M.mmsi,position:E,latitude:M.lat,longitude:M.lon})}return b},getAnalystRecords(m=2e3){if(!r.feed.enabled)return[];const b=r.records.all;if(!Array.isArray(b)||!b.length)return[];const C=Number.isFinite(m)?Math.max(1,Math.floor(m)):2e3,y=[];for(const v of b){if(y.length>=C)break;y.push(d(v))}return y},selectById(m){if(m==null)return!1;const b=String(m).trim();if(!b)return!1;const C=r.records.byMmsi.get(b);return C?(n.selection.selectVessel(C),!0):!1},clearSelection(){return n.selection.clearVesselInspection(),!0},getSelectedInfo(){const m=r.selectedRecord;return m?{mmsi:m.mmsi,name:m.name,latitude:m.lat,longitude:m.lon,speedKt:m.speed,course:m.course,type:m.type}:null},getDetectableObjects(m={}){var k;if(!r.feed.enabled||!r.billboardCollection||!r.billboardCollection.show)return[];const b=r.records.all;if(!Array.isArray(b)||!b.length)return[];const C=Number.isFinite(m.maxCount)?Math.max(1,Math.floor(m.maxCount)):b.length,y=Number.isFinite(m.seed)?Math.floor(m.seed):0,v=Math.max(1,Math.ceil(b.length/C)),M=y%v,w=r.selectedRecord,E=[];for(let T=0;T=C))break}return E},getStats(){const m=r.feed.firstConnectPhase==="loading";return{count:r.feed.count,lastUpdate:r.feed.lastUpdate,loading:r.feed.loading||m,loadingLabel:m?Jl:r.feed.loadingLabel,error:r.feed.error,stale:r.feed.stale,status:r.feed.firstConnectPhase==="unavailable"?"unavailable":void 0,transportStatus:r.feed.transportStatus,lastMessageAt:r.feed.lastMessageAt,rawRowCount:r.feed.rawRowCount,acceptedRowCount:r.feed.acceptedRowCount,retryInSec:a()}}}}}function rx({source:e,services:t,options:n={}}={}){const i=YP({source:e,services:t}),o={},r={},s={vesselState:i,services:t,parts:o,layer:r,options:n};return o.lifecycle=XP(s),o.rendering=ZP(s),o.selection=JP(s),o.tracking=ex(s),o.cards=tx(s),o.testing=nx(s),o.evidence=ix(s),o.queries=ox(s),o.snapshots=QP({state:i.state,records:i.state.records,rendering:o.rendering,tracking:o.tracking,selection:o.selection,cards:o.cards}),o.ingestion=RP({feed:i.state.feed,readSource:()=>i._source,readViewer:()=>i.state.viewer,getRowLimit:o.rendering.renderRowLimit,readCount:()=>i.state.records.all.length,applyRows:o.snapshots.reconcileVessels,classifySnapshot:o.queries.classifyAisFeedSnapshot,isDefinitiveTransportFailure:o.lifecycle.isDefinitiveTransportFailure,isGraceEligibleTransport:o.lifecycle.isGraceEligibleTransport,markUnavailable:o.lifecycle.markAisUnavailable,settleFirstConnect:o.lifecycle.settleFirstConnectPhase,now:()=>i._aisRuntime.now(),setSourceLabel:a=>{r.source=a}}),Object.assign(r,o.queries.methods,o.lifecycle.methods,o.ingestion.methods),r.source=(e==null?void 0:e.label)||"Vessels",Object.assign(r,{applyVesselFocusDeemphasis:o.rendering.applyVesselFocusDeemphasis,buildVesselCard:o.cards.buildVesselCard,buildSelectedVesselCard:o.cards.buildSelectedVesselCard,cardScreenSeparated:o.cards.cardScreenSeparated}),Object.defineProperty(r,"testing",{value:o.testing}),r}const ec="gev:world-request-focus",uM=1.9,dm=Object.freeze({vessel:Object.freeze({radiusM:150,rangeM:1200,pitchDeg:-30}),fire:Object.freeze({radiusM:400,rangeM:3e3,pitchDeg:-35})});function iu(e){if(!e||!dm[e.kind]||!String(e.id||"").trim())return!1;const{position:t}=e;if(!t||!Number.isFinite(t.x)||!Number.isFinite(t.y)||!Number.isFinite(t.z))return!1;const n=Cesium.Cartesian3.magnitude(t);return Number.isFinite(n)&&n>=Cesium.Ellipsoid.WGS84.minimumRadius*.95}function sx(e,t=globalThis.window){return!iu(e)||typeof(t==null?void 0:t.dispatchEvent)!="function"?!1:(t.dispatchEvent(new CustomEvent(ec,{detail:e})),!0)}function dM(e,t){if(!(e!=null&&e.addEventListener)||!(e!=null&&e.removeEventListener)||typeof t!="function")return()=>{};e.addEventListener(ec,t);let n=!1;return()=>{n||(n=!0,e.removeEventListener(ec,t))}}function hM(e,t,n){const i=e==null?void 0:e.detail;return!iu(i)||typeof t!="function"||typeof n!="function"?!1:t(i,()=>n(i))}function fM(e,t={}){var s;const n=e==null?void 0:e.camera,i=dm[t.kind];if(!n||!i||!iu(t))return!1;const o=Number.isFinite(n.heading)?n.heading:0,r=t.durationSec>0?t.durationSec:uM;return(s=n.cancelFlight)==null||s.call(n),n.flyToBoundingSphere(new Cesium.BoundingSphere(t.position,i.radiusM),{offset:new Cesium.HeadingPitchRange(o,Cesium.Math.toRadians(i.pitchDeg),i.rangeM),duration:r,easingFunction:Cesium.EasingFunction.CUBIC_IN_OUT}),!0}const mM=Object.freeze(Object.defineProperty({__proto__:null,WORLD_CLICK_FOCUS_DURATION_SEC:uM,WORLD_FOCUS_FRAMING:dm,WORLD_FOCUS_REQUEST_EVENT:ec,flyToWorldTarget:fM,isValidWorldFocusTarget:iu,registerWorldFocusRequestListener:dM,requestWorldFocus:sx,routeWorldFocusRequest:hM},Symbol.toStringTag,{value:"Module"}));function ax({source:e,options:t={}}){return rx({source:e,options:t,services:{context:Go,trails:Df,labels:Bf,picking:rn,overlay:ui,geoid:wf,sprites:Ki,focus:ma,worldFocus:mM,render:Pt}})}const lx=.08,cx=1e-6,hm=new Cesium.Cartesian3;function Na(e,t,n,i){const o=Cesium.Cartesian3.dot(t,i),r=1-o*o;if(Math.abs(r)Math.PI&&(i-=n),i<=-Math.PI&&(i+=n),i}const rr="cctv-gizmo-",Tg=96,ux=.12,dx=6,hx=40,fx=1.6,mx=16,px=120,gx=Cesium.Color.fromCssColorString("#35d8ff"),_x=Cesium.Color.fromCssColorString("#ff5fd0"),bx=Cesium.Color.fromCssColorString("#ff5252"),Cx=Cesium.Color.fromCssColorString("#52ff7a"),yx=Cesium.Color.fromCssColorString("#5b8cff"),Vu=Cesium.Color.fromCssColorString("#ffd97a"),kg=e=>e*Math.PI/180,Hu=e=>e*180/Math.PI;function Ag(e){const t=Cesium.Transforms.eastNorthUpToFixedFrame(e),n=Cesium.Matrix4.getMatrix3(t,new Cesium.Matrix3);return{east:Cesium.Matrix3.getColumn(n,0,new Cesium.Cartesian3),north:Cesium.Matrix3.getColumn(n,1,new Cesium.Cartesian3),up:Cesium.Matrix3.getColumn(n,2,new Cesium.Cartesian3)}}function hl(e,t,n,i){const o=Cesium.Cartesian3.multiplyByScalar(e,t,new Cesium.Cartesian3),r=Cesium.Cartesian3.multiplyByScalar(n,i,new Cesium.Cartesian3);return Cesium.Cartesian3.add(o,r,o)}function Ig(e,t,n){const i=kg(e),o=kg(t),r=hl(n.east,Math.sin(i),n.north,Math.cos(i)),s=hl(n.east,Math.cos(i),n.north,-Math.sin(i)),a=hl(r,Math.cos(o),n.up,Math.sin(o));return{forwardHoriz:r,right:s,view:a}}function Rg(e,t,n,i){const o=[];for(let r=0;r<=Tg;r++){const s=r/Tg*2*Math.PI,a=hl(n,Math.cos(s)*t,i,Math.sin(s)*t);o.push(Cesium.Cartesian3.add(e,a,a))}return o}function vx({viewer:e,getActiveRecord:t,applyPatch:n,endPatch:i}){let o=!1,r=null,s=null,a=0,c=0;const l=new Map,u=e.scene,h=new Cesium.ScreenSpaceEventHandler(u.canvas);function d(T,I){const R=`${rr}${T}`,S=e.entities.getById(R);S&&e.entities.remove(S);const A=e.entities.add({id:R,show:!1,...I});return l.set(T,A),A}function f(T,I,R,S=!1){d(T,{...S?{position:Cesium.Cartesian3.ZERO,point:{pixelSize:14,color:I,outlineColor:Cesium.Color.BLACK.withAlpha(.7),outlineWidth:2,disableDepthTestDistance:Number.POSITIVE_INFINITY}}:{},polyline:{positions:[],width:R,material:S?new Cesium.PolylineArrowMaterialProperty(I):I.withAlpha(.9),depthFailMaterial:I.withAlpha(.45)}})}function p(T,I,R){d(T,{position:Cesium.Cartesian3.ZERO,point:{pixelSize:R,color:I,outlineColor:Cesium.Color.BLACK.withAlpha(.7),outlineWidth:2,disableDepthTestDistance:Number.POSITIVE_INFINITY}})}f("ring-heading",gx,3),f("ring-pitch",_x,3),f("move-east",bx,12,!0),f("move-north",Cx,12,!0),f("move-up",yx,12,!0),p("handle-range",Vu,13),p("handle-fov-l",Vu,10),p("handle-fov-r",Vu,10);function g(){for(const T of l.values())T.show=!1}function _(){const T=o?r?r.record:t():null,I=T==null?void 0:T.frustumPositions,R=T==null?void 0:T.camera;if(!T||!I||!R){g();return}const S=I.mount,A=Ag(S),{forwardHoriz:L}=Ig(R.headingDeg,R.pitchDeg,A),F=Math.max(1,Number(R.rangeM)||1),P=Math.min(hx,Math.max(dx,F*ux)),O=P*fx;l.get("ring-heading").polyline.positions=Rg(S,P,A.north,A.east),l.get("ring-pitch").polyline.positions=Rg(S,P,L,A.up);const D=G=>[S,Cesium.Cartesian3.add(S,Cesium.Cartesian3.multiplyByScalar(G,O,new Cesium.Cartesian3),new Cesium.Cartesian3)],$=D(A.east),x=D(A.north),N=D(A.up);l.get("move-east").polyline.positions=$,l.get("move-east").position=$[1],l.get("move-north").polyline.positions=x,l.get("move-north").position=x[1],l.get("move-up").polyline.positions=N,l.get("move-up").position=N[1],l.get("handle-range").position=I.capCenter,l.get("handle-fov-l").position=Cesium.Cartesian3.midpoint(I.tl,I.bl,new Cesium.Cartesian3),l.get("handle-fov-r").position=Cesium.Cartesian3.midpoint(I.tr,I.br,new Cesium.Cartesian3);for(const G of l.values())G.show=!0}function m(T){var R;const I=((R=T==null?void 0:T.id)==null?void 0:R.id)??(T==null?void 0:T.id);return typeof I!="string"||!I.startsWith(rr)?null:I.slice(rr.length)}function b(T){var R,S;try{const A=u.pick(T,14,14),L=m(A);if(L&&((R=l.get(L))!=null&&R.show))return L}catch(A){typeof window<"u"&&window.__gevGizmoDebug&&console.debug("[CCTV:gizmo] pick threw:",(A==null?void 0:A.message)||A)}let I=[];try{I=u.drillPick(T,6,14,14)||[]}catch(A){return typeof window<"u"&&window.__gevGizmoDebug&&console.debug("[CCTV:gizmo] drillPick threw:",(A==null?void 0:A.message)||A),null}typeof window<"u"&&window.__gevGizmoDebug&&console.debug("[CCTV:gizmo] drillPick @",T==null?void 0:T.x,T==null?void 0:T.y,"→",JSON.stringify(I.map(A=>{var L,F,P;return String(((L=A==null?void 0:A.id)==null?void 0:L.id)??(A==null?void 0:A.id)??((P=(F=A==null?void 0:A.primitive)==null?void 0:F.constructor)==null?void 0:P.name))})));for(const A of I){const L=m(A);if(L&&((S=l.get(L))!=null&&S.show))return L}return null}function C(T){try{return e.camera.getPickRay(T)||null}catch{return null}}function y(T){var I;(I=u.canvas)!=null&&I.style&&(u.canvas.style.cursor=T)}function v(T){const I=T?`${rr}${T}`:null;if(I!==s){s=I;for(const[R,S]of l.entries()){if(!S.point)continue;const A=s===`${rr}${R}`;S.point.pixelSize=(R==="handle-range"?13:10)+(A?4:0)}y(s?"grab":"")}}function M(T,I){const R=t(),S=R==null?void 0:R.frustumPositions,A=R==null?void 0:R.camera,L=R==null?void 0:R.frustumGeometry;if(!R||!S||!(A!=null&&A.basePose)||!L)return!1;const F=C(I);if(!F)return!1;const P=Cesium.Cartesian3.clone(S.mount),O=Cesium.Cartesian3.clone(S.capCenter),D=Ag(P),{forwardHoriz:$,right:x,view:N}=Ig(A.headingDeg,A.pitchDeg,D),G={...A.calibration},W={...A.basePose},V={record:R,part:T,startCal:G,basePose:W,mount:P,capCenter:O,axes:D,forwardHoriz:$,right:x,view:N,effectiveRangeM:L.rangeM,startAngle:null,startParam:null};if(T==="ring-heading"){const H=Ko(F.origin,F.direction,P,D.up);if(!H)return!1;V.startAngle=Da(H,P,D.north,D.east)}else if(T==="ring-pitch"){const H=Ko(F.origin,F.direction,P,x);if(!H)return!1;V.startAngle=Da(H,P,$,D.up)}else if(T==="move-east"||T==="move-north"||T==="move-up"){const H=T==="move-east"?D.east:T==="move-north"?D.north:D.up;V.axisDir=H;const B=Na(F.origin,F.direction,P,H);if(B===null)return!1;V.startParam=B}else if(T==="handle-range"){const H=Na(F.origin,F.direction,P,N);if(H===null)return!1;V.startParam=H}else if(T==="handle-fov-l"||T==="handle-fov-r"){if(!Ko(F.origin,F.direction,O,N))return!1}else return!1;return r=V,y("grabbing"),u.screenSpaceCameraController&&(u.screenSpaceCameraController.enableInputs=!1),!0}function w(T){const I=C(T);if(!I||!r)return null;const{part:R,startCal:S,basePose:A,mount:L,capCenter:F,axes:P,forwardHoriz:O,right:D,view:$}=r;if(R==="ring-heading"){const x=Ko(I.origin,I.direction,L,P.up);if(!x)return null;const N=Da(x,L,P.north,P.east);return{headingDeg:S.headingDeg+Hu(Eg(r.startAngle,N))}}if(R==="ring-pitch"){const x=Ko(I.origin,I.direction,L,D);if(!x)return null;const N=Da(x,L,O,P.up);return{pitchDeg:S.pitchDeg+Hu(Eg(r.startAngle,N))}}if(R==="move-east"||R==="move-north"||R==="move-up"){const x=Na(I.origin,I.direction,L,r.axisDir);if(x===null)return null;const N=x-r.startParam;return R==="move-east"?{offsetEastM:S.offsetEastM+N}:R==="move-north"?{offsetNorthM:S.offsetNorthM+N}:{heightM:S.heightM+N}}if(R==="handle-range"){const x=Na(I.origin,I.direction,L,$);return x===null||!(A.rangeM>0)?null:{rangeScale:Math.max(.01,x)/A.rangeM}}if(R==="handle-fov-l"||R==="handle-fov-r"){const x=Ko(I.origin,I.direction,F,$);if(!x)return null;const N=Math.abs(Cesium.Cartesian3.dot(Cesium.Cartesian3.subtract(x,F,new Cesium.Cartesian3),D)),G=Math.max(.5,N);return{fovDeg:Hu(2*Math.atan(G/Math.max(1,r.effectiveRangeM)))-A.fovDeg}}return null}function E(){if(!r)return;const T=r.record;r=null,u.screenSpaceCameraController&&(u.screenSpaceCameraController.enableInputs=!0),y(s?"grab":""),i(T)}function k(...T){typeof window<"u"&&window.__gevGizmoDebug&&console.debug("[CCTV:gizmo]",...T)}return h.setInputAction(T=>{if(!Bt()||!o)return;const I=b(T.position);if(k("LEFT_DOWN",T.position,"part:",I),!I)return;const R=M(I,T.position);k("beginDrag",I,"→",R)},Cesium.ScreenSpaceEventType.LEFT_DOWN),h.setInputAction(T=>{if(!o)return;const I=Date.now();if(r){if(I-a{o&&E()},Cesium.ScreenSpaceEventType.LEFT_UP),{setEnabled(T){o=!!T,o?_():(r&&E(),v(null),g())},refresh:_,destroy(){r&&E(),h.destroy();for(const T of l.values())e.entities.remove(T);l.clear(),y("")},isDragging:()=>!!r,isEnabled:()=>o}}const Mx="/api/cctv/frame",wx="/api/cctv/media",dh=1e4,Ex=96,Tx=54,kx=192,Ax=108,pM=112,Ix=.18,Rx=150,Lx=96,Px=1800,xx=6e3,Fx=7500,gM=9500,Sx=.45,Nx=.35,Dx=1e3,_M=250,bM=4,Ox=15e4,Bx=15e3,Vx=300*1e3,ur="cctv",Hx=Object.freeze({fullEnd:Px,midEnd:xx,end:gM,midValue:Sx,endValue:Nx,smoothToMid:!0});function $x(e,{minSepPx:t=pM,limit:n=1/0}={}){const i=(Array.isArray(e)?e:[]).filter(a=>a&&typeof a.id=="string"&&a.id&&Number.isFinite(a.sx)&&Number.isFinite(a.sy)).sort((a,c)=>(a.distanceKm??1/0)-(c.distanceKm??1/0)||a.id.localeCompare(c.id)),o=t*t,r=[],s=[];for(const a of i){if(s.length>=n)break;let c=!0;for(let l=0;l=_M}:{mode:"steady",launch:t===0&&n>=Dx}}function CM(){return{frame:null,stamp:0,failCount:0,lastAttemptAt:0}}function Ux(e,t,n){const i=e||CM();return t!=null&&t.ok&&t.frame?{frame:t.frame,stamp:n,failCount:0,lastAttemptAt:n}:{frame:i.frame,stamp:i.stamp,failCount:(i.failCount||0)+1,lastAttemptAt:n}}function zx(e){const t=Math.max(0,Number(e)||0);return Math.min(Vx,Bx*2**t)}function yM(e,t,n){return!e||!(!(e.stamp>0)||n-e.stamp>=t)?!1:e.lastAttemptAt>0?n-e.lastAttemptAt>=zx(e.failCount):!0}function jx(e,t,n=Lx){const i=new Set(t),o=(Array.isArray(e)?e:[]).filter(s=>s&&typeof s.id=="string"&&!i.has(s.id)).sort((s,a)=>(a.stamp||0)-(s.stamp||0)||s.id.localeCompare(a.id)),r=Math.max(0,n-i.size);return o.slice(r).map(s=>s.id)}function qx({id:e,position:t,title:n,frameSlot:i,rank:o=0,pinned:r=!1,active:s=!1,gapPx:a=16}={}){const c=Math.max(14,(Number(a)||14)+6);return{id:e,position:t,variant:"thumbnail",paintLane:"thumbnail",title:n,details:[],image:i,requireImage:!0,accent:Ht.accent,priority:s?1e6:r?9e5:1e5-o,selected:!1,pinned:r,protected:s,active:s,collisionGroup:"ambient-card",zIndex:50,interactive:!0,minDistance:0,maxDistance:Ox,distanceFadeStartRatio:.7,altitudeScale:Hx,altitudeFadeStart:Fx,altitudeFadeEnd:gM,edgeFade:"keyhole",horizonCull:!0,terrainOcclusion:!1,gapPx:c,leaderOffsetPx:Math.max(2,c-6),verticalOnly:!0,stateless:!0,minAnchorSeparationPx:pM,viewportMargin:4,viewportPadding:60,safeTopRatio:Ix,safeTopMaxPx:Rx,pinnedBypassesSafeTop:!0,thumbnailWidth:Ex,thumbnailHeight:Tx,thumbnailPadX:Ht.padding,thumbnailPadTop:Ht.padding,thumbnailPadBottom:Ht.padding,thumbnailTitleGap:2,thumbnailTitleHeight:Ht.titleHeight,thumbnailTitleChars:Ht.titleChars,thumbnailBackground:Ht.background,thumbnailTitleColor:Ht.titleColor,thumbnailTitleFont:Ht.titleFont,thumbnailLeaderColor:Ht.leader,thumbnailRuleColor:Ht.rule,thumbnailRuleHeight:Ht.ruleHeight,thumbnailRadius:Ht.radius}}const Vr=40,Wx=28,Kx=20,Yx=2500,Lg=15e3,Xx=300*1e3,Qx=Object.freeze({"austin transportation & public works":300*1e3,"transport for london":180*1e3,caltrans:180*1e3,"ontario 511":180*1e3,txdot:180*1e3,fintraffic:600*1e3});function Zx(e){const t=Number.isFinite(e)?Math.max(0,e):Lg;return t<=Yx?{cardLimit:Kx}:t<=Lg?{cardLimit:Wx}:{cardLimit:Vr}}const Jx=.8;function Pg(e,t,n=Jx){const i=Number.isFinite(e)?Math.max(0,e):1/0;return t?i*n:i}const eF=.5,tF=.9;function fm(e,t){return Number.isFinite(e)&&e>0&&Number.isFinite(t)&&t>0}function hh(e,t,n,i){if(!fm(n,i))return 0;if(!Number.isFinite(e)||!Number.isFinite(t))return 1;const o=n/2,r=i/2,s=Math.hypot(o,r)||1;return Math.min(1,Math.hypot(e-o,t-r)/s)}function nF(e,t=tF){const n=(Array.isArray(e)?e:[]).filter(o=>Number.isFinite(o)&&o>=0).sort((o,r)=>o-r);if(!n.length)return 0;const i=Math.min(1,Math.max(0,Number.isFinite(t)?t:0));return n[Math.round(i*(n.length-1))]}function iF(e,t,n,i=eF){const o=Number.isFinite(e)?Math.max(0,e):1/0;if(!Number.isFinite(o))return 1/0;const r=Math.min(1,Math.max(0,Number.isFinite(i)?i:0)),s=Number.isFinite(n)&&n>0?n:0,a=Number.isFinite(t)?Math.min(1,Math.max(0,t)):1;return(1-r)*o+r*s*a}const oF=5,rF=4;function sF(e,{budget:t=Vr,viewW:n=0,viewH:i=0,cols:o=oF,rows:r=rF}={}){const s=Number.isFinite(t)?Math.max(0,Math.floor(t)):0,a=(Array.isArray(e)?e:[]).filter(b=>b&&typeof b.id=="string"&&b.id&&Number.isFinite(b.sx)&&Number.isFinite(b.sy));if(!s||!a.length)return[];const c=fm(n,i),l=c?n:1,u=c?i:1,h=Math.max(1,Math.floor(o)),d=Math.max(1,Math.floor(r)),f=(b,C)=>(Number.isFinite(b.rankKm)?b.rankKm:1/0)-(Number.isFinite(C.rankKm)?C.rankKm:1/0)||b.id.localeCompare(C.id),p=new Map;for(const b of a){const C=Math.min(h-1,Math.max(0,Math.floor(b.sx/l*h))),v=Math.min(d-1,Math.max(0,Math.floor(b.sy/u*d)))*h+C,M=p.get(v);M?M.push(b):p.set(v,[b])}const g=[],_=[];for(const b of p.values()){b.sort(f),g.push(b[0]);for(let C=1;C=s)break;m.push(b)}return m.map(b=>b.id)}function aF(e,{cameraHeightM:t,incumbentIds:n,viewW:i,viewH:o}={}){const r=Zx(t),s=n instanceof Set?n:new Set(n||[]),a=fm(i,o);if(!a){const d=(Array.isArray(e)?e:[]).filter(g=>g&&typeof g.id=="string"&&g.id).map(g=>({id:g.id,distanceKm:Number.isFinite(g.distanceKm)?Math.max(0,g.distanceKm):1/0,rankKm:Pg(g.distanceKm,s.has(g.id)),inView:g.inView===!0,isVideo:g.isVideo===!0})).filter(g=>g.inView).sort((g,_)=>g.rankKm-_.rankKm||g.distanceKm-_.distanceKm||g.id.localeCompare(_.id)),f=[],p=new Set;for(const g of d)if(!(g.isVideo||p.has(g.id))&&(f.push(g.id),p.add(g.id),f.length>=r.cardLimit))break;return{cardIds:f,budgets:r}}const c=new Map;for(const d of Array.isArray(e)?e:[]){if(!d||typeof d.id!="string"||!d.id.trim()||d.inView!==!0||d.isVideo===!0||!Number.isFinite(d.distanceKm))continue;const f={id:d.id,distanceKm:Math.max(0,d.distanceKm),rankKm:1/0,sx:Number.isFinite(d.sx)?d.sx:NaN,sy:Number.isFinite(d.sy)?d.sy:NaN},p=c.get(f.id);(!p||lF(f,p,{screened:a,viewW:i,viewH:o})<0)&&c.set(f.id,f)}const l=[...c.values()],u=nF(l.map(d=>d.distanceKm));for(const d of l){const f=iF(d.distanceKm,hh(d.sx,d.sy,i,o),u);d.rankKm=Pg(f,s.has(d.id))}l.sort((d,f)=>d.rankKm-f.rankKm||d.distanceKm-f.distanceKm||d.id.localeCompare(f.id));let h;if(h=sF(l,{budget:r.cardLimit,viewW:i,viewH:o}),h.length=r.cardLimit)break;d.has(f.id)||h.push(f.id)}}return{cardIds:h,budgets:r}}function lF(e,t,{screened:n,viewW:i,viewH:o}){if(e.distanceKm!==t.distanceKm)return e.distanceKmr||i-m>=s?l.push(p):h.push({id:p,misses:_,since:m})}h.sort((p,g)=>p.since-g.since||g.misses-p.misses||p.id.localeCompare(g.id));const d=Math.max(0,o-c.length),f=Math.max(0,h.length-d);for(let p=0;p0)return Math.max(6e4,Math.min(1200*1e3,Math.round(t)));const n=String((e==null?void 0:e.provider)||"").trim().toLowerCase();return Qx[n]||Xx}const hF=1e4,fF=8,mF=90,pF=7e3,gF=6e4,_F=1e4,bF=6e4,Ji=1920,eo=1080,Oa=64,Ba=36,xg=14,CF=1.8,yF=4,vF=120,MF=2,wF=250,EF=300,TF=10,kF=750,Fg="godsEyeView.cctv.calibration.v2",AF=1e3,Sg=2,Ng=60,tc=120,IF=220,mn=Object.freeze({FOCUSED:"focused",NO_ACTIVE_CAMERA:"no-active-camera",TRACKING_HOLDS_VIEW:"tracking-holds-view",COCKPIT_ACTIVE:"cockpit-active"}),RF=4,LF=12,PF=8e3,nc=Object.freeze({offsetNorthM:0,offsetEastM:0,headingDeg:0,pitchDeg:0,fovDeg:0,rangeScale:1,heightM:0}),xF="data:image/svg+xml;base64,"+btoa(` + + + + + + + + + + + + + + + `),FF=[{id:"nyc-midtown-w",cityId:"nyc",poiIndex:1,label:"Midtown West @ 34th",offsetNorthM:120,offsetEastM:-70,headingDeg:206,fovDeg:74,rangeM:880,elevationM:26},{id:"nyc-wtc-n",cityId:"nyc",poiIndex:2,label:"WTC North Plaza",offsetNorthM:95,offsetEastM:34,headingDeg:164,fovDeg:68,rangeM:760,elevationM:32},{id:"nyc-times-square-ne",cityId:"nyc",poiIndex:1,label:"Times Sq Northeast",offsetNorthM:230,offsetEastM:120,headingDeg:218,fovDeg:66,rangeM:640,elevationM:24},{id:"sf-market-5th",cityId:"sf",poiIndex:2,label:"Market & 5th",offsetNorthM:-160,offsetEastM:80,headingDeg:320,fovDeg:70,rangeM:780,elevationM:20},{id:"sf-financial-district",cityId:"sf",poiIndex:1,label:"SF Financial Core",offsetNorthM:110,offsetEastM:52,headingDeg:205,fovDeg:72,rangeM:760,elevationM:24},{id:"tokyo-shibuya-scramble",cityId:"tokyo",poiIndex:4,label:"Shibuya Crossing",offsetNorthM:180,offsetEastM:46,headingDeg:18,fovDeg:82,rangeM:640,elevationM:30},{id:"tokyo-ginza-core",cityId:"tokyo",poiIndex:0,label:"Ginza Core",offsetNorthM:-180,offsetEastM:150,headingDeg:245,fovDeg:70,rangeM:690,elevationM:28},{id:"tokyo-asakusa-n",cityId:"tokyo",poiIndex:3,label:"Asakusa North Gate",offsetNorthM:110,offsetEastM:-65,headingDeg:192,fovDeg:68,rangeM:620,elevationM:24},{id:"london-city-a1",cityId:"london",poiIndex:4,label:"City Cluster A1",offsetNorthM:80,offsetEastM:65,headingDeg:220,fovDeg:71,rangeM:720,elevationM:27},{id:"london-soho-core",cityId:"london",poiIndex:2,label:"Soho Core",offsetNorthM:210,offsetEastM:120,headingDeg:206,fovDeg:70,rangeM:700,elevationM:22},{id:"paris-rivoli",cityId:"paris",poiIndex:4,label:"Rue de Rivoli",offsetNorthM:55,offsetEastM:85,headingDeg:248,fovDeg:66,rangeM:640,elevationM:22},{id:"paris-champs-n",cityId:"paris",poiIndex:1,label:"Champs-Élysées North",offsetNorthM:130,offsetEastM:-38,headingDeg:175,fovDeg:68,rangeM:700,elevationM:26},{id:"dc-mall-center",cityId:"dc",poiIndex:1,label:"National Mall Center",offsetNorthM:120,offsetEastM:20,headingDeg:258,fovDeg:78,rangeM:940,elevationM:24},{id:"dc-pentagon-s",cityId:"dc",poiIndex:3,label:"Pentagon South",offsetNorthM:-100,offsetEastM:92,headingDeg:14,fovDeg:66,rangeM:620,elevationM:21},{id:"dubai-difc-loop",cityId:"dubai",poiIndex:4,label:"DIFC Loop",offsetNorthM:92,offsetEastM:-45,headingDeg:196,fovDeg:70,rangeM:720,elevationM:26},{id:"dubai-downtown-east",cityId:"dubai",poiIndex:0,label:"Downtown East",offsetNorthM:-130,offsetEastM:190,headingDeg:322,fovDeg:72,rangeM:760,elevationM:28},{id:"austin-congress-s",cityId:"austin",poiIndex:0,label:"Congress Southbound",offsetNorthM:-165,offsetEastM:40,headingDeg:12,fovDeg:74,rangeM:760,elevationM:24},{id:"austin-downtown-west",cityId:"austin",poiIndex:1,label:"Downtown West",offsetNorthM:-120,offsetEastM:-160,headingDeg:120,fovDeg:69,rangeM:700,elevationM:20}],fh=Cesium.Color.fromCssColorString("#6be8ff").withAlpha(.88),Dg=Cesium.Color.fromCssColorString("#ffd97a").withAlpha(.95),SF=Cesium.Color.fromCssColorString("#2fe0ff").withAlpha(.24),NF=Cesium.Color.fromCssColorString("#2fe0ff").withAlpha(.2),DF=Cesium.Color.fromCssColorString("#2fe0ff").withAlpha(.18),OF=Cesium.Color.fromCssColorString("#8dff87").withAlpha(.58),BF=Cesium.Color.fromCssColorString("#d7ff8d").withAlpha(.82),VF=Cesium.Color.fromCssColorString("#8dff87").withAlpha(.18),HF=Cesium.Color.fromCssColorString("#d7ff8d").withAlpha(.26),$F=Cesium.Color.fromCssColorString("#6be8ff").withAlpha(.55),GF=16,UF=_M,Og=.06,zF=16,Bg=Object.freeze({cohortLimit:Vr,collisionCapacity:Vr,moving:!0,solveIntervalMs:125}),Va="cctv-projection",jF=Object.freeze({cohortLimit:1,collisionCapacity:0,moving:!1}),qF=120,WF=1e3;function KF({state:e,services:t,parts:n,source:i}){function o(g){return!g||typeof g!="object"?!1:Object.prototype.hasOwnProperty.call(g,"offsetNorthM")||Object.prototype.hasOwnProperty.call(g,"offsetEastM")}function r(g={}){const _=g&&typeof g=="object"?g:{};return{offsetNorthM:n.model.quantize(n.model.clamp(n.model.safeNumber(_.offsetNorthM,0),-900,900),.1),offsetEastM:n.model.quantize(n.model.clamp(n.model.safeNumber(_.offsetEastM,0),-900,900),.1),headingDeg:n.model.quantize(n.model.clamp(n.model.safeNumber(_.headingDeg,0),-180,180),.1),pitchDeg:n.model.quantize(n.model.clamp(n.model.safeNumber(_.pitchDeg,0),-45,45),.1),fovDeg:n.model.quantize(n.model.clamp(n.model.safeNumber(_.fovDeg,0),-50,50),.1),rangeScale:n.model.quantize(n.model.clamp(n.model.safeNumber(_.rangeScale,1),.35,3),.01),heightM:n.model.quantize(n.model.clamp(n.model.safeNumber(_.heightM,0),-120,240),.1)}}function s(g,_){const m=n.model.clamp(n.model.safeNumber(_,700),IF,2200),b=n.model.clamp(n.model.safeNumber(_,700),tc,2200);return m===b?g:r({...g,rangeScale:g.rangeScale*(m/b)})}function a(g){const _=r(g);return Object.keys(nc).every(m=>Math.abs(_[m]-nc[m])<1e-4)}function c(g=n.model.safeWindowLocalStorage()){const _=new Map;if(!g)return _;try{const m=g.getItem(Fg);if(!m)return _;const b=JSON.parse(m);if(!b||typeof b!="object")return _;for(const[C,y]of Object.entries(b))!C||!y||typeof y!="object"||!y.values||typeof y.values!="object"||_.set(C,{values:r(y.values),source:"manual",savedAt:n.model.safeNumber(y.savedAt,0),rangeFloorM:n.model.safeNumber(y.rangeFloorM,NaN)});return _}catch{return _}}function l(g,_=n.model.safeWindowLocalStorage()){if(_)try{const m={};for(const[b,C]of g.entries())m[b]={values:r(C.values),source:"manual",savedAt:n.model.safeNumber(C.savedAt,Date.now()),...Number.isFinite(C.rangeFloorM)?{rangeFloorM:C.rangeFloorM}:{}};_.setItem(Fg,JSON.stringify(m))}catch{}}function u(){return c()}function h(){l(e._calibrationById)}function d(g){return(g==null?void 0:g.calSource)==="manual"?"calibrated":(g==null?void 0:g.poseSource)==="curated"?"curated":"raw-prior"}function f(g,_,m={}){if(!g||!_||typeof _!="object")return!1;g.camera.calibration=r({...g.camera.calibration,..._}),n.model.ensureCameraPose(g.camera),"rangeScale"in _&&(g.probeClampRangeM=null);const b=o(_);return m.transient===!0&&b&&(g.calibrationAnchorDirty=!0),g.calDirty=!0,m.transient===!0?(n.geometry.applyFrustumGeometry(g,n.ground.groundAltFor(g)),n.presentation.notifyListenersThrottled(),!0):(b?n.ground.resolveCommittedGroundAnchor(g):n.geometry.applyFrustumGeometry(g,n.ground.groundAltFor(g)),n.ground.resolveFootprintGround(g),n.frames.refreshProjectionImage(g,!0),!0)}function p(){if(e._gizmo||!e._viewer)return;const g=_=>{var m;return _&&e._recordById.get((m=_.camera)==null?void 0:m.id)===_?_:null};e._gizmo=vx({viewer:e._viewer,getActiveRecord:()=>e._enabled&&e._calibrationMode?n.selection.getActiveRecord():null,applyPatch:(_,m)=>{const b=e._enabled&&e._calibrationMode?g(m):null;b&&f(b,_,{transient:!0})},endPatch:_=>{const m=g(_);m&&(n.ground.resolveFootprintGround(m),m.calibrationAnchorDirty?(m.calibrationAnchorDirty=!1,n.ground.resolveCommittedGroundAnchor(m)):n.geometry.applyFrustumGeometry(m,n.ground.groundAltFor(m)),n.frames.refreshProjectionImage(m,!0),n.rendering.refreshCoverageStyles(),n.presentation.notifyListeners())}})}return{calibrationPatchMovesAnchor:o,normalizeCalibration:r,isDefaultCalibration:a,migrateRangeScaleForFloor:s,readCalibrationStoreV2:c,writeCalibrationStoreV2:l,loadCalibrationStore:u,saveCalibrationStore:h,deriveCalBadge:d,applyCalibrationPatch:f,ensureGizmo:p}}function YF({state:e,services:t,parts:n,source:i}){function o(){n.cards.pushAmbientCardEntries()}function r(u=null){e._cctvOverlayHost=u?{...e.DEFAULT_CCTV_OVERLAY_HOST,...u}:e.DEFAULT_CCTV_OVERLAY_HOST,e._projectionOverlayOwnerId=null}function s(u,h){e._viewer=u;const d=h.frustumGeometry||n.geometry.computeFrustumGeometry(h.camera,n.ground.groundAltFor(h),h.probeClampRangeM),f=h.frustumPositions||n.geometry.frustumCartesians(d);h.frustumGeometry=d,h.frustumPositions=f;const p={cameraId:String(h.camera.id),planeEntity:null,labelPosition:new Cesium.Cartesian3,overlayEntry:null,planeMaterial:new Cesium.ColorMaterialProperty(Cesium.Color.WHITE)};return n.projection.createProjectionPlane(h,p,d,f),h.projection=p,p}function a(u){n.projection.updatePlanePlacement(u)}function c(u){return n.selection.extractPickedCameraId(u)}function l({viewer:u=null,records:h=[],activeCameraId:d=null,enabled:f=!0,coverageMode:p="on",showProjection:g=!1}={}){e._viewer=u,e._records=Array.isArray(h)?h:[],e._recordById=new Map(e._records.filter(_=>{var m;return(m=_==null?void 0:_.camera)==null?void 0:m.id}).map(_=>[_.camera.id,_])),e._coverageEntities=[],e._projectionEntities=[],e._billboards=null,e._activeCameraId=d,e._autoHopSuspended=!1,e._enabled=!!f,e._coverageMode=n.model.normalizeCoverageMode(p,"on"),e._showProjection=!!g}return{_pushAmbientCardEntriesForTest:o,_setCctvOverlayHostForTest:r,_createCctvProjectionPlaneForTest:s,_updateCctvProjectionPlaneForTest:a,_extractPickedCameraIdForTest:c,_setCctvCoverageStateForTest:l}}function XF({state:e,services:t,parts:n,source:i}){const{holdContinuousRender:o,releaseContinuousRender:r}=t.render;function s({cameraId:m,name:b,position:C}){return{id:String(m),position:C,variant:"selected",selected:!0,protected:!0,paintLane:"selected",collisionGroup:"ambient-card",priority:Number.MAX_SAFE_INTEGER-1,title:String(b||m||"CAMERA"),details:[],accent:"#6be8ff",interactive:!1,gapPx:6,verticalOnly:!0,placement:"above",edgeFade:"keyhole",horizonCull:!0,terrainOcclusion:!1}}function a(m){const b=m==null?void 0:m.projection;if(!(b!=null&&b.planeEntity))return;const C=m.frustumGeometry||n.geometry.computeFrustumGeometry(m.camera,n.ground.groundAltFor(m),m.probeClampRangeM),y=m.frustumPositions||n.geometry.frustumCartesians(C);b.planeEntity.position=y.capCenter,b.planeEntity.orientation=n.model.planeOrientationFor(m.camera,y.capCenter),b.planeEntity.plane&&(b.planeEntity.plane.dimensions=new Cesium.Cartesian2(C.halfW*2,C.halfH*2)),b.labelPosition&&Cesium.Cartesian3.clone(y.label,b.labelPosition)}function c(){e._cctvOverlayHost.clearSource(Va),e._cctvOverlayHost.setVisible(Va,!1),e._projectionOverlayOwnerId=null}function l(m,b){m&&(m.planeEntity&&(m.planeEntity.show=!!b),b&&m.overlayEntry&&m.cameraId?e._projectionOverlayOwnerId!==m.cameraId&&(e._cctvOverlayHost.setEntries(Va,[m.overlayEntry],jF),e._cctvOverlayHost.setVisible(Va,!0),e._projectionOverlayOwnerId=m.cameraId):e._projectionOverlayOwnerId===m.cameraId&&c())}function u(m,b,C,y){return b.labelPosition||(b.labelPosition=new Cesium.Cartesian3),Cesium.Cartesian3.clone(y.label,b.labelPosition),b.cameraId=String(m.camera.id),b.overlayEntry=s({cameraId:b.cameraId,name:m.camera.name,position:()=>b.labelPosition}),b.planeEntity=e._viewer.entities.add({id:`cctv-${m.camera.id}-plane`,properties:{cctvCameraId:m.camera.id},show:!1,position:y.capCenter,orientation:n.model.planeOrientationFor(m.camera,y.capCenter),plane:{plane:new Cesium.Plane(Cesium.Cartesian3.UNIT_Z,0),dimensions:new Cesium.Cartesian2(C.halfW*2,C.halfH*2),material:b.planeMaterial,outline:!0,outlineColor:$F}}),b.planeEntity}function h(m){if(!e._viewer)return null;const b=document.createElement("canvas");b.width=Ji,b.height=eo;const C=b.getContext("2d",{alpha:!0}),y=n.model.normalizeFeedType(m.camera.feedType),v=n.model.isVideoFeedType(y)?"video":"image",M={mode:v,canvas:b,ctx:C,image:null,video:null,planeEntity:null,cameraId:String(m.camera.id),labelPosition:new Cesium.Cartesian3,overlayEntry:null,planeMaterial:null,buffers:null,bufferIndex:0,lastTextureSwapAt:0,lastImageRefreshAt:0,imageReady:!1,imageLoading:!1,imageStamp:0,drawnImageStamp:-1,lastFrameSignature:null,signatureCanvas:null,signatureCtx:null,lastPlaceholderPaintAt:0,canvasStamp:1,lastSwappedCanvasStamp:0};if(n.frames.paintProjectionPlaceholder(C,m.camera),v==="video"){const k=document.createElement("video");k.muted=!0,k.loop=!0,k.autoplay=!0,k.playsInline=!0,k.crossOrigin="anonymous",k.preload="auto",k.src=n.frames.mediaUrlFor(m.camera),k.addEventListener("canplay",()=>{k.play().catch(()=>{})}),M.video=k}else{const k=new Image;k.decoding="async",k.crossOrigin="anonymous",k.onload=()=>{M.imageLoading=!1,M.imageReady=!0,M.imageStamp=Date.now()},k.onerror=()=>{M.imageLoading=!1,M.imageReady=!1},M.image=k}const w=m.frustumGeometry||n.geometry.computeFrustumGeometry(m.camera,n.ground.groundAltFor(m),m.probeClampRangeM),E=m.frustumPositions||n.geometry.frustumCartesians(w);return M.planeMaterial=new Cesium.ImageMaterialProperty({image:v==="video"&&M.video?M.video:b,transparent:!0,color:Cesium.Color.WHITE.withAlpha(.95)}),u(m,M,w,E),M}function d(m){if(!m)return null;if(m.projection)return m.projection;const b=h(m);return m.projection=b,b&&e._projectionEntities.push(b),b}function f(m){m&&(m.video&&(m.video.pause(),m.video.removeAttribute("src"),m.video.load()),m.planeEntity&&e._viewer&&(e._viewer.entities.remove(m.planeEntity),m.planeEntity=null),e._projectionOverlayOwnerId===m.cameraId&&c(),m.overlayEntry=null,m.labelPosition=null,m.planeMaterial=null)}function p(){if(e._projectionRaf||!n.model.projectionLoopIsNeeded())return;o("cctv-projection");const m=()=>{var C;if(!e._viewer||!n.model.projectionLoopIsNeeded()){e._projectionRaf=0,r("cctv-projection");return}n.rendering.refreshCctvFocusStyles(performance.now());const b=n.selection.getActiveRecord();e._enabled&&e._showProjection&&b&&(d(b),(C=b.projection)!=null&&C.video&&b.projection.video.play().catch(()=>{}),b.projection&&(n.frames.drawProjectionFrame(b),n.frames.refreshProjectionTextures(b))),e._projectionRaf=requestAnimationFrame(m)};e._projectionRaf=requestAnimationFrame(m)}function g(){e._projectionRaf&&(cancelAnimationFrame(e._projectionRaf),e._projectionRaf=0),r("cctv-projection")}function _(m){var b;for(const C of e._records)(b=C.projection)!=null&&b.video&&(C.camera.id===m&&e._enabled&&e._showProjection?C.projection.video.play().catch(()=>{}):C.projection.video.pause())}return{createCctvProjectionOverlayEntry:s,updatePlanePlacement:a,clearProjectionOverlay:c,setPlaneVisible:l,createProjectionPlane:u,createProjectionRuntime:h,ensureProjectionRuntime:d,destroyProjectionRuntime:f,startProjectionLoop:p,stopProjectionLoop:g,pauseInactiveProjectionFeeds:_}}function QF({state:e,services:t,parts:n,source:i}){function o({activeCameraCardEnabled:f=!1}={}){var p,g,_;return e._activeCameraCardEnabled=f===!0,e._enabled&&a(),(_=(g=(p=e._viewer)==null?void 0:p.scene)==null?void 0:g.requestRender)==null||_.call(g),{activeCameraCardEnabled:e._activeCameraCardEnabled}}function r(f){let p=e._cardFrameSlots.get(f);return p||(p=CM(),e._cardFrameSlots.set(f,p)),p}function s(){if(!e._enabled||!e._viewer||e._viewer.isDestroyed()||!e._records.length){e._cctvOverlayHost.setEntries(ur,[],Bg);return}const f=e._viewer.scene,p=e._viewer.camera.positionCartographic,g=p?Cesium.Math.toDegrees(p.latitude):0,_=p?Cesium.Math.toDegrees(p.longitude):0,m=e._activeCameraId,b=Vo(e._viewer.camera),C=f.canvas.clientWidth||f.canvas.width||0,y=f.canvas.clientHeight||f.canvas.height||0,v=C*Og,M=y*Og,w=[],E=new Map;for(const F of e._records){const P=F.camera.id;if(P===m||!F.position)continue;let O=!1,D=NaN,$=NaN;if(b.isPointVisible(F.position)){const x=f.cartesianToCanvasCoordinates(F.position);x&&Number.isFinite(x.x)&&Number.isFinite(x.y)&&x.x>=-v&&x.x<=C+v&&x.y>=-M&&x.y<=y+M&&(O=!0,D=x.x,$=x.y,E.set(P,{sx:D,sy:$}))}w.push({id:P,distanceKm:n.model.haversineKm(g,_,F.camera.lat,F.camera.lon),inView:O,isVideo:n.model.isVideoFeedType(n.model.normalizeFeedType(F.camera.feedType)),sx:D,sy:$})}const{cardIds:k,budgets:T}=aF(w,{cameraHeightM:p==null?void 0:p.height,incumbentIds:e._cardIds,viewW:C,viewH:y}),I=e._geoLoading?Math.min(T.cardLimit,GF):T.cardLimit,R=$x(k.filter(F=>E.has(F)).slice(0,I).map((F,P)=>({id:F,...E.get(F),distanceKm:P})),{limit:I});m&&(e._cardIds.delete(m),e._cardGraceState.delete(m));const S=dF({selectedIds:R,builtIds:[...e._cardIds],graceState:e._cardGraceState,nowMs:Date.now(),cardLimit:T.cardLimit});e._cardIds=new Set(S.keepIds),e._cardGraceState=S.graceState;const A=new Set(e._cardIds);e._hoverCardId&&A.add(e._hoverCardId),e._activeCameraCardEnabled&&e._activeCameraId&&A.add(e._activeCameraId);const L=jx([...e._cardFrameSlots].map(([F,P])=>({id:F,stamp:P.stamp})),A);for(const F of L)e._cardFrameSlots.delete(F);a()}function a(){const f=[];let p=0;const g=(_,{pinned:m=!1,active:b=!1}={})=>{const C=e._recordById.get(_);C!=null&&C.position&&f.push(qx({id:_,position:C.position,gapPx:zF,title:C.camera.name,frameSlot:r(_),rank:p++,pinned:m,active:b}))};for(const _ of e._cardIds)g(_,{pinned:_===e._hoverCardId});e._hoverCardId&&!e._cardIds.has(e._hoverCardId)&&e._hoverCardId!==e._activeCameraId&&g(e._hoverCardId,{pinned:!0}),e._activeCameraCardEnabled&&e._activeCameraId&&g(e._activeCameraId,{active:!0}),e._cctvOverlayHost.setEntries(ur,f,Bg)}function c(f,p,g,{userGesture:_=!1}={}){if(typeof document<"u"&&document.hidden&&!_)return;const m=Date.now(),b=f.camera.id;if(e._cardFetchInFlightCount+=1,e._cardFetchPendingIds.add(b),e._cardLastFetchAt>0&&!_){const v=m-e._cardLastFetchAt;e._cardMinFetchSpacingMs=e._cardMinFetchSpacingMs==null?v:Math.min(e._cardMinFetchSpacingMs,v)}e._cardLastFetchAt=m,e._cardFetchCount+=1;const C=new Image;e._cardFetchImages.add(C);const y=v=>{var w,E,k;C.onload=null,C.onerror=null,e._cardFetchImages.delete(C)&&(e._cardFetchInFlightCount=Math.max(0,e._cardFetchInFlightCount-1),e._cardFetchPendingIds.delete(b));let M=null;if(v)try{const T=document.createElement("canvas");T.width=kx,T.height=Ax,T.getContext("2d").drawImage(C,0,0,T.width,T.height),M=T}catch{M=null}Object.assign(p,Ux(p,{ok:!!M,frame:M},Date.now())),(k=(E=(w=e._viewer)==null?void 0:w.scene)==null?void 0:E.requestRender)==null||k.call(E)};C.onload=()=>y(!0),C.onerror=()=>y(!1),C.src=n.frames.frameUrlFor(f.camera,g)}function l(){e._cardFetchTimer||(e._cardFetchTimer=setInterval(n.model.cardFrameTick,UF))}function u(){e._cardFetchTimer&&(clearInterval(e._cardFetchTimer),e._cardFetchTimer=0);for(const f of e._cardFetchImages)f.onload=null,f.onerror=null,f.removeAttribute("src");e._cardFetchImages.clear(),e._cardFetchPendingIds.clear(),e._cardFetchInFlightCount=0,e._cardFetchMode="steady"}function h(){u(),e._cctvOverlayHost.clearSource(ur),e._cctvOverlayHost.setVisible(ur,!1),n.hover.clearHoverCard(),e._cameraMoving=!1,e._cardIds=new Set,e._cardGraceState=new Map,e._cardFrameSlots=new Map,e._cardFetchCount=0,e._cardLastFetchAt=0,e._cardMinFetchSpacingMs=null}function d(){if(document.hidden){for(const f of e._cardFetchImages)f.onload=null,f.onerror=null,f.removeAttribute("src");e._cardFetchImages.clear(),e._cardFetchPendingIds.clear(),e._cardFetchInFlightCount=0}}return{handleVisibilityChange:d,setCctvCardPresentationOptions:o,ensureCardFrameSlot:r,refreshAmbientCards:s,pushAmbientCardEntries:a,fetchCardFrame:c,startCardFrameLoop:l,stopCardFrameLoop:u,teardownAmbientCards:h}}function ZF({state:e,services:t,parts:n,source:i}){const{focusPassIsNeeded:o,getFocusTarget:r}=t.focus;function s(S){return Cesium.Math.toRadians(S)}function a(S){let A=S%360;return A<0&&(A+=360),A}function c(S,A,L){return Math.max(A,Math.min(L,S))}function l(S){let A=S%360;return A>180&&(A-=360),A<=-180&&(A+=360),A}function u(S,A){return Math.abs(l(S-A))}function h(S){const A=String(S||"").trim().toLowerCase();return A?A==="mjpg"?"mjpeg":A==="jpeg"||A==="jpg"?"image":A==="video"?"mp4":A==="stream"?"hls":A==="png"||A==="gif"?"image":A:"image"}function d(S){return S==="mp4"||S==="hls"||S==="webm"}function f(S,A=NaN){const L=Number(S);return Number.isFinite(L)?L:A}function p(S){const A=String(S||"");let L=0;for(let F=0;F>>0;return a(L%16*22.5)}function g(S,A=.1){return Math.round(S/A)*A}function _(S,A){return S===!0?"on":S===!1?"off":S==="off"||S==="on"||S==="viewshed"?S:A}function m(S,A,L){const F=A/111320,P=Math.max(.15,Math.cos(s(S))),O=L/(111320*P);return{latOffset:F,lonOffset:O}}function b(){if(typeof window>"u")return null;try{return window.localStorage||null}catch{return null}}function C(S){var P;if(!S)return;S.basePose||(S.basePose={lat:f(S.lat,0),lon:f(S.lon,0),headingDeg:a(f(S.headingDeg,0)),pitchDeg:c(f(S.pitchDeg,-17),-70,10),fovDeg:c(f(S.fovDeg,74),20,130),rangeM:c(f(S.rangeM,700),120,5e3),mountHeightM:c(f(S.mountHeightM,24),2,240)});const A=n.calibration.normalizeCalibration(S.calibration||nc);S.calibration=A;const L=S.basePose,F=m(L.lat,A.offsetNorthM,A.offsetEastM);S.lat=L.lat+F.latOffset,S.lon=L.lon+F.lonOffset,S.headingDeg=a(L.headingDeg+A.headingDeg),S.pitchDeg=c(L.pitchDeg+A.pitchDeg,-70,10),S.fovDeg=c(L.fovDeg+A.fovDeg,20,130),S.rangeM=c(L.rangeM*A.rangeScale,120,5e3),S.mountHeightM=c(L.mountHeightM+A.heightM,2,240),S.intrinsics={fovDeg:S.fovDeg,principalPoint:[.5,.5]},S.extrinsics={headingDeg:S.headingDeg,pitchDeg:S.pitchDeg,rollDeg:0,heightM:S.mountHeightM},S.anchor={lat:S.lat,lon:S.lon,elevM:f(S.groundElevationM,0),targetLatLon:((P=S.anchor)==null?void 0:P.targetLatLon)||null}}function y(S,A,L,F){const P=F/6371e3,O=s(L),D=s(S),$=s(A),x=Math.sin(D)*Math.cos(P)+Math.cos(D)*Math.sin(P)*Math.cos(O),N=Math.asin(x),G=Math.sin(O)*Math.sin(P)*Math.cos(D),W=Math.cos(P)-Math.sin(D)*x,V=$+Math.atan2(G,W);return{lat:Cesium.Math.toDegrees(N),lon:Cesium.Math.toDegrees(V)}}function v(S,A,L,F){const P=s(L-S),O=s(F-A),D=Math.sin(P/2)**2+Math.cos(s(S))*Math.cos(s(L))*Math.sin(O/2)**2;return 6371*2*Math.atan2(Math.sqrt(D),Math.sqrt(1-D))}function M(S,A){const L=s(c(A,12,170));return .5*S*S*L/1e6}function w(){var D,$;const S=($=(D=e._viewer)==null?void 0:D.camera)==null?void 0:$.positionCartographic;if(!S)return"none";const A=Cesium.Math.toDegrees(S.latitude),L=Cesium.Math.toDegrees(S.longitude),F=S.height||0,P=F<1500?"street":F<12e3?"city":F<75e3?"regional":"global",O=P==="street"?.045:P==="city"?.24:P==="regional"?1:4.5;return`${P}:${Math.floor(A/O)}:${Math.floor(L/O)}`}function E(){var S,A,L,F,P;if(!e._activeTileset||(A=(S=e._activeTileset).isDestroyed)!=null&&A.call(S)){e._activeTileset=null;const O=(F=(L=e._viewer)==null?void 0:L.scene)==null?void 0:F.primitives;if(O&&typeof O.get=="function")for(let D=0;D{const x=e._recordById.get($);if(!x)return;const N=n.cards.ensureCardFrameSlot($);if(e._cardFetchPendingIds.has($)){N.stamp>0||(F=!0);return}const G=vM(x.camera);if(yM(N,G,S)){if(!(N.stamp>0)){F=!0,A||(A={record:x,slot:N,refreshMs:G});return}(!L||N.stamp0?S-e._cardLastFetchAt:1/0});if(e._cardFetchMode=O.mode,!O.launch)return;const D=A||L;D&&n.cards.fetchCardFrame(D.record,D.slot,D.refreshMs)}function R(S,A,L){return S!==A||(L==null?void 0:L.activationDone)!==!0}return{toRad:s,normalizeHeading:a,clamp:c,normalizeSignedAngle:l,angularDeltaAbs:u,normalizeFeedType:h,isVideoFeedType:d,safeNumber:f,headingFromId:p,quantize:g,normalizeCoverageMode:_,offsetDegrees:m,safeWindowLocalStorage:b,ensureCameraPose:C,projectPoint:y,haversineKm:v,sectorAreaKm2:M,currentViewContext:w,projectionTilesReady:E,planeOrientationFor:k,projectionLoopIsNeeded:T,cardFrameTick:I,cctvRecordNeedsActivation:R}}const JF=6371e3,eS=16/9,Ss=Object.freeze(["bl","bm","br","ml","mc","mr","tl","tm","tr"]),Ns=e=>e*Math.PI/180,mh=e=>e*180/Math.PI;function $u(e,t,n,i){const o=Ns(n),r=Ns(e),s=Ns(t),a=i/JF,c=Math.asin(Math.sin(r)*Math.cos(a)+Math.cos(r)*Math.sin(a)*Math.cos(o)),l=s+Math.atan2(Math.sin(o)*Math.sin(a)*Math.cos(r),Math.cos(a)-Math.sin(r)*Math.sin(c));return{lat:mh(c),lon:mh(l)}}function MM(e){const t=Math.max(1,Number(e.rangeM)||1),n=Ns(Math.max(-89,Math.min(89,Number(e.pitchDeg)||0))),i=Ns(Math.max(8,Math.min(160,Number(e.fovDeg)||74))),o=t*Math.tan(i/2),r=2*Math.atan(Math.tan(i/2)/eS),s=t*Math.tan(r/2);return{R:t,pitch:n,halfW:o,halfH:s,horiz:t*Math.cos(n),vert:t*Math.sin(n),upVert:Math.cos(n)*s,upHoriz:-Math.sin(n)*s,vFovDeg:mh(r)}}function tS(e){const t=MM(e),n=Number(e.headingDeg)||0,i=$u(e.lat,e.lon,n,t.horiz),o={},r={b:-1,m:0,t:1},s={l:-1,m:0,c:0,r:1};for(const a of Ss){const c=r[a[0]],l=s[a[1]],u=$u(i.lat,i.lon,n+90,l*t.halfW),h=$u(u.lat,u.lon,n,c*t.upHoriz);o[a]={lat:h.lat,lon:h.lon,row:c,col:l}}return{mount:{lat:e.lat,lon:e.lon},capCenter:i,supports:o}}function nS(e,t,n){return e+t*n.upVert}function Vg(e,t,n,i,o){let r=0,s=null;const a={b:-1,m:0,t:1};for(const c of Ss){const l=n?n[c]:void 0,u=typeof l=="number"&&Number.isFinite(l)?l:i;if(!Number.isFinite(u))continue;const h=nS(e,a[c[0]],t),d=u+o-h;d>r&&(r=d,s=c)}return{liftM:r,limitingKey:s}}function ic(e){const t=[Number(e.lat).toFixed(6),Number(e.lon).toFixed(6),Number(e.headingDeg).toFixed(1),Number(e.pitchDeg).toFixed(1),Number(e.fovDeg).toFixed(1),Number(e.rangeM).toFixed(1),Number(e.mountHeightM).toFixed(1)].join("|");let n=2166136261;for(let i=0;i>>0;return`p1-${n.toString(36)}`}const iS=6e4;function oS({state:e,services:t,parts:n,source:i}){const{resolveGroundFloorCells:o}=t.ground,{resolveEllipsoidalGround:r}=t.terrain;function s(m){return m===!1?"google-3d":"terrain-globe"}function a(){var m,b,C;return s((C=(b=(m=e._viewer)==null?void 0:m.scene)==null?void 0:b.globe)==null?void 0:C.show)}function c(m){var C,y;const b=(C=m==null?void 0:m.groundPrior)==null?void 0:C.ellipsoid;return Number.isFinite(b)?b:Number((y=m==null?void 0:m.camera)==null?void 0:y.groundElevationM)||0}function l(m,b=a()){var C;return((C=m==null?void 0:m.groundResolved)==null?void 0:C[b])===!0}function u(m,b=a()){var y;const C=(y=m==null?void 0:m.groundSamples)==null?void 0:y[b];return Number.isFinite(C)?C:c(m)}function h(m){m&&(m.groundResolved[a()]=!1)}function d(m){if(!(m!=null&&m.camera))return;m.calibrationGroundResolveCount=(m.calibrationGroundResolveCount||0)+1;const b=(m.calibrationGroundRevision||0)+1;m.calibrationGroundRevision=b;const C={lat:m.camera.lat,lon:m.camera.lon};h(m),n.geometry.updateRecordGeometry(m),!l(m)&&o([C]).then(()=>{e._recordById.get(m.camera.id)===m&&m.calibrationGroundRevision===b&&(m.camera.lat!==C.lat||m.camera.lon!==C.lon||(h(m),n.geometry.updateRecordGeometry(m),n.rendering.refreshCoverageStyles(),n.presentation.notifyListeners()))})}async function f(m){try{const b=m.map(C=>{const y=Number(C.groundElevationM);return{lat:C.lat,lon:C.lon,...Number.isFinite(y)?{sourceOrthometricM:y}:{}}});return await r(b)}catch(b){return console.warn("[Data:CCTV] ground-prior batch failed (keeping catalog fallbacks):",(b==null?void 0:b.message)||b),null}}function p(m,b){if(!Array.isArray(m)||!Array.isArray(b))return;let C=0;for(let y=0;y({lat:M[R].lat,lon:M[R].lon}));let E=null;try{E=await r(w)}catch{E=null}if(!Array.isArray(E)||m.footprintRevision!==v||e._recordById.get(m.camera.id)!==m||ic(n.geometry.footprintPose(m))!==C)return;const k={};let T=0;E.forEach((R,S)=>{Number.isFinite(R==null?void 0:R.ellipsoid)&&(k[Ss[S]]=R.ellipsoid,R.source==="reearth"&&(T+=1))});const I=T{n[r*3]=o.x,n[r*3+1]=o.y,n[r*3+2]=o.z});const i=new Uint16Array([0,1,2,0,2,3,0,3,4,0,4,1,1,2,3,1,3,4]);return{positions:n,indices:i}}function fS(e,t){const{positions:n,indices:i}=hS(e),o=new Cesium.Geometry({attributes:{position:new Cesium.GeometryAttribute({componentDatatype:Cesium.ComponentDatatype.DOUBLE,componentsPerAttribute:3,values:n})},indices:i,primitiveType:Cesium.PrimitiveType.TRIANGLES,boundingSphere:Cesium.BoundingSphere.fromVertices(Array.from(n))});return new Cesium.Primitive({geometryInstances:new Cesium.GeometryInstance({geometry:o,attributes:{color:Cesium.ColorGeometryInstanceAttribute.fromColor(t)}}),appearance:new Cesium.PerInstanceColorAppearance({flat:!0,translucent:!0,renderState:{cull:{enabled:!1}}}),asynchronous:!1,allowPicking:!1})}function mS({state:e,services:t,parts:n,source:i}){const{warmGroundFloor:o,cachedGroundFloor:r}=t.ground,{sampleMeshFloorCells:s}=t.mesh;function a(A){if(l(A))return A.camera.groundHeights.supports||null;const L=A==null?void 0:A.footprintGround;return L&&L.poseHash===ic(c(A))&&L.supports||null}function c(A){const L=A.camera,F=n.model.safeNumber(A.probeClampRangeM,NaN),P=Number.isFinite(F)&&F>0?Math.min(L.rangeM,F):L.rangeM;return{lat:L.lat,lon:L.lon,headingDeg:L.headingDeg,pitchDeg:L.pitchDeg,fovDeg:L.fovDeg,rangeM:P,mountHeightM:L.mountHeightM}}function l(A){var F;const L=(F=A==null?void 0:A.camera)==null?void 0:F.groundHeights;return!L||typeof L!="object"||n.ground.currentSurfaceRegime()!=="google-3d"?!1:Number.isFinite(L.mountGroundM)&&L.poseHash===ic(c(A))}function u(A,L,F=null,P=null){const O=n.model.safeNumber(L,0),D=Math.max(1,n.model.safeNumber(A.rangeM,700)),$=n.model.safeNumber(F,NaN),x=Number.isFinite($)&&$>0?Math.min(D,$):D,N=n.model.clamp(n.model.safeNumber(A.pitchDeg,-17),-89,89),G=n.model.clamp(n.model.safeNumber(A.fovDeg,74),8,160),W=n.model.safeNumber(A.headingDeg,0),V=O+n.model.safeNumber(A.mountHeightM,24),H=MM({rangeM:x,pitchDeg:N,fovDeg:G}),B=n.model.projectPoint(A.lat,A.lon,W,H.horiz),q=V+H.vert,z=n.model.projectPoint(B.lat,B.lon,W-90,H.halfW),j=n.model.projectPoint(B.lat,B.lon,W+90,H.halfW),ne=Vg(q,H,null,O,Sg),ee=Vg(q,H,P,O,Sg),re=Math.max(0,ee.liftM-ne.liftM),se=ne.liftM+Math.min(Ng,re),me=re>0?ee.limitingKey:ne.limitingKey,be=q+se,J=(ae,oe)=>{const le=n.model.projectPoint(ae.lat,ae.lon,W,oe*H.upHoriz);return{lat:le.lat,lon:le.lon,alt:be+oe*H.upVert}},Z=J(B,1);return{rangeM:x,vFovDeg:H.vFovDeg,halfW:H.halfW,halfH:H.halfH,mount:{lat:A.lat,lon:A.lon,alt:V},capCenter:{lat:B.lat,lon:B.lon,alt:be},corners:{tl:J(z,1),tr:J(j,1),br:J(j,-1),bl:J(z,-1)},topCenter:Z,groundAltM:O,liftM:se,liftLimitedBy:me,liftCapped:re>Ng,footprintMeasured:!!P}}function h(A,L){const F=Number(A),P=Number(L);return!Number.isFinite(F)||F<=0||!Number.isFinite(P)||P<=0||P>=F?null:Math.max(LF,P-RF)}function d(A){const L=F=>Cesium.Cartesian3.fromDegrees(F.lon,F.lat,F.alt);return{mount:L(A.mount),capCenter:L(A.capCenter),tl:L(A.corners.tl),tr:L(A.corners.tr),br:L(A.corners.br),bl:L(A.corners.bl),label:Cesium.Cartesian3.fromDegrees(A.topCenter.lon,A.topCenter.lat,A.topCenter.alt+1.2)}}function f(A,L){const F=n.model.toRad(A.headingDeg),P=n.model.toRad(A.pitchDeg),O=Cesium.Transforms.eastNorthUpToFixedFrame(L),D=Cesium.Matrix4.getMatrix3(O,new Cesium.Matrix3),$=new Cesium.Cartesian3(Math.sin(F)*Math.cos(P),Math.cos(F)*Math.cos(P),Math.sin(P)),x=new Cesium.Cartesian3(-Math.sin(P)*Math.sin(F),-Math.sin(P)*Math.cos(F),Math.cos(P));return{dir:Cesium.Matrix3.multiplyByVector(D,$,new Cesium.Cartesian3),up:Cesium.Matrix3.multiplyByVector(D,x,new Cesium.Cartesian3)}}function p(A,L){var O,D;const F=u(A.camera,L,A.probeClampRangeM,a(A)),P=d(F);A.frustumGeometry=F,A.frustumPositions=P,A.position=P.mount,A.camera.absoluteHeightM=F.mount.alt,A.billboard&&(A.billboard.position=P.mount),((O=A.coverageEntities)==null?void 0:O.length)>=5&&(A.coverageEntities[0].polyline.positions=[P.mount,P.tl],A.coverageEntities[1].polyline.positions=[P.mount,P.tr],A.coverageEntities[2].polyline.positions=[P.mount,P.br],A.coverageEntities[3].polyline.positions=[P.mount,P.bl],A.coverageEntities[4].polyline.positions=[P.tl,P.tr,P.br,P.bl,P.tl]),A.viewshedPrimitive&&b(A,A.camera.id===e._activeCameraId),n.projection.updatePlanePlacement(A),(D=e._gizmo)!=null&&D.isEnabled()&&A.camera.id===e._activeCameraId&&e._gizmo.refresh()}function g(A,L={}){var x,N,G,W;const F=L.sampleGround!==!1,P=n.ground.currentSurfaceRegime(),O={lat:A.camera.lat,lon:A.camera.lon};if(o([O]),P==="terrain-globe"){const V=r(O.lat,O.lon),H=Number.isFinite(V)?V:n.ground.groundPriorAltFor(A);A.groundSamples["terrain-globe"]=H,A.groundResolved["terrain-globe"]=!0,p(A,H);return}if(l(A)){const V=A.camera.groundHeights.mountGroundM;A.groundSamples["google-3d"]=V,A.groundResolved["google-3d"]=!0,p(A,V);return}if(F&&n.model.projectionTilesReady()){A.groundMeshSampleRequestCount=(A.groundMeshSampleRequestCount||0)+1;const V=(N=(x=e._viewer)==null?void 0:x.camera)==null?void 0:N.positionCartographic,H=[...A.coverageEntities||[]];A.billboard&&H.push(A.billboard),(G=A.projection)!=null&&G.planeEntity&&H.push(A.projection.planeEntity),s((W=e._viewer)==null?void 0:W.scene,[O],{excludeObjects:H.filter(Boolean),viewerLat:V?Cesium.Math.toDegrees(V.latitude):void 0,viewerLon:V?Cesium.Math.toDegrees(V.longitude):void 0})}const D=r(O.lat,O.lon),$=Number.isFinite(D)?D:n.ground.groundAltFor(A,"google-3d");p(A,$),A.groundResolved["google-3d"]=Number.isFinite(D),Number.isFinite(D)&&(A.groundSamples["google-3d"]=$)}function _(A){if(!e._records.length)return new Set;if(!A)return new Set;const L=e._records.map(D=>D===A?{record:D,distKm:-1}:{record:D,distKm:n.model.haversineKm(A.camera.lat,A.camera.lon,D.camera.lat,D.camera.lon)});L.sort((D,$)=>D.distKm-$.distKm);const F=L.filter(D=>D.distKm<=CF||D.distKm===-1),P=L,O=(F.length>=xg?F:P).slice(0,xg).map(D=>D.record.camera.id);return new Set(O)}function m(A){A&&(A.viewshedPrimitive&&e._viewer&&e._viewer.scene.primitives.remove(A.viewshedPrimitive),A.viewshedPrimitive=null)}function b(A,L){if(m(A),!e._viewer||!(A!=null&&A.frustumPositions)||!A.viewshedColors)return;const F=L?A.viewshedColors.fillActive:A.viewshedColors.fill,P=fS(A.frustumPositions,F);P._gevViewshed=A.camera.id,A.viewshedPrimitive=e._viewer.scene.primitives.add(P),A.viewshedActiveTint=!!L}function C(A){if(!A)return 0;let L=0;for(const F of e._records){if(F===A)continue;const P=n.model.haversineKm(A.camera.lat,A.camera.lon,F.camera.lat,F.camera.lon),O=(A.camera.rangeM+F.camera.rangeM)/1e3*.92;P<=O&&L++}return L}function y(A){var O;A.probeClampRangeM=null;const L=(O=e._viewer)==null?void 0:O.scene;if(!L||typeof L.pickFromRay!="function")return;const F=A.camera,P=n.calibration.normalizeCalibration(F.calibration).rangeScale;if(!(Math.abs(P-1)>1e-4))try{const D=n.ground.groundAltFor(A)+F.mountHeightM,$=Cesium.Cartesian3.fromDegrees(F.lon,F.lat,D),{dir:x}=f(F,$),N=[e._billboards,...e._coverageEntities];for(const V of e._projectionEntities)V!=null&&V.planeEntity&&N.push(V.planeEntity);const G=L.pickFromRay(new Cesium.Ray($,x),N);if(!(G!=null&&G.position))return;const W=Cesium.Cartesian3.distance($,G.position);A.probeClampRangeM=h(F.rangeM,W)}catch{}}function v(A,L){return!A||!Number.isFinite(A.probeClampRangeM)?!1:(A.probeClampRangeM=null,L==null||L(A),!0)}function M(A){const{camera:L}=A;let F=A.frustumGeometry,P=A.frustumPositions;(!F||!P)&&(F=u(L,n.ground.groundPriorAltFor(A),A.probeClampRangeM),P=d(F),A.frustumGeometry=F,A.frustumPositions=P,A.position=P.mount);const O=($,x)=>e._viewer.entities.add({id:`cctv-${L.id}-${$}`,properties:{cctvCameraId:L.id},polyline:{positions:x,width:1.2,material:SF}}),D=[O("ray-tl",[P.mount,P.tl]),O("ray-tr",[P.mount,P.tr]),O("ray-br",[P.mount,P.br]),O("ray-bl",[P.mount,P.bl]),O("cap",[P.tl,P.tr,P.br,P.bl,P.tl])];return D[0]._coverageRole="edge",D[1]._coverageRole="edge",D[2]._coverageRole="edge",D[3]._coverageRole="edge",D[4]._coverageRole="cap",D}function w(A,L=()=>!0,F){var O;const P=[];if(typeof F!="function")return P;for(const D of Array.isArray(A)?A:[]){if(!D||(O=D.coverageEntities)!=null&&O.length||!L(D))continue;const $=F(D);D.coverageEntities=Array.isArray($)?$.filter(Boolean):[],P.push(...D.coverageEntities)}return P}function E(A,L){return w([A],()=>!0,L)}function k(A,L,F){const P=L instanceof Set?L:new Set(L||[]);return w(A,O=>{var D;return P.has((D=O.camera)==null?void 0:D.id)},F)}function T(A){return e._coverageEntities.push(...A),A}function I(A){return T(E(A,M))}function R(A,L){return T(k(A,L,M))}function S(){if(e._viewer){for(const A of e._coverageEntities)e._viewer.entities.remove(A);e._coverageEntities=[];for(const A of e._records)m(A);for(const A of e._projectionEntities)n.projection.destroyProjectionRuntime(A);e._projectionEntities=[]}}return{computeFrustumGeometry:u,hasShippedFootprint:l,footprintPose:c,activationProbeClampRange:h,frustumCartesians:d,frustumFrameEcef:f,applyFrustumGeometry:p,updateRecordGeometry:g,buildCoverageVisibleSet:_,destroyViewshedVolume:m,rebuildViewshedVolume:b,coverageNeighborCount:C,runActivationObstructionProbe:y,clearProbeClampOnDeactivation:v,buildCoverageEntities:M,materializeCctvCoverageEntities:w,materializeCctvActiveCoverageEntities:E,materializeCctvVisibleCoverageEntities:k,registerCoverageEntities:T,ensureActiveCoverageEntities:I,ensureVisibleCoverageEntities:R,destroyCoverageEntities:S}}function pS({state:e,services:t,parts:n,source:i}){const{CITY_POIS:o}=t.locations;function r(){var u;const l=[];for(const h of FF){const d=o[h.cityId],f=(u=d==null?void 0:d.pois)==null?void 0:u[h.poiIndex];if(!d||!f)continue;const{latOffset:p,lonOffset:g}=n.model.offsetDegrees(f.lat,h.offsetNorthM||0,h.offsetEastM||0),_={id:h.id,name:h.label,cityId:h.cityId,city:d.name,provider:"OSM Camera Grid",sourceKind:"seed",feedType:"image",feedConfigured:!1,headingConfidence:"medium",lat:f.lat+p,lon:f.lon+g,headingDeg:n.model.normalizeHeading(h.headingDeg??f.heading??0),fovDeg:n.model.clamp(h.fovDeg??70,20,120),rangeM:n.model.clamp(h.rangeM??700,260,1800),mountHeightM:n.model.clamp(h.elevationM??22,8,80),groundElevationM:Number(d.groundElevation)||0,absoluteHeightM:(Number(d.groundElevation)||0)+n.model.clamp(h.elevationM??22,8,80),pitchDeg:n.model.clamp(h.pitchDeg??-17,-40,-4)};n.model.ensureCameraPose(_),l.push(_)}return l}function s(l){const u=String(l||"").trim().toLowerCase();if(!u)return null;for(const[h,d]of Object.entries(o))if(d.name.toLowerCase()===u)return h;for(const[h,d]of Object.entries(o))if(d.name.toLowerCase().includes(u)||u.includes(d.name.toLowerCase()))return h;return null}async function a(){var l;try{const u=(l=e._sourceAbort)==null?void 0:l.signal,h=await i.getCatalog({signal:u});return u==null||u.throwIfAborted(),Array.isArray(h==null?void 0:h.sources)?h.sources:[]}catch(u){if((u==null?void 0:u.name)==="AbortError")throw u;return[]}}function c(l){const u=Array.isArray(l)?l:[];if(!u.length)return[];const h=r(),d=new Map(h.map(p=>[p.id,p])),f=[];for(const p of u){if(!p||typeof p!="object")continue;const g=String(p.id||"").trim();if(!g)continue;const _=d.get(g),m=String(p.cityId||"").trim()||s(p.city)||(_==null?void 0:_.cityId)||"",b=m&&o[m]?o[m]:null,C=n.model.safeNumber(p.lat,(_==null?void 0:_.lat)??NaN),y=n.model.safeNumber(p.lon,(_==null?void 0:_.lon)??NaN);if(!Number.isFinite(C)||!Number.isFinite(y))continue;const v=n.model.safeNumber(p.headingDeg,NaN),M=n.model.normalizeHeading(Number.isFinite(v)?v:(_==null?void 0:_.headingDeg)??n.model.headingFromId(g)),w=n.model.clamp(n.model.safeNumber(p.fovDeg,(_==null?void 0:_.fovDeg)??74),20,125),E=n.model.clamp(n.model.safeNumber(p.rangeM,(_==null?void 0:_.rangeM)??700),120,2200),k=n.model.clamp(n.model.safeNumber(p.mountHeightM,(_==null?void 0:_.mountHeightM)??24),6,120),T=n.model.clamp(n.model.safeNumber(p.pitchDeg,(_==null?void 0:_.pitchDeg)??-17),-55,-2),I=n.model.safeNumber(p.groundElevationM,(b==null?void 0:b.groundElevation)??(_==null?void 0:_.groundElevationM)??0),R=n.model.normalizeFeedType(p.feedType||p.type||"image"),S=String(p.headingConfidence||(_?"high":"low")).toLowerCase(),A=p.poseSource==="curated"?"curated":(_==null?void 0:_.poseSource)||null,L={id:g,name:String(p.name||(_==null?void 0:_.name)||g),cityId:m,city:String(p.city||(b==null?void 0:b.name)||(_==null?void 0:_.city)||"Global"),provider:String(p.provider||(_==null?void 0:_.provider)||"Configured CCTV Source"),sourceKind:String(p.sourceKind||p.kind||(p.url?"configured":"seed")).toLowerCase(),feedType:R,feedConfigured:typeof p.url=="string"&&!!p.url.trim(),lat:C,lon:y,headingDeg:M,headingConfidence:S,fovDeg:w,rangeM:E,mountHeightM:k,groundElevationM:I,absoluteHeightM:I+k,pitchDeg:T,license:String(p.license||p.licenseNote||""),credit:String(p.credit||""),code:String(p.code||""),groundHeights:p.groundHeights&&typeof p.groundHeights=="object"?p.groundHeights:null,poseSource:A};n.model.ensureCameraPose(L),f.push(L)}return f}return{seedCatalog:r,cityIdByName:s,loadCameraSources:a,buildCatalogFromSources:c}}function gS({state:e,services:t,parts:n,source:i}){function o(p){if(!p||typeof p.length!="number"||p.length<4)return null;let g=2166136261;for(let _=0;_>>0}function r(p){const g=p==null?void 0:p.image;if(!g)return null;if(!p.signatureCtx){const m=document.createElement("canvas");m.width=Oa,m.height=Ba,p.signatureCanvas=m,p.signatureCtx=m.getContext("2d",{willReadFrequently:!0})}const _=p.signatureCtx;if(!_)return null;try{return _.clearRect(0,0,Oa,Ba),_.drawImage(g,0,0,Oa,Ba),o(_.getImageData(0,0,Oa,Ba).data)}catch{return null}}function s(p){if(!(p!=null&&p.canvas))return null;p.buffers||(p.buffers=[0,1].map(()=>{const m=document.createElement("canvas");return m.width=Ji,m.height=eo,m}),p.bufferIndex=0),p.bufferIndex=(p.bufferIndex+1)%2;const g=p.buffers[p.bufferIndex],_=g.getContext("2d");return _?(_.clearRect(0,0,g.width,g.height),_.drawImage(p.canvas,0,0),g):null}function a(p){var C;const g=p==null?void 0:p.projection;if(!g||g.mode==="video")return;const _=Date.now();if(_-n.model.safeNumber(g.lastTextureSwapAt,0)=2&&m.videoWidth>0&&m.videoHeight>0){g.ctx.clearRect(0,0,Ji,eo),g.ctx.drawImage(m,0,0,Ji,eo),g.canvasStamp=(g.canvasStamp||0)+1;return}d(p,g,_);return}if(h(p),g.image&&g.imageReady){if(g.drawnImageStamp!==g.imageStamp){const m=r(g);if(g.drawnImageStamp=g.imageStamp,m!==null&&m===g.lastFrameSignature)return;g.lastFrameSignature=m,g.ctx.clearRect(0,0,Ji,eo),g.ctx.drawImage(g.image,0,0,Ji,eo),g.canvasStamp=(g.canvasStamp||0)+1,g.lastPlaceholderPaintAt=0}return}g.drawnImageStamp===-1&&d(p,g,_)}return{frameSignatureFromPixels:o,projectionFrameSignature:r,paintNextProjectionBuffer:s,refreshProjectionTextures:a,frameUrlFor:c,mediaUrlFor:l,paintProjectionPlaceholder:u,refreshProjectionImage:h,paintPlaceholderThrottled:d,drawProjectionFrame:f}}function _S({state:e,services:t,parts:n,source:i}){const{focusNowMs:o,getFocusTarget:r,focusPassIsNeeded:s,advanceSpriteFocus:a,focusAlphaNeedsWrite:c}=t.focus;function l(g){g=o(g);const _=r();if(!e._enabled||!e._viewer||!s(_,e._activeFocusStyleCount)||g-e._lastFocusStyleAt<80)return;e._lastFocusStyleAt=g;const m=e._viewer.scene,b=e._viewer.camera,C=u({records:e._records,target:_,previousActiveCount:e._activeFocusStyleCount,nowMs:g,screenPositionFor:y=>Cesium.SceneTransforms.worldToWindowCoordinates(m,y,e._scratchFocusScreen),cameraDistanceFor:y=>Cesium.Cartesian3.distance(b.positionWC,y),baseColorFor:y=>y.camera.id===e._activeCameraId?Dg:fh});e._activeFocusStyleCount=C.activeCount}function u({records:g,target:_,previousActiveCount:m=0,nowMs:b,screenPositionFor:C,cameraDistanceFor:y,baseColorFor:v,params:M}){var T;if(!s(_,m))return{writes:0,transitioning:!1,activeCount:0,ran:!1};let w=0,E=!1,k=0;for(const I of g||[]){const R=I.billboard;if(!R)continue;const S=R.position,A=a(R,{screenPosition:R.show===!1||!S?null:C(S),cameraDistance:S?y(S):Number.NaN,nowMs:b,target:_,params:M,spriteHalfWidthPx:(R.width||24)*(R.scale||1)*.5,spriteHalfHeightPx:(R.height||24)*(R.scale||1)*.5});E||(E=A.transitioning),A.active&&(k+=1);const L=v(I),F=L.alpha*A.factor;c((T=R.color)==null?void 0:T.alpha,F,M)&&(R.color=L.withAlpha(F),w+=1)}return{writes:w,transitioning:E,activeCount:k,ran:!0}}function h(){if(!e._viewer||e._viewer.isDestroyed()||!e._records.length)return;const g=Vo(e._viewer.camera);for(const _ of e._records){const m=_.billboard;if(!m)continue;const b=g.isPointVisible(m.position);m.show!==b&&(m.show=b)}}function d(g,_,m=null){var b,C;for(const y of Array.isArray(g)?g:[]){y&&(y.probeClampRangeM=null,((b=y.camera)==null?void 0:b.id)===m&&(y.activationDone=!1));for(const v of(y==null?void 0:y.coverageEntities)||[])v.show=!1;y!=null&&y.viewshedPrimitive&&(_==null||_(y)),(C=y==null?void 0:y.projection)!=null&&C.planeEntity&&(y.projection.planeEntity.show=!1)}}function f(){d(e._records,n.geometry.destroyViewshedVolume,e._activeCameraId),n.projection.clearProjectionOverlay(),e._billboards&&(e._billboards.show=!1),n.projection.pauseInactiveProjectionFeeds(null)}function p(){const g=n.selection.getActiveRecord();n.geometry.ensureActiveCoverageEntities(g);const _=(g==null?void 0:g.camera.id)||null,m=n.geometry.buildCoverageVisibleSet(g),b=e._coverageMode!=="off",C=e._coverageMode==="viewshed";b&&n.geometry.ensureVisibleCoverageEntities(e._records,m);for(const y of e._records){const v=y.camera.id===_;y.billboard&&(y.billboard.color=v?Dg:fh,y.billboard.scale=v?1.25:1),e._enabled&&e._showProjection&&v&&n.projection.ensureProjectionRuntime(y);const M=!!(e._enabled&&e._showProjection&&v),w=m.has(y.camera.id);for(const k of y.coverageEntities||[]){if(k.show=!!(e._enabled&&(b&&w||M)),!k.polyline)continue;const T=C?y.viewshedColors:null;k._coverageRole==="cap"?(k.polyline.material=T?v?T.lineActive:T.line:v?BF:NF,k.polyline.width=v?2.2:1,k.polyline.depthFailMaterial=M?T?T.line.withAlpha(.26):HF:void 0):(k.polyline.material=T?v?T.lineActive:T.line.withAlpha(.6):v?OF:DF,k.polyline.width=v?1.8:.9,k.polyline.depthFailMaterial=M?T?T.line.withAlpha(.18):VF:void 0)}!!(e._enabled&&C&&w&&y.frustumPositions)?(!y.viewshedPrimitive||y.viewshedActiveTint!==v)&&n.geometry.rebuildViewshedVolume(y,v):y.viewshedPrimitive&&n.geometry.destroyViewshedVolume(y),y.projection&&n.projection.setPlaneVisible(y.projection,M)}e._billboards&&(e._billboards.show=!!e._enabled),n.projection.pauseInactiveProjectionFeeds(_)}return{refreshCctvFocusStyles:l,applyCctvFocusDeemphasis:u,refreshHorizonCulling:h,hideCctvRecordVisuals:d,hideCctvVisuals:f,refreshCoverageStyles:p}}function bS({state:e,services:t,parts:n,source:i}){function o(f=!0){e._geoQueueTimer&&(clearTimeout(e._geoQueueTimer),e._geoQueueTimer=0),e._geoQueue=[],e._geoProgressNotifier=null,f&&(e._geoLoading=!1,e._geoLoadTotal=0,e._geoLoadDone=0)}function r(f,p={}){const g=typeof p.now=="function"?p.now:Date.now,_=Number.isFinite(p.intervalMs)?Math.max(0,p.intervalMs):EF,m=Number.isFinite(p.batchLimit)?Math.max(1,Math.floor(p.batchLimit)):TF;let b=g(),C=0;return{progress(){C+=1;const y=g();return y-b<_&&C{var p;return{trackedEntity:e._viewer.trackedEntity,cockpitActive:typeof document<"u"&&((p=document.body)==null?void 0:p.classList.contains("cockpit-mode"))}},visit:p=>{try{n.geometry.updateRecordGeometry(p)}catch(g){console.warn("[Data:CCTV] geometry refresh error:",(g==null?void 0:g.message)||g)}e._geoLoading&&e._geoLoadDone{var p;return(p=e._geoProgressNotifier)==null?void 0:p.progress()},complete:()=>{var g;const p=e._geoLoading;e._geoLoading=!1,p&&(e._geoLoadDone=e._geoLoadTotal,e._enabled&&(n.rendering.refreshCoverageStyles(),n.cards.refreshAmbientCards())),(g=e._geoProgressNotifier)==null||g.finish(),e._geoProgressNotifier=null}});if(f.hasMore){e._geoQueueTimer=setTimeout(u,f.delayMs);return}}function h(f){for(const p of f)e._geoQueue.includes(p)||e._geoQueue.push(p);!e._geoQueueTimer&&e._geoQueue.length&&(e._geoProgressNotifier=r(n.presentation.notifyListeners),e._geoQueueTimer=setTimeout(u,0))}function d(){var b,C;if(o(),e._tilesReadyReenqueued=!1,!e._records.length)return;const f=n.selection.getActiveRecord(),p=(C=(b=e._viewer)==null?void 0:b.camera)==null?void 0:C.positionCartographic,g=p?Cesium.Math.toDegrees(p.latitude):(f==null?void 0:f.camera.lat)??0,_=p?Cesium.Math.toDegrees(p.longitude):(f==null?void 0:f.camera.lon)??0,m=e._records.filter(y=>y!==f).map(y=>({record:y,distKm:n.model.haversineKm(g,_,y.camera.lat,y.camera.lon)})).sort((y,v)=>y.distKm-v.distKm).map(y=>y.record);e._geoQueue=f?[f,...m]:m,e._geoLoadTotal=e._geoQueue.length,e._geoLoadDone=0,e._geoLoading=!0,e._geoProgressNotifier=r(n.presentation.notifyListeners),e._geoQueueTimer=setTimeout(u,0)}return{stopGeometryLoadQueue:o,createGeometryProgressNotifier:r,processCctvGeometryQueueBatch:s,cctvGeometryDrainPacing:a,processCctvGeometryDrainBatch:c,prioritizeActiveCctvGeometryRecord:l,processGeometryBatch:u,enqueueGeometryRefresh:h,startGeometryLoadQueue:d}}function CS({state:e,services:t,parts:n,source:i}){const{CCTV_ACTIVATION_RESULT:o}=t.activation,{resolvePickId:r}=t.picking;function s(){var f;if(!e._activeCameraId)return null;if(e._recordById.has(e._activeCameraId))return e._recordById.get(e._activeCameraId);const d=e._records[0]||null;return d&&((f=d.camera)!=null&&f.id)&&(e._activeCameraId=d.camera.id),d}function a(d,f,p={}){Ff(d,(g,_)=>{xf(_)&&f(g)},p)}function c(d){var _;if(!d||!e._recordById.has(d))return o.NOT_FOUND;const f=e._recordById.get(d),p=s();if(!n.model.cctvRecordNeedsActivation(d,e._activeCameraId,f))return o.UNCHANGED;e._activeCameraId=d,e._autoHopSuspended=!1,n.projection.startProjectionLoop(),p&&p!==f&&n.geometry.clearProbeClampOnDeactivation(p,m=>{n.geometry.applyFrustumGeometry(m,n.ground.groundAltFor(m))}),e._cardIds.delete(d),e._cardGraceState.delete(d),e._hoverCardId===d&&n.hover.clearHoverCard();const g=e._geoQueue.indexOf(f);return g>0&&(e._geoQueue.splice(g,1),e._geoQueue.unshift(f)),n.geometry.runActivationObstructionProbe(f),n.geometry.ensureActiveCoverageEntities(f),n.projection.ensureProjectionRuntime(f),n.frames.refreshProjectionImage(f,!0),n.ground.rearmGroundResolution(f),n.geometry.updateRecordGeometry(f),n.ground.resolveFootprintGround(f),f.activationDone=!0,n.rendering.refreshCoverageStyles(),n.cards.refreshAmbientCards(),(_=e._gizmo)==null||_.refresh(),n.presentation.notifyListeners(),o.ACTIVATED}function l(){var f;const d=e._activeCameraId?e._recordById.get(e._activeCameraId):null;return d?(e._activeCameraId=null,e._autoHopSuspended=!0,d.activationDone=!1,n.geometry.clearProbeClampOnDeactivation(d,p=>{n.geometry.applyFrustumGeometry(p,n.ground.groundAltFor(p))}),n.rendering.refreshCoverageStyles(),n.cards.refreshAmbientCards(),(f=e._gizmo)==null||f.refresh(),n.presentation.notifyListeners(),!0):!1}function u(d,{activeCameraId:f=null,calibrationMode:p=!1}={}){return!f||p?!1:r(d)===null}function h(d){var m,b,C,y,v,M,w;if(!d)return null;const f=(m=d.id)!=null&&m.properties?d.id:(C=(b=d.primitive)==null?void 0:b.id)!=null&&C.properties?d.primitive.id:null,p=(y=f==null?void 0:f.properties)==null?void 0:y.cctvCameraId;if(p){const E=typeof p.getValue=="function"?p.getValue(Cesium.JulianDate.now()):p,k=typeof E=="string"?e._recordById.get(E):null,T=!!((v=k==null?void 0:k.coverageEntities)!=null&&v.includes(f)),I=((M=k==null?void 0:k.projection)==null?void 0:M.planeEntity)===f||e._projectionEntities.some(R=>(R==null?void 0:R.cameraId)===E&&R.planeEntity===f);if(k&&(T||I))return E}const g=typeof d.id=="string"?d.id:typeof((w=d.primitive)==null?void 0:w.id)=="string"?d.primitive.id:null,_=g===null?null:e._recordById.get(g);return _&&(d.primitive===e._billboards||d.primitive===_.billboard)?g:null}return{getActiveRecord:s,bindCctvWorldClickGesture:a,setActiveCamera:c,deactivateActiveCamera:l,cctvEmptyClickDeselects:u,extractPickedCameraId:h}}function yS({state:e,services:t,parts:n,source:i}){function o(l){if(!e._enabled||e._cameraMoving||e._calibrationMode||!l||!e._viewer||e._viewer.isDestroyed())return;const u=Date.now();if(u-e._hoverLastPickAt{e._hoverReleaseTimer=0,e._hoverCardId=null,n.cards.pushAmbientCardEntries()},WF))}function a(){r(),e._hoverCardId=null,e._hoverLastPickAt=0}function c(l){const u=l.camera.id;if(e._cardFetchPendingIds.has(u)||e._cardFetchInFlightCount>=bM)return;const h=n.cards.ensureCardFrameSlot(u),d=vM(l.camera);yM(h,d,Date.now())&&n.cards.fetchCardFrame(l,h,d,{userGesture:!0})}return{handleHoverMove:o,cancelHoverRelease:r,scheduleHoverRelease:s,clearHoverCard:a,hoverFetchCardFrame:c}}function vS({state:e,services:t,parts:n,source:i}){function o(){var f,p;const l=(p=(f=e._viewer)==null?void 0:f.camera)==null?void 0:p.positionCartographic;if(!l||!e._records.length)return null;const u=Cesium.Math.toDegrees(l.latitude),h=Cesium.Math.toDegrees(l.longitude);let d=null;for(const g of e._records){const _=n.model.haversineKm(u,h,g.camera.lat,g.camera.lon);(!d||_f.camera.id===e._activeCameraId),1,e._records.length);n.selection.setActiveCamera(e._records[d].camera.id),e._lastHopAt=l}function c(l,u,h){const d=Number.isFinite(h)?Math.floor(h):0;if(d<=0)return-1;const f=Number.isFinite(u)?Math.trunc(u):1;return!Number.isFinite(l)||l<0?f<0?d-1:0:((Math.floor(l)+f)%d+d)%d}return{nearestCameraIdToViewer:o,focusCctvRecord:r,focusCamera:s,maybeAutoHop:a,cctvCycleIndex:c}}function MS({state:e,services:t,parts:n,source:i}){function o(){const l=n.selection.getActiveRecord();if(!l)return e._records.length?`${e._records.length} CAMERAS STANDING BY · NO CAMERA SELECTED · CLICK A CAMERA TO ACTIVATE`:"No cameras available in catalog.";const u=n.model.sectorAreaKm2(l.camera.rangeM,l.camera.fovDeg),h=n.geometry.coverageNeighborCount(l),f=n.model.currentViewContext().split(":")[0]||"global",p=e._healthById.get(l.camera.id)||null,g=n.calibration.deriveCalBadge(l.camera);return[`${l.camera.city.toUpperCase()} CCTV`,`${l.camera.name.toUpperCase()}`,`HDG ${Math.round(l.camera.headingDeg)}°`,`FOV ${Math.round(l.camera.fovDeg)}°`,`COVERAGE ${u.toFixed(2)}km²`,h>0?`OVERLAP ${h} cams`:"ISOLATED VIEW",`PROJ ${e._showProjection?"MONITOR":"OFF"}`,e._coverageMode==="viewshed"?"VIEWSHED":null,`CAL ${g.replace("-"," ").toUpperCase()}`,p!=null&&p.sourceKind?`SRC ${String(p.sourceKind).toUpperCase()}`:`SRC ${String(l.camera.feedType||"image").toUpperCase()}`,`${f.toUpperCase()} CONTEXT`].filter(Boolean).join(" · ")}function r(l,u=null){var _,m;const h=u||((_=n.selection.getActiveRecord())==null?void 0:_.camera.id)||null,d=l.camera,f=e._healthById.get(d.id)||null,p=d.id===h,g=p?dh:gF;return{id:d.id,name:d.name,city:d.city,provider:d.provider,lat:d.lat,lon:d.lon,headingDeg:d.headingDeg,pitchDeg:d.pitchDeg,fovDeg:d.fovDeg,rangeM:d.rangeM,elevationM:d.absoluteHeightM,mountHeightM:d.mountHeightM,active:p,feedType:d.feedType,sourceKind:(f==null?void 0:f.sourceKind)||d.sourceKind||(d.feedConfigured?"configured":"seed"),sourceStatus:(f==null?void 0:f.status)||"unknown",sourceMessage:(f==null?void 0:f.message)||"",sourceLabel:(f==null?void 0:f.label)||d.provider||"",credit:d.credit||"",calibration:{...n.calibration.normalizeCalibration(d.calibration)},calDirty:!!l.calDirty,groundResolveCount:l.calibrationGroundResolveCount||0,groundMeshSampleRequestCount:l.groundMeshSampleRequestCount||0,groundPriorM:Number.isFinite((m=l.groundPrior)==null?void 0:m.ellipsoid)?l.groundPrior.ellipsoid:null,intrinsics:d.intrinsics?{...d.intrinsics}:null,extrinsics:d.extrinsics?{...d.extrinsics}:null,anchor:d.anchor?{...d.anchor}:null,calBadge:n.calibration.deriveCalBadge(d),poseSource:d.poseSource||null,basePose:d.basePose?{...d.basePose}:null,frameUrl:n.frames.frameUrlFor(d,g),mediaUrl:n.frames.mediaUrlFor(d)}}function s(){const l=n.selection.getActiveRecord(),u=(l==null?void 0:l.camera.id)||null;return{enabled:e._enabled,showCoverage:e._coverageMode!=="off",coverageMode:e._coverageMode,showProjection:e._showProjection,calibrationMode:e._calibrationMode,autoHop:e._autoHop,autoHopSuspended:e._autoHopSuspended,autoHopSec:e._autoHopSec,count:e._count,lastUpdate:e._lastUpdate,error:e._lastError,loading:{active:e._geoLoading,loaded:Math.min(e._geoLoadDone,e._geoLoadTotal),total:e._geoLoadTotal},ambientCards:{count:e._cardIds.size,limit:Vr,frameFetches:e._cardFetchCount,minFrameFetchSpacingMs:e._cardMinFetchSpacingMs,fetchMode:e._cardFetchMode,fetchesInFlight:e._cardFetchInFlightCount,hoverId:e._hoverCardId},activeCameraId:u,activeCamera:l?r(l,u):null,cameras:e._records.map(d=>r(d,u)),summary:o()}}function a(){const l=s();for(const u of e._listeners)try{u(l)}catch(h){console.warn("[Data:CCTV] listener error:",h)}}function c(){const l=Date.now();l-e._lastTransientNotifyAt<100||(e._lastTransientNotifyAt=l,a())}return{buildSummaryText:o,getPublicCameraState:r,uiState:s,notifyListeners:a,notifyListenersThrottled:c}}function wS({state:e,services:t,parts:n,source:i}){const{registerSpriteCollection:o,restoreSpriteOrder:r}=t.sprites,{activateCctvCameraFromWorldClick:s}=t.activation,{resolvePickId:a,registerPickOwner:c,unregisterPickOwner:l}=t.picking,{onFocusTargetAppear:u}=t.focus,{releaseContinuousRender:h}=t.render;function d(){n.geometryQueue.stopGeometryLoadQueue(),n.cards.teardownAmbientCards(),n.projection.clearProjectionOverlay(),e._records=[],e._recordById=new Map,e._healthById=new Map,e._count=0,e._lastUpdate=null,e._lastHealthSyncAt=0,e._lastError=null,e._lastFocusStyleAt=0,e._activeFocusStyleCount=0,e._activeTileset=null,e._lastAppliedRegime=null}return{clearRuntimeState:d,methods:{async init(p){var M;(M=e._sourceAbort)==null||M.abort();const g=new AbortController;e._sourceAbort=g,typeof document<"u"&&document.addEventListener("visibilitychange",n.cards.handleVisibilityChange),e._viewer=p,d(),e._enabled=!1,e._activeCameraId=null,e._autoHopSuspended=!1,e._lastHopAt=0,e._lastViewContext="",e._calibrationById=n.calibration.loadCalibrationStore(),e._billboards=new Cesium.BillboardCollection,e._viewer.scene.primitives.add(e._billboards),o("cctv",e._billboards);const _=await n.catalog.loadCameraSources(),m=n.catalog.buildCatalogFromSources(_),b=m.length?m:n.catalog.seedCatalog(),C=new Map(b.map(w=>w.id).sort().map((w,E)=>[w,E]));for(const w of b){const E=e._calibrationById.get(w.id);if(E){const k=E.rangeFloorM===tc?E.values:n.calibration.migrateRangeScaleForFloor(E.values,w.rangeM);E.values=k,E.rangeFloorM=tc,w.calibration=n.calibration.normalizeCalibration(k),w.calSource=E.source}n.model.ensureCameraPose(w)}const y=n.ground.resolveGroundPriors(b),v=await Promise.race([y,new Promise(w=>setTimeout(()=>w(null),PF))]);g.signal.throwIfAborted();for(let w=0;w0&&(e._activeCameraId=e._records[0].camera.id),!v){const w=e._records.slice();y.then(E=>{E&&n.ground.applyLateGroundPriors(w,E)}).catch(()=>{})}e._lastAppliedRegime=n.ground.currentSurfaceRegime(),!e._mapStackListener&&typeof window<"u"&&(e._mapStackListener=()=>n.ground.handleMapStackChanged(),window.addEventListener("gev:map-stack-changed",e._mapStackListener)),e._horizonCullListener||(e._horizonCullListener=()=>{e._cameraMoving=!1,n.rendering.refreshHorizonCulling(),n.cards.refreshAmbientCards()},e._viewer.camera.moveEnd.addEventListener(e._horizonCullListener)),e._moveStartListener||(e._moveStartListener=()=>{e._cameraMoving=!0},e._viewer.camera.moveStart.addEventListener(e._moveStartListener)),n.rendering.refreshHorizonCulling(),e._clickHandler=new Cesium.ScreenSpaceEventHandler(e._viewer.scene.canvas),n.selection.bindCctvWorldClickGesture(e._clickHandler,w=>{var R;if(!e._enabled)return;const E=e._viewer.scene.pick(w.position),k=n.selection.extractPickedCameraId(E);if(k){s(k,n.selection.setActiveCamera);return}if(a(E)!==null)return;const I=(R=e._cctvOverlayHost.hitTest(w.position.x,w.position.y,{sourceId:ur}))==null?void 0:R.entryId;if(I&&e._recordById.has(I)){s(I,n.selection.setActiveCamera);return}n.selection.cctvEmptyClickDeselects(E,{activeCameraId:e._activeCameraId,calibrationMode:e._calibrationMode})&&n.selection.deactivateActiveCamera()},{onMouseMove:w=>n.hover.handleHoverMove(w==null?void 0:w.endPosition)}),await n.health.syncHealthState(!0),n.rendering.refreshCoverageStyles(),n.presentation.notifyListeners(),r(e._viewer),console.log("[Data:CCTV] Initialized with",e._count,"cameras")},enable(){var g;e._enabled=!0,e._lastUpdate=Date.now(),c("cctv",_=>{if(e._recordById.has(_)||typeof _=="string"&&_.startsWith(rr))return!0;const m=/^cctv-(.+)-(?:ray-tl|ray-tr|ray-br|ray-bl|cap|plane|plane-label)$/.exec(_);return!!(m&&e._recordById.has(m[1]))}),!e._activeCameraId&&e._records.length&&(e._activeCameraId=e._records[0].camera.id,e._autoHopSuspended=!1);const p=n.selection.getActiveRecord();p&&(n.projection.ensureProjectionRuntime(p),n.frames.refreshProjectionImage(p,!0)),n.geometryQueue.startGeometryLoadQueue(),n.rendering.refreshCoverageStyles(),n.projection.startProjectionLoop(),(g=e._removeFocusAppearListener)==null||g.call(e),e._removeFocusAppearListener=u(()=>n.projection.startProjectionLoop()),e._cctvOverlayHost.setVisible(ur,!0),n.cards.startCardFrameLoop(),n.cards.refreshAmbientCards(),n.presentation.notifyListeners(),r(e._viewer)},disable(){var p,g;e._enabled=!1,l("cctv"),e._calibrationMode=!1,h("cctv-adjust"),(p=e._gizmo)==null||p.setEnabled(!1),(g=e._removeFocusAppearListener)==null||g.call(e),e._removeFocusAppearListener=null,n.projection.stopProjectionLoop(),n.geometryQueue.stopGeometryLoadQueue(),n.cards.teardownAmbientCards(),n.rendering.hideCctvVisuals(),n.presentation.notifyListeners()},destroy(p){var _,m,b,C;(_=e._sourceAbort)==null||_.abort(),typeof document<"u"&&document.removeEventListener("visibilitychange",n.cards.handleVisibilityChange),l("cctv"),e._mapStackListener&&typeof window<"u"&&(window.removeEventListener("gev:map-stack-changed",e._mapStackListener),e._mapStackListener=null);const g=p||e._viewer;e._horizonCullListener&&((m=g==null?void 0:g.camera)!=null&&m.moveEnd)&&(g.camera.moveEnd.removeEventListener(e._horizonCullListener),e._horizonCullListener=null),e._moveStartListener&&((b=g==null?void 0:g.camera)!=null&&b.moveStart)&&(g.camera.moveStart.removeEventListener(e._moveStartListener),e._moveStartListener=null),e._gizmo&&(e._gizmo.destroy(),e._gizmo=null),e._calibrationMode=!1,h("cctv-adjust"),e._clickHandler&&(e._clickHandler.destroy(),e._clickHandler=null),(C=g==null?void 0:g.scene)!=null&&C.screenSpaceCameraController&&(g.scene.screenSpaceCameraController.enableInputs=!0),n.projection.stopProjectionLoop(),n.geometryQueue.stopGeometryLoadQueue(),n.cards.teardownAmbientCards(),n.geometry.destroyCoverageEntities(),e._billboards&&g&&(g.scene.primitives.remove(e._billboards),e._billboards=null),d(),e._viewer=null,e._enabled=!1,e._activeCameraId=null,e._autoHopSuspended=!1,e._listeners.clear()}}}}function ES({state:e,services:t,parts:n,source:i}){async function o(r=!1){var a;const s=Date.now();if(!(!r&&s-e._lastHealthSyncAt=l)break}return f},getStats(){return{count:e._count,lastUpdate:e._lastUpdate,error:e._lastError,loading:e._geoLoading,loadingLoaded:Math.min(e._geoLoadDone,e._geoLoadTotal),loadingTotal:e._geoLoadTotal}},subscribe(c){return typeof c!="function"?()=>{}:(e._listeners.add(c),c(n.presentation.uiState()),()=>{e._listeners.delete(c)})},getUIState(){return n.presentation.uiState()},setCardPresentationOptions(c={}){return n.cards.setCctvCardPresentationOptions(c)},selectCamera(c,l={}){return n.selection.setActiveCamera(c)===s.NOT_FOUND?!1:(l.focus&&n.navigation.focusCamera(c,l.durationSec||1.8),!0)},focusCamera(c,l=2.2){return n.navigation.focusCamera(c,l)},cycleCamera(c=1,l={}){if(!e._records.length)return null;const u=n.selection.getActiveRecord(),h=n.navigation.cctvCycleIndex(e._records.findIndex(f=>f===u),c,e._records.length),d=e._records[h].camera.id;return n.selection.setActiveCamera(d),l.focus&&n.navigation.focusCamera(d,l.durationSec||1.8),d},focusNearest(c={}){const l=n.navigation.nearestCameraIdToViewer();return l?(n.selection.setActiveCamera(l),c.focus!==!1&&n.navigation.focusCamera(l,c.durationSec||1.8),l):null}}}}function kS({state:e,services:t,parts:n,source:i}){return{methods:{async update(){if(!e._enabled)return;const r=Date.now();if(e._lastUpdate=r,!e._tilesReadyReenqueued&&n.model.projectionTilesReady()){e._tilesReadyReenqueued=!0;const s=e._records.filter(a=>!n.ground.isGroundResolved(a));s.length&&n.geometryQueue.enqueueGeometryRefresh(s)}await n.health.syncHealthState(),n.navigation.maybeAutoHop(r),n.presentation.notifyListeners()}}}}function AS({services:e}){const{clearOverlaySource:t,hitTestWorldOverlay:n,setOverlayEntries:i,setOverlaySourceVisible:o}=e.overlays,r={};return r._viewer=null,r._billboards=null,r._records=[],r._recordById=new Map,r._coverageEntities=[],r._projectionEntities=[],r._enabled=!1,r._activeCameraId=null,r._coverageMode="on",r._showProjection=!0,r._autoHop=!1,r._autoHopSuspended=!1,r._autoHopSec=18,r._lastHopAt=0,r._lastViewContext="",r._clickHandler=null,r._count=0,r._lastUpdate=null,r._lastHealthSyncAt=0,r._lastError=null,r._healthById=new Map,r._calibrationById=new Map,r._listeners=new Set,r._projectionRaf=0,r._removeFocusAppearListener=null,r._lastFocusStyleAt=0,r._activeFocusStyleCount=0,r._scratchFocusScreen=new Cesium.Cartesian2,r._geoQueue=[],r._geoQueueTimer=0,r._geoLoading=!1,r._geoLoadTotal=0,r._geoLoadDone=0,r._geoProgressNotifier=null,r._tilesReadyReenqueued=!1,r._calibrationMode=!1,r._gizmo=null,r._lastTransientNotifyAt=0,r._activeTileset=null,r._lastAppliedRegime=null,r._mapStackListener=null,r._horizonCullListener=null,r._cardIds=new Set,r._cardGraceState=new Map,r._cardFrameSlots=new Map,r._cardFetchTimer=0,r._cardFetchInFlightCount=0,r._cardFetchImages=new Set,r._cardFetchPendingIds=new Set,r._cardFetchCount=0,r._cardLastFetchAt=0,r._cardMinFetchSpacingMs=null,r._cardFetchMode="steady",r.DEFAULT_CCTV_OVERLAY_HOST=Object.freeze({clearSource:t,hitTest:n,setEntries:i,setVisible:o}),r._cctvOverlayHost=r.DEFAULT_CCTV_OVERLAY_HOST,r._projectionOverlayOwnerId=null,r._activeCameraCardEnabled=!1,r._hoverCardId=null,r._hoverReleaseTimer=0,r._hoverLastPickAt=0,r._cameraMoving=!1,r._moveStartListener=null,r._sourceAbort=null,r}function IS(e,t=NaN){const n=Number(e);return Number.isFinite(n)?n:t}function RS(e,t=dh){const n=Math.max(1e3,IS(t,dh)),i=Math.floor(Date.now()/n),o=new URLSearchParams({label:e.name,city:e.city,lat:e.lat.toFixed(6),lon:e.lon.toFixed(6),heading:String(Math.round(e.headingDeg)),fov:String(Math.round(e.fovDeg)),pitch:String(Math.round(e.pitchDeg||-10)),ts:String(i)});return`${Mx}/${encodeURIComponent(e.id)}?${o.toString()}`}function LS(e){return`${wx}/${encodeURIComponent(e.id)}?ts=${Math.floor(Date.now()/15e3)}`}function PS({fetchImpl:e=(...t)=>globalThis.fetch(...t)}={}){async function t(n,i,{signal:o}={}){o==null||o.throwIfAborted();const r=await e(n,{cache:"no-store",signal:o});if(!r.ok)throw new Error("Camera source HTTP "+r.status);const s=await r.json();if(o==null||o.throwIfAborted(),!Array.isArray(s==null?void 0:s[i]))throw new Error("Malformed camera "+i+" snapshot");return s}return{getCatalog(n){return t("/api/cctv/sources","sources",n)},getHealth(n){return t("/api/cctv/health","cameras",n)},getFrameUrl:RS,getMediaUrl:LS}}function xS({services:e,source:t}){var r;if(!["getCatalog","getHealth","getFrameUrl","getMediaUrl"].every(s=>typeof(t==null?void 0:t[s])=="function"))throw new TypeError("A camera source is required");const n=AS({services:e}),i={},o={state:n,services:e,parts:i,source:t};return i.calibration=KF(o),i.testing=YF(o),i.projection=XF(o),i.cards=QF(o),i.model=ZF(o),i.ground=oS(o),i.geometry=mS(o),i.catalog=pS(o),i.frames=gS(o),i.rendering=_S(o),i.geometryQueue=bS(o),i.selection=CS(o),i.hover=yS(o),i.navigation=vS(o),i.presentation=MS(o),i.lifecycle=wS(o),i.health=ES(o),i.controls=TS(o),i.ingestion=kS(o),Object.assign({},i.controls.methods,i.lifecycle.methods,(r=i.ingestion)==null?void 0:r.methods,{calibrationPatchMovesAnchor:i.calibration.calibrationPatchMovesAnchor,migrateRangeScaleForFloor:i.calibration.migrateRangeScaleForFloor,_pushAmbientCardEntriesForTest:i.testing._pushAmbientCardEntriesForTest,_setCctvOverlayHostForTest:i.testing._setCctvOverlayHostForTest,createCctvProjectionOverlayEntry:i.projection.createCctvProjectionOverlayEntry,setCctvCardPresentationOptions:i.cards.setCctvCardPresentationOptions,surfaceRegimeKey:i.ground.surfaceRegimeKey,normalizeCoverageMode:i.model.normalizeCoverageMode,readCalibrationStoreV2:i.calibration.readCalibrationStoreV2,writeCalibrationStoreV2:i.calibration.writeCalibrationStoreV2,deriveCalBadge:i.calibration.deriveCalBadge,computeFrustumGeometry:i.geometry.computeFrustumGeometry,activationProbeClampRange:i.geometry.activationProbeClampRange,frameSignatureFromPixels:i.frames.frameSignatureFromPixels,_createCctvProjectionPlaneForTest:i.testing._createCctvProjectionPlaneForTest,_updateCctvProjectionPlaneForTest:i.testing._updateCctvProjectionPlaneForTest,applyCctvFocusDeemphasis:i.rendering.applyCctvFocusDeemphasis,createGeometryProgressNotifier:i.geometryQueue.createGeometryProgressNotifier,processCctvGeometryQueueBatch:i.geometryQueue.processCctvGeometryQueueBatch,cctvGeometryDrainPacing:i.geometryQueue.cctvGeometryDrainPacing,processCctvGeometryDrainBatch:i.geometryQueue.processCctvGeometryDrainBatch,prioritizeActiveCctvGeometryRecord:i.geometryQueue.prioritizeActiveCctvGeometryRecord,processGeometryBatch:i.geometryQueue.processGeometryBatch,hideCctvRecordVisuals:i.rendering.hideCctvRecordVisuals,refreshCoverageStyles:i.rendering.refreshCoverageStyles,clearProbeClampOnDeactivation:i.geometry.clearProbeClampOnDeactivation,cctvRecordNeedsActivation:i.model.cctvRecordNeedsActivation,bindCctvWorldClickGesture:i.selection.bindCctvWorldClickGesture,setActiveCamera:i.selection.setActiveCamera,deactivateActiveCamera:i.selection.deactivateActiveCamera,cctvEmptyClickDeselects:i.selection.cctvEmptyClickDeselects,materializeCctvCoverageEntities:i.geometry.materializeCctvCoverageEntities,materializeCctvActiveCoverageEntities:i.geometry.materializeCctvActiveCoverageEntities,materializeCctvVisibleCoverageEntities:i.geometry.materializeCctvVisibleCoverageEntities,_extractPickedCameraIdForTest:i.testing._extractPickedCameraIdForTest,_setCctvCoverageStateForTest:i.testing._setCctvCoverageStateForTest,focusCctvRecord:i.navigation.focusCctvRecord,maybeAutoHop:i.navigation.maybeAutoHop,cctvCycleIndex:i.navigation.cctvCycleIndex})}const oc="gev:cctv-request-focus",wM=1.9,EM=Object.freeze({ACTIVATED:"activated",UNCHANGED:"unchanged",NOT_FOUND:"not-found"});function FS(e,t,n=window){return!e||typeof t!="function"||t(e)!==EM.ACTIVATED?!1:(n.dispatchEvent(new CustomEvent(oc,{detail:{cameraId:e}})),!0)}function TM(e,t){if(!(e!=null&&e.addEventListener)||!(e!=null&&e.removeEventListener)||typeof t!="function")return()=>{};e.addEventListener(oc,t);let n=!1;return()=>{n||(n=!0,e.removeEventListener(oc,t))}}function kM(e,t,n){var o;const i=(o=e==null?void 0:e.detail)==null?void 0:o.cameraId;return typeof i!="string"||!i||typeof t!="function"?!1:t(()=>i,r=>n(r,wM))}const SS=Object.freeze(Object.defineProperty({__proto__:null,CCTV_ACTIVATION_RESULT:EM,CCTV_FOCUS_REQUEST_EVENT:oc,CCTV_WORLD_CLICK_FOCUS_DURATION_SEC:wM,activateCctvCameraFromWorldClick:FS,registerCctvFocusRequestListener:TM,routeCctvFocusRequest:kM},Symbol.toStringTag,{value:"Module"}));function NS(e,t,n="Source",i={}){let o=e,r=null;const s=Object.fromEntries([...t,...Object.keys(i)].map(a=>[a,(...c)=>{if(typeof(o==null?void 0:o[a])!="function"&&i[a])return i[a](...c);if(typeof(o==null?void 0:o[a])!="function")throw new Error(`${n} is not configured`);const l=r,u=o,h=u[a](...c);return h&&typeof h.then=="function"?h.then(d=>{if(r!==l||o!==u)throw new DOMException(`${n} was replaced`,"AbortError");return d}):h}]));for(const a of["label","attribution"])Object.defineProperty(s,a,{enumerable:!0,get:()=>o==null?void 0:o[a]});return{source:s,configure(a){if(t.some(l=>typeof(a==null?void 0:a[l])!="function"))throw new TypeError(`Invalid ${n.toLowerCase()}`);const c=Symbol(n);return o=a,r=c,()=>{r===c&&(o=null,r=null)}}}}const DS=Ef(),OS=Object.fromEntries(Object.entries({boundaries:["query"],terrain:["getHeights"],regional:["getBrief"],weather:["getConditions"],summary:["summarize"]}).map(([e,t])=>[e,NS(DS[e],t,`${e} service`)])),ts=Object.freeze(Object.fromEntries(Object.entries(OS).map(([e,t])=>[e,t.source]))),Hg=Object.freeze({country:["country","political"],nation:["country","political"],state:["administrative_area_level_1","political"],province:["administrative_area_level_1","political"],region:["administrative_area_level_1","political"],county:["administrative_area_level_2","political"],district:["administrative_area_level_2","political"],municipality:["locality","political"],city:["locality","political"],town:["locality","political"],village:["locality","political"],hamlet:["locality","political"],suburb:["neighborhood","political"],neighbourhood:["neighborhood","political"],neighborhood:["neighborhood","political"],quarter:["neighborhood","political"],postcode:["postal_code"],road:["route"],highway:["route"],peak:["natural_feature"],mountain_range:["natural_feature"],wood:["natural_feature"],forest:["natural_feature"],park:["park"],nature_reserve:["park","natural_feature"],aerodrome:["airport"],airport:["airport"],university:["university"],stadium:["stadium"],island:["natural_feature"]});function AM(e,t,n){if(typeof e!="number"&&typeof e!="string"||typeof e=="string"&&e.trim()==="")return null;const i=Number(e);return Number.isFinite(i)&&i>=t&&i<=n?i:null}function ra(e){return AM(e,-90,90)}function sa(e){return AM(e,-180,180)}function BS(e){const t=String((e==null?void 0:e.addresstype)||"").toLowerCase(),n=String((e==null?void 0:e.type)||"").toLowerCase(),i=String((e==null?void 0:e.class)||"").toLowerCase(),o=Hg[t]||Hg[n]||(i==="highway"?["route"]:null)||(i==="leisure"?["park"]:null)||(i==="natural"?["natural_feature"]:null)||(i==="aeroway"?["airport"]:null)||(i==="amenity"&&n==="university"?["university"]:null);return o?[...o]:["point_of_interest","establishment"]}function VS(e){const t=Array.isArray(e==null?void 0:e.boundingbox)?e.boundingbox:[];if(t.length!==4)return null;const n=ra(t[0]),i=ra(t[1]),o=sa(t[2]),r=sa(t[3]);return n===null||i===null||o===null||r===null||n>i?null:{southwest:{lat:n,lng:o},northeast:{lat:i,lng:r}}}function HS(e){const t=ra(e==null?void 0:e.lat),n=sa(e==null?void 0:e.lon);if(t===null||n===null)return null;const i=String((e==null?void 0:e.display_name)||(e==null?void 0:e.name)||"").trim();if(!i)return null;const o=BS(e),r=VS(e),s=String((e==null?void 0:e.name)||"").trim();return{geometry:{location:{lat:t,lng:n},...r?{bounds:r,viewport:r}:{}},formatted_address:i,types:o,address_components:s?[{long_name:s,short_name:s,types:[...o]}]:[]}}function $S(e){const t=String(e||"").trim().match(/^(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)\|(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)$/);if(!t)return null;const n=ra(t[1]),i=sa(t[2]),o=ra(t[3]),r=sa(t[4]);return[n,i,o,r].some(s=>s===null)||n>=o?null:`${i},${o},${r},${n}`}function io(e){return Array.isArray(e)&&e.length>=2&&Number.isFinite(e[0])&&Math.abs(e[0])<=180&&Number.isFinite(e[1])&&Math.abs(e[1])<=90}function GS({providers:e={},signal:t}={}){const n=Object.freeze(Object.fromEntries(["reverseGeocode","textSearch","nearby","route"].map(o=>[o,typeof e[o]=="function"])));async function i(o,r,s={}){const a=AbortSignal.any([t,s.signal,AbortSignal.timeout(o==="route"?13e3:5e3)].filter(Boolean));if(a.throwIfAborted(),!n[o])return null;const c=await e[o](...r,{...s,signal:a});return a.throwIfAborted(),c}return{capabilities:n,signal:t,attribution:Object.freeze({...e.attribution}),reverseGeocode(o,r,s){return io([r,o])?i("reverseGeocode",[o,r],s):Promise.resolve(null)},async textSearch(o,r,s){return!String(o||"").trim()||!io([r==null?void 0:r.longitude,r==null?void 0:r.latitude])?[]:await i("textSearch",[String(o).trim(),r],s)||[]},async nearby(o,r){return io([o==null?void 0:o.longitude,o==null?void 0:o.latitude])?await i("nearby",[o],r)||[]:[]},async route(o,r="foot",s){if(!Array.isArray(o)||o.length<2||o.length>12||!o.every(io)||!(e.routeProfiles||["foot","car","bike"]).includes(r))return null;const c=await i("route",[o,r],s);return!c||!Array.isArray(c.geometry)||c.geometry.length<2||!c.geometry.every(io)||!Number.isFinite(c.distanceM)||c.distanceM<0||!Number.isFinite(c.durationS)||c.durationS<0?null:{...c,ok:!0,profile:r}}}}function ls(e,t=180){return String(e||"").replace(/\s+/g," ").trim().slice(0,t)}function US(e){const t=(e==null?void 0:e.address)||{},n=ls(t.city||t.town||t.village||t.municipality||t.hamlet||t.county,90),i=ls(t.state||t.region||t.county,90),o=ls(t.country,90),r=[n,i].filter((s,a,c)=>s&&c.indexOf(s)===a).join(", ")||o||ls(e==null?void 0:e.display_name,120);return r?{label:r,locality:n||null,region:i||null,country:o||null,countryCode:ls(t.country_code,4).toUpperCase()||null}:null}function zS(e){const t=Number(e);return Number.isFinite(t)?t===0?"CLEAR":[1,2].includes(t)?"PARTLY CLOUDY":t===3?"OVERCAST":[45,48].includes(t)?"FOG":t>=51&&t<=57?"DRIZZLE":t>=61&&t<=67?"RAIN":t>=71&&t<=77?"SNOW":t>=80&&t<=82?"RAIN SHOWERS":t>=85&&t<=86?"SNOW SHOWERS":t>=95?"THUNDERSTORM":"MIXED CONDITIONS":"CONDITIONS UNKNOWN"}function jS(e,t){if(![e==null?void 0:e.latitude,e==null?void 0:e.longitude,t==null?void 0:t.latitude,t==null?void 0:t.longitude].every(Number.isFinite))return 1/0;const n=e.latitude*Math.PI/180,i=t.latitude*Math.PI/180,o=(t.latitude-e.latitude)*Math.PI/180,r=(t.longitude-e.longitude)*Math.PI/180,s=Math.sin(o/2)**2+Math.cos(n)*Math.cos(i)*Math.sin(r/2)**2;return 6371e3*2*Math.atan2(Math.sqrt(s),Math.sqrt(1-s))}async function qS(e,t,n){var u,h,d;const i=()=>Object.assign(new Error("Upstream response too large"),{code:"RESPONSE_TOO_LARGE"}),o=Number(e.headers.get("content-length"));if(Number.isFinite(o)&&o>t)throw(u=e.body)==null||u.cancel().catch(()=>{}),i();n==null||n.throwIfAborted();const r=(d=(h=e.body)==null?void 0:h.getReader)==null?void 0:d.call(h);if(!r){const f=await e.text();if(n==null||n.throwIfAborted(),new TextEncoder().encode(f).byteLength>t)throw i();return f}const s=()=>{r.cancel().catch(()=>{})};n==null||n.addEventListener("abort",s,{once:!0});const a=new TextDecoder;let c="",l=0;try{for(;;){n==null||n.throwIfAborted();const{done:f,value:p}=await r.read();if(n==null||n.throwIfAborted(),f)break;if(l+=p.byteLength,l>t)throw i();c+=a.decode(p,{stream:!0})}return c+a.decode()}catch(f){throw s(),f}finally{n==null||n.removeEventListener("abort",s),r.releaseLock()}}async function WS(e,t,n){return JSON.parse(await qS(e,t,n))}function mm(e){return HS(e&&{...e,class:e.class||e.category})}function IM(e){var r,s;const t=mm(e),n=US(e);if(!t||!n)return null;const i=a=>String(a||"").replace(/[\x00-\x1f\x7f]/g," ").replace(/\s+/g," ").trim().slice(0,120),o=i(((r=e.address)==null?void 0:r.road)||((s=e.address)==null?void 0:s.pedestrian));return{formattedAddress:t.formatted_address,locality:n.locality,region:n.region,country:n.country,types:t.types,labels:[i(t.formatted_address)].filter(Boolean),streetLabels:o?[o]:[]}}function KS({searchEndpoint:e,reverseEndpoint:t,fetchImpl:n=(...i)=>fetch(...i)}={}){for(const o of[e,t]){if(o==null)continue;if(typeof o!="string"||!o||/[?#]/.test(o))throw new TypeError("A query-free Nominatim endpoint is required");const r=new URL(o,"http://localhost");if(!["http:","https:"].includes(r.protocol)||r.username||r.password||!(o.startsWith("/")&&!o.startsWith("//")||/^https?:\/\//.test(o)))throw new TypeError("Invalid Nominatim endpoint")}async function i(o,r,s){var c,l;s==null||s.throwIfAborted();const a=await n(`${o}?${new URLSearchParams({format:"jsonv2",addressdetails:"1",...r})}`,{signal:s,redirect:"error"});if(s==null||s.throwIfAborted(),!a.ok)throw await((l=(c=a.body)==null?void 0:c.cancel)==null?void 0:l.call(c).catch(()=>{})),new Error("Geocoding service unavailable");return WS(a,512*1024,s)}return{...e?{async search(o,{bias:r,signal:s}={}){const a=$S(r),c=await i(e,{q:o,limit:"1",...a?{viewbox:a,bounded:"0"}:{}},s);if(!Array.isArray(c))throw new Error("Invalid geocoding response");if(c.length&&!mm(c[0]))throw new Error("Invalid geocoding result");return c}}:{},...t?{async reverse(o,r,{signal:s}={}){if(!io([r,o]))return null;const a=await i(t,{lat:o,lon:r},s);if((a==null?void 0:a.error)==="Unable to geocode")return null;if(!IM(a))throw new Error("Invalid reverse geocoding result");return a}}:{}}}function RM(e){var a,c,l,u;const t=(c=(a=e==null?void 0:e.geometry)==null?void 0:a.location)==null?void 0:c.lat,n=(u=(l=e==null?void 0:e.geometry)==null?void 0:l.location)==null?void 0:u.lng;if(!Number.isFinite(t)||!Number.isFinite(n)||Math.abs(t)>90||Math.abs(n)>180)return null;const i=Array.isArray(e.types)?e.types:[],o=new Set(i.map(h=>String(h).toLowerCase())),s=(Array.isArray(e.address_components)?e.address_components:[]).find(h=>Array.isArray(h.types)&&h.types.some(d=>d!=="political"&&o.has(String(d).toLowerCase())));return{lat:t,lng:n,name:(s==null?void 0:s.long_name)||"",label:e.formatted_address||"",types:i,viewport:e.geometry.bounds||e.geometry.viewport||null}}function $g({request:e}){return{async geocode(t,{bias:n=null,signal:i}={}){var o;i==null||i.throwIfAborted();try{const r=await e(t,{bias:n,signal:i});if(i==null||i.throwIfAborted(),!r)return{place:null,answered:!0};if(r.ok===!1)return{place:null,answered:!1};const s=await r.json();if(i==null||i.throwIfAborted(),(s==null?void 0:s.status)==="ZERO_RESULTS"&&Array.isArray(s.results)&&s.results.length===0)return{place:null,answered:!0};const a=(s==null?void 0:s.status)==="OK"?RM((o=s.results)==null?void 0:o[0]):null;return{place:a,answered:!!a}}catch{return i==null||i.throwIfAborted(),{place:null,answered:!1}}}}}function YS(e={}){const t=KS(e);return{attribution:{geocode:"OpenStreetMap / Nominatim",reverseGeocode:"OpenStreetMap / Nominatim"},...t.search?{async geocode(n,i={}){var o;try{const r=await t.search(n,i);return{place:r.length?RM(mm(r[0])):null,answered:!0}}catch{return(o=i.signal)==null||o.throwIfAborted(),{place:null,answered:!1}}}}:{},...t.reverse?{async reverseGeocode(n,i,o){const r=await t.reverse(n,i,o);return r?IM(r):null}}:{}}}function Gg(e){return[...new Set(e.map(t=>String(t||"").replace(/[\x00-\x1f\x7f]/g," ").replace(/\s+/g," ").trim().slice(0,120)).filter(Boolean))]}function XS(e){var r;if((e==null?void 0:e.status)!=="OK"||!((r=e.results)!=null&&r.length))return null;const t=e.results[0],n=e.results.slice(0,12),i=Array.isArray(t.address_components)?t.address_components:[],o=s=>{var a;return((a=i.find(c=>{var l;return(l=c.types)==null?void 0:l.includes(s)}))==null?void 0:a.long_name)||null};return{formattedAddress:t.formatted_address||null,locality:o("locality")||o("postal_town")||o("administrative_area_level_2"),region:o("administrative_area_level_1"),country:o("country"),types:t.types||[],labels:Gg(n.map(s=>s.formatted_address)).slice(0,12),streetLabels:Gg(n.flatMap(s=>(s.address_components||[]).filter(a=>{var c;return(c=a.types)==null?void 0:c.includes("route")}).map(a=>a.long_name))).slice(0,12)}}function QS({fetchImpl:e=(...i)=>fetch(...i),resolveApiKey:t,endpoints:n={}}={}){const i={reverse:"https://maps.googleapis.com/maps/api/geocode/json",textSearch:"/api/google/text-search",nearby:"/api/google/nearby-places",route:"/api/route",...n};async function o(s,a,{signal:c}={}){var d,f;if(!s)return null;const l=s.includes("?")?"&":"?",u=await e(`${s}${l}${new URLSearchParams(a)}`,{signal:c});if(c==null||c.throwIfAborted(),!u.ok)throw await((f=(d=u.body)==null?void 0:d.cancel)==null?void 0:f.call(d).catch(()=>{})),new Error("Geospatial service unavailable");const h=await u.json();return c==null||c.throwIfAborted(),h}const r=s=>(Array.isArray(s==null?void 0:s.places)?s.places:[]).filter(a=>io([a.longitude,a.latitude])).slice(0,20);return{attribution:{reverseGeocode:"Google",textSearch:"Google",nearby:"Google",route:"OpenStreetMap / OSRM"},routeProfiles:["foot","car","bike"],async reverseGeocode(s,a,c){const l=t==null?void 0:t();return t&&!l?null:XS(await o(i.reverse,{latlng:`${s},${a}`,...l?{key:l}:{}},c))},async textSearch(s,{latitude:a,longitude:c,radiusM:l=6e3},u){return r(await o(i.textSearch,{q:s,lat:a,lon:c,radiusM:l},u))},async nearby({latitude:s,longitude:a,radiusM:c=250},l){return r(await o(i.nearby,{lat:s,lon:a,radiusM:c},l))},async route(s,a,c){const l=s.map(h=>h.slice(0,2).map(d=>d.toFixed(6)).join(",")).join(";"),u=await o(i.route,{profile:a,coords:l},c);return u!=null&&u.ok?u:null}}}const So=Object.freeze({async geocode(e,{signal:t}={}){return t==null||t.throwIfAborted(),{place:null,answered:!1}}});function ZS({providers:e,signal:t,timeoutMs:n=12e3,now:i=Date.now}){const o=new Map;return{async geocode(r,{bias:s=null,signal:a}={}){const c=AbortSignal.any([t,a,AbortSignal.timeout(n)].filter(Boolean));c.throwIfAborted();const l=String(r??"").trim();if(!l)return{place:null,answered:!0};const u=`${s||""} +${l.toLowerCase()}`,h=o.get(u);if(h&&h.expires>i())return h.result;o.delete(u);let d={place:null,answered:e.length>0};try{for(const[f,p]of e.entries()){c.throwIfAborted();const g=await p.geocode(l,{bias:s,signal:c});if(c.throwIfAborted(),d={place:g.place,answered:!!g.place||d.answered&&g.answered},d.place){d.fallbackUsed=f>0;break}}}catch(f){if(t==null||t.throwIfAborted(),a==null||a.throwIfAborted(),!c.aborted)throw f;return{place:null,answered:!1}}if(c.throwIfAborted(),d.answered)for(o.set(u,{result:d,expires:i()+(d.place?3e5:3e4)});o.size>64;)o.delete(o.keys().next().value);return d}}}const pm="https://photon.komoot.io/api/",JS=6e3,eN=64,tN=5,nN=new Map,iN=Object.freeze({country:"country",state:"administrative_area_level_1",county:"administrative_area_level_2",city:"locality",district:"sublocality",locality:"locality",street:"route"}),Ug=Object.freeze({"leisure=park":"park","leisure=nature_reserve":"park","leisure=garden":"park","leisure=stadium":"stadium","boundary=national_park":"park","boundary=protected_area":"park","tourism=zoo":"zoo","tourism=theme_park":"amusement_park","amenity=university":"university","amenity=college":"university","amenity=grave_yard":"cemetery","landuse=cemetery":"cemetery","landuse=forest":"natural_feature","aeroway=aerodrome":"airport","shop=mall":"shopping_mall","place=region":"natural_feature","place=suburb":"sublocality","place=neighbourhood":"sublocality","place=quarter":"sublocality","place=borough":"sublocality","place=square":null}),oN=Object.freeze(new Set(["natural","water","waterway","landuse"]));function rN(e){const t=String((e==null?void 0:e.osm_key)||""),n=String((e==null?void 0:e.osm_value)||""),i=`${t}=${n}`;if(Object.prototype.hasOwnProperty.call(Ug,i)){const r=Ug[i];return r?[r]:[]}if(oN.has(t))return["natural_feature"];if(t==="highway")return["route"];const o=iN[String((e==null?void 0:e.type)||"")];return o?[o]:[]}function sN(e){if(!Array.isArray(e)||e.length!==4)return null;const[t,n,i,o]=e;return![t,n,i,o].every(Number.isFinite)||t>i||Math.abs(n)>90||Math.abs(o)>90||Math.abs(t)>180||Math.abs(i)>180?null:{southwest:{lat:Math.min(n,o),lng:Math.min(t,i)},northeast:{lat:Math.max(n,o),lng:Math.max(t,i)}}}function aN(e){const n=[String((e==null?void 0:e.name)||"").trim()];for(const i of["district","city","state","country"]){const o=String((e==null?void 0:e[i])||"").trim();o&&!n.includes(o)&&n.push(o)}return n.filter(Boolean).join(", ")}function zg(e){var r;if(!Array.isArray((r=e==null?void 0:e.geometry)==null?void 0:r.coordinates)||e.geometry.type!=="Point")return null;const[t,n]=e.geometry.coordinates;if(!Number.isFinite(n)||!Number.isFinite(t)||Math.abs(n)>90||Math.abs(t)>180)return null;const i=e.properties||{},o=String(i.name||"");return{lat:n,lng:t,name:o,label:aN(i)||o,types:rN(i),viewport:sN(i.extent)}}function jg(e,{bias:t=null,limit:n=tN,endpoint:i=pm}={}){const o=new URL(i);o.searchParams.set("q",String(e??"")),o.searchParams.set("limit",String(n));const r=String(t??"").split("|");if(r.length===2){const[s,a]=r[0].split(",").map(Number),[c,l]=r[1].split(",").map(Number);[s,a,c,l].every(Number.isFinite)&&(o.searchParams.set("lat",String((s+c)/2)),o.searchParams.set("lon",String((a+l)/2)))}return o.toString()}function ph(e){return String(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}function qg(e,t,{allowContains:n=!1}={}){if(!t)return null;const i=(Array.isArray(e)?e:[]).map(o=>{var r;return[o,ph((r=o==null?void 0:o.properties)==null?void 0:r.name)]});for(const[o,r]of i)if(r===t||r.startsWith(`${t} `))return o;if(!n)return null;for(const[o,r]of i)if(r.includes(t))return o;return null}function lN(e){for(;e.size>eN;){const t=e.keys().next().value;if(t===void 0)break;e.delete(t)}}async function cN(e,{bias:t=null,fetchImpl:n=fetch,signal:i,cache:o=nN,endpoint:r=pm}={}){i==null||i.throwIfAborted();const s=String(e??"").trim();if(!s)return{place:null,answered:!0};const a=`${r} +${t??""} +${s}`,c=o.get(a);if(c&&c.expires>Date.now())return{place:c.place,answered:!0};o.delete(a);const l=async p=>{try{i==null||i.throwIfAborted();const g=AbortSignal.timeout(JS),_=i?AbortSignal.any([i,g]):g,m=await n(p,{signal:_});if(!m.ok)return null;const b=await m.json();return _.throwIfAborted(),!Array.isArray(b==null?void 0:b.features)||b.features.some(C=>!zg(C))?null:b.features}catch{return i==null||i.throwIfAborted(),null}};let u=null,h=!0;if(t){const p=await l(jg(s,{bias:t,endpoint:r}));p===null?h=!1:u=qg(p,ph(s))}if(i==null||i.throwIfAborted(),!u){const p=await l(jg(s,{bias:null,endpoint:r}));if(p===null)h=!1;else{const g=ph(s.split(",")[0]);u=qg(p,g,{allowContains:!0})||p[0]}}i==null||i.throwIfAborted();const d=zg(u),f=!!d||h;return f&&(o.set(a,{place:d,expires:Date.now()+(d?3e5:3e4)}),lN(o)),{place:d,answered:f}}function uN({fetchImpl:e=(...n)=>fetch(...n),endpoint:t=pm}={}){const n=new Map;return{geocode:(i,o={})=>cN(i,{...o,fetchImpl:e,cache:n,endpoint:t})}}const dN=/^([NSEW])?\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*°?\s*([NSEW])?$/i,hN=new Set(["N","S"]);function Wg(e){const t=dN.exec(String(e).trim());if(!t)return null;const[,n,i,o]=t;if(n&&o)return null;const r=(n||o||"").toUpperCase(),s=Number(i);if(!Number.isFinite(s)||r&&/^[+-]/.test(i))return null;if(!r)return{value:s,axis:null};const a=Math.abs(s);return{value:r==="S"||r==="W"?-a:a,axis:hN.has(r)?"lat":"lon"}}function fN(e){const t=String(e).trim();if(!t)return null;const i=(/[,;]/.test(t)?t.split(/[,;]/):t.split(/\s+(?=[+-]?[.\d]|[NSEW]\s*[+-]?[.\d])/i)).map(o=>o.trim()).filter(Boolean);return i.length===2?i:null}function mN(e,t){const n=e>=0?"N":"S",i=t>=0?"E":"W";return`${Math.abs(e).toFixed(4)}° ${n}, ${Math.abs(t).toFixed(4)}° ${i}`}function pN(e){if(typeof e!="string")return null;const t=fN(e);if(!t)return null;const n=Wg(t[0]),i=Wg(t[1]);if(!n||!i||n.axis&&n.axis===i.axis)return null;let o,r;return n.axis==="lon"||i.axis==="lat"?(o=i.value,r=n.value):(o=n.value,r=i.value),!Number.isFinite(o)||!Number.isFinite(r)||o<-90||o>90||r<-180||r>180?null:{lat:o,lon:r,label:mN(o,r)}}const gN=.015;function _N(e,t,n){const i=o=>{const r=((o+180)%360+360)%360-180;return r===-180?180:r};return{southwest:{lat:Math.max(-90,e-n),lng:i(t-n)},northeast:{lat:Math.min(90,e+n),lng:i(t+n)}}}function bN(){return{async geocode(e,{signal:t}={}){t==null||t.throwIfAborted();const n=pN(e);return n?{place:{lat:n.lat,lng:n.lon,name:n.label,label:n.label,types:["coordinate"],exact:!0,viewport:_N(n.lat,n.lon,gN)},answered:!0}:{place:null,answered:!0}}}}const CN=.005;function LM(e){return String(e||"").toLowerCase().normalize("NFKD").replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function Kg(e,t,n){const i=o=>{const r=((o+180)%360+360)%360-180;return r===-180?180:r};return{southwest:{lat:Math.max(-90,e-n),lng:i(t-n)},northeast:{lat:Math.min(90,e+n),lng:i(t+n)}}}function yN(e){var i,o,r,s,a;const t=new Map,n=(c,l)=>{const u=LM(c);u&&!t.has(u)&&t.set(u,l)};for(const[c,l]of Object.entries(e||{})){const u=(i=l==null?void 0:l.pois)==null?void 0:i[0],h=l==null?void 0:l.viewBounds,d=Number(u==null?void 0:u.lat),f=Number(u==null?void 0:u.lon);if(Number.isFinite(d)&&Number.isFinite(f)){const p={lat:d,lng:f,name:l.name,label:l.name,types:["locality"],exact:!0,viewport:Number.isFinite((o=h==null?void 0:h.southwest)==null?void 0:o.lat)&&Number.isFinite((r=h==null?void 0:h.southwest)==null?void 0:r.lng)&&Number.isFinite((s=h==null?void 0:h.northeast)==null?void 0:s.lat)&&Number.isFinite((a=h==null?void 0:h.northeast)==null?void 0:a.lng)?{southwest:{lat:h.southwest.lat,lng:h.southwest.lng},northeast:{lat:h.northeast.lat,lng:h.northeast.lng}}:Kg(d,f,.1)};n(c,p),n(l.name,p)}for(const p of(l==null?void 0:l.pois)||[]){const g=Number(p==null?void 0:p.lat),_=Number(p==null?void 0:p.lon);!Number.isFinite(g)||!Number.isFinite(_)||n(p.name,{lat:g,lng:_,name:p.name,label:l!=null&&l.name?`${p.name}, ${l.name}`:p.name,types:["point_of_interest"],exact:!0,viewport:Kg(g,_,CN)})}}return t}function vN({presets:e={}}={}){const t=yN(e);return{async geocode(n,{signal:i}={}){i==null||i.throwIfAborted();const o=t.get(LM(n));return o?{place:o,answered:!0}:{place:null,answered:!0}}}}function PM({resolveApiKey:e,fetchImpl:t=(...a)=>fetch(...a),signal:n,endpoints:i={},providers:o={},presets:r=null,geocoding:s=null}={}){if(s&&s.provider!=="nominatim")throw new TypeError("Unsupported geocoding provider");const a=s?YS({...s,fetchImpl:t}):null;if(a&&!a.geocode)throw new TypeError("Nominatim searchEndpoint is required");const c=ZS({signal:n,providers:o.geocode||[bN(),...r?[vN({presets:r})]:[],...a?[a]:[$g({request(u,{bias:h,signal:d}){const f=e==null?void 0:e();if(!f)return null;const p=new URL(i.geocode||"https://maps.googleapis.com/maps/api/geocode/json");return p.searchParams.set("address",u),p.searchParams.set("key",f),h&&p.searchParams.set("bounds",h),t(p.toString(),{signal:d})}}),uN({fetchImpl:t,endpoint:i.photon}),$g({request(u,{bias:h,signal:d}){const f=new URLSearchParams({q:u});return h&&f.set("bounds",h),t(`${i.nominatim||"/api/geocode"}?${f}`,{signal:d})}})]]}),l=QS({fetchImpl:t,resolveApiKey:e,endpoints:i});return{...c,...GS({signal:n,providers:{...l,...a?{reverseGeocode:a.reverseGeocode,attribution:{...l.attribution,...a.attribution}}:{},...o}})}}const No=PM({resolveApiKey:()=>{var e;return(e=globalThis.window)==null?void 0:e.__GOOGLE_MAPS_API_KEY__}}),MN=5e3,wN=3e5;function xM(e,{cooldownMs:t=MN,maxCooldownMs:n=wN,now:i=()=>Date.now()}={}){let o=null,r=null,s=!1,a=0,c=0;return function(){if(o)return o;if(s){const h=Math.min(t*2**(c-1),n);if(i()-ae())();return o=u,u.then(()=>{o===u&&(r=null,s=!1,c=0)},h=>{o===u&&(o=null,r=h,s=!0,a=i(),c+=1)}),u}}const EN=[{id:"san-francisco",bbox:[-122.55,37.7,-122.35,37.84],loader:()=>Rl(()=>import("./san-francisco-B-TUYeaR.js"),[])}],Yg=new Map;function Xg(e){return String(e||"").toLowerCase().replace(/[^a-z0-9 ]+/g," ").replace(/\s+/g," ").trim()}const TN=new Map([["financial district","financial district south beach"],["downtown","financial district south beach"]]);function Qg(e,t,n){let i=!1;for(let o=0,r=n.length-1;ot!=l>t&&e<(c-s)*(t-a)/(l-a)+s&&(i=!i)}return i}function FM(e){return e?e.type==="Polygon"?[e.coordinates]:e.type==="MultiPolygon"?e.coordinates:[]:[]}function kN(e,t,n){for(const i of FM(e.geometry)){const o=i[0];if(!o||o.length<3||!Qg(t,n,o))continue;let r=!1;for(let s=1;st.length)&&(t=i)}return t}function IN(e){let t=Yg.get(e.id);return t||(t=xM(async()=>{const n=await e.loader(),i=n.default||n;return Array.isArray(i.features)?i.features:[]}),Yg.set(e.id,t)),t}async function RN(e){try{return await IN(e)()}catch(t){return console.warn(`[neighborhoods] ${e.id} pack unavailable:`,(t==null?void 0:t.message)||t),[]}}async function LN(e,t,n){const i=EN.find(l=>t>=l.bbox[0]&&e>=l.bbox[1]&&t<=l.bbox[2]&&e<=l.bbox[3]);if(!i)return null;const o=await RN(i);if(!o.length)return null;const r=Xg(n),s=TN.get(r)||r,a=new Set(s.split(" ").filter(Boolean));if(!a.size)return null;let c=null;for(const l of o){const u=Xg(l.properties&&l.properties.name);if(!u)continue;const h=u.split(" ").filter(Boolean);if(!h.length||!h.every(g=>a.has(g)))continue;const d=kN(l,t,e),f=d||AN(l.geometry);if(!f)continue;const p={ring:f,name:l.properties.name,contains:!!d,fwordCount:h.length};(!c||p.contains&&!c.contains||p.contains===c.contains&&p.fwordCount>c.fwordCount)&&(c=p)}return c?{ring:c.ring,name:c.name}:null}const gh=6371,uo=e=>e*Math.PI/180;function PN(e){const t=e.length;if(t<3)return 0;let n=0;for(let i=0;iimport("./regions-RPMKg9pq.js"),[]):await Rl(()=>import("./marine-BJ61ZZ9E.js"),[]);return t.default||t}function e_(e,t){const n=[];for(const i of e.features||[]){const o=i.polygons||[];if(!o.length)continue;let r=0,s=1/0,a=1/0,c=-1/0,l=-1/0;for(const u of o){r+=PN(u);for(const[h,d]of u)hc&&(c=h),dl&&(l=d)}n.push({name:i.name,namealt:i.namealt||null,featurecla:i.featurecla||"",kind:t,polygons:o,areaKm2:r,bbox:[s,a,c,l],bboxDiagonalKm:xN(s,a,c,l)})}return n}const NM=xM(async()=>{const[e,t]=await Promise.all([Jg("regions"),Jg("marine")]);Zg=[...e_(e,"natural"),...e_(t,"marine")];const n=new Map;for(const i of Zg)for(const o of new Set([rc(i.name),rc(i.namealt)])){if(!o)continue;const r=n.get(o);r?r.push(i):n.set(o,[i])}for(const i of n.values())i.sort((o,r)=>r.areaKm2-o.areaKm2);return n});function FN(e){return{name:e.name,featurecla:e.featurecla,kind:e.kind,polygons:e.polygons,bboxDiagonalKm:e.bboxDiagonalKm,areaKm2:e.areaKm2}}async function SN(e){const t=rc(e);if(!t)return null;const n=await NM(),i=[t,sc[t],...SM(sc[t]||t)];for(const o of i){if(!o)continue;const r=n.get(o);if(r&&r.length)return FN(r[0])}return null}function DM(e,t,n){if(!Array.isArray(e)||e.length<3)return!1;let i=!1;for(let o=0,r=e.length-1;ot!=l>t&&n<(c-s)*(t-a)/(l-a)+s&&(i=!i)}return i}async function NN(e,t,n){const i=rc(e);if(!i||!Number.isFinite(t)||!Number.isFinite(n))return null;const o=await NM(),r=[i,sc[i],...SM(sc[i]||i)],s=new Set;for(const a of r)if(!(!a||s.has(a))){s.add(a);for(const c of o.get(a)||[])for(const l of c.polygons)if(DM(l,t,n))return{name:c.name,kind:c.kind,featurecla:c.featurecla,ring:l,areaKm2:c.areaKm2}}return null}const OM=[{key:"opensky",html:'Flights: OpenSky Network — Schäfer et al., “Bringing Up OpenSky”, IPSN 2014 · opensky-network.org (non-commercial)'},{key:"adsblol",html:'Military flights, aircraft traces & bounded regional flight fallback: adsb.lol (ODbL 1.0)'},{key:"aisstream",html:'Live vessels (AIS): AISStream.io'},{key:"celestrak",html:'Satellites (TLEs): CelesTrak (celestrak.org), Dr. T.S. Kelso'},{key:"launch-library-2",html:'Space mission launch, payload & recovery metadata: Launch Library 2 — The Space Devs (API documentation and rate limits)'},{key:"usgs",html:"Earthquakes: Data courtesy of the U.S. Geological Survey"},{key:"overpass",html:'Road geometry (traffic): © OpenStreetMap contributors (ODbL 1.0)'},{key:"photon-geocoder",html:'Keyless place search: Photon (komoot) over © OpenStreetMap contributors (ODbL 1.0)'},{key:"alpr-osm",html:'ALPR camera locations (automatic license plate readers): © OpenStreetMap contributors (ODbL 1.0); community mapping includes DeFlock'},{key:"military-installations-osm",html:'Mapped installation context: © OpenStreetMap contributors (ODbL 1.0; incomplete mapped context)'},{key:"cockpit-place-osm",html:'Cockpit place context and last-resort place search: © OpenStreetMap contributors via Nominatim (ODbL 1.0)'},{key:"open-meteo",html:'Cockpit current conditions: Weather data by Open-Meteo.com (CC BY 4.0)'},{key:"google-news-rss",html:'Cockpit regional headlines: Google News RSS (location-matched article links; publisher terms apply)'},{key:"gdelt",html:'Cockpit regional headlines: GDELT Project (location-matched article links; publisher terms apply)'},{key:"austin-cctv",html:'CCTV cameras & frames: City of Austin, TX — data.austintexas.gov'},{key:"txdot-cctv",html:'CCTV cameras & frames (Texas): Texas Department of Transportation (courtesy)'},{key:"caltrans-cctv",html:'CCTV cameras & frames (California): Caltrans — cwwp2.dot.ca.gov'},{key:"tfl-cctv",html:'CCTV cameras & frames (London): Powered by TfL Open Data. Contains OS data © Crown copyright and database rights.'},{key:"ontario-511-cctv",html:'CCTV cameras & frames (Ontario): Ontario 511 (Open Government Licence - Ontario)'},{key:"fintraffic-cctv",html:'CCTV cameras & frames (Finland): Fintraffic / digitraffic.fi, license CC BY 4.0'},{key:"calgary-cctv",html:'Traffic cameras (Calgary): contains information licensed under the Open Government Licence – City of Calgary'},{key:"gbfs",html:"Bikeshare availability: GBFS operator feeds (e.g. Austin BCycle)"},{key:"osrm-routing",html:'Routing (voice routes and Directions): OSRM on the FOSSGIS servers — routing.openstreetmap.de · © OpenStreetMap contributors (ODbL) · fix the map'},{key:"gtfs-rt",html:"Transit vehicles: operator GTFS-Realtime feeds (each operator is credited below when its vehicles are shown)"},{key:"radio-browser",html:'Internet-radio station directory: Radio Browser (public domain; audio delivered directly by each broadcaster)'},{key:"reearth-terrain",html:'Terrain (keyless globe stacks): Re:Earth Terrain / Mapterhorn (CC BY 4.0) / EGM2008 (NGA)'},{key:"datacenters",html:'Datacenters: © OpenStreetMap contributors (ODbL 1.0)'},{key:"dams",html:'Dams: © OpenStreetMap contributors (ODbL 1.0) + Open Infrastructure Map'},{key:"firms",html:'Active fires: NASA FIRMS — we acknowledge the use of data and/or imagery from NASA’s Fire Information for Resource Management System (earthdata.nasa.gov/firms), part of NASA’s Earth Observing System Data and Information System (EOSDIS)'},{key:"drivebc-cctv",html:'CCTV cameras & frames (British Columbia): DriveBC. Contains information licensed under the Open Government Licence – British Columbia. Some cameras are supplied by partners (TransLink, the City of Vancouver, the City of Surrey, Parks Canada and others); each names its provider in the CCTV panel.'},{key:"tallinn-cctv",html:'CCTV cameras & frames (Tallinn): City of Tallinn — ristmikud.tallinn.ee (courtesy)'},{key:"tarktee-cctv",html:'CCTV cameras & frames (Estonia road weather): Transpordiamet / Tarktee — tarktee.transpordiamet.ee (courtesy)'},{key:"warendorf-cctv",html:'Webcam (Warendorf): Stadt Warendorf (courtesy); camera poses derived from OpenStreetMap geometry, © OpenStreetMap contributors (ODbL)'},{key:"nsw-cctv",html:'CCTV cameras & frames (New South Wales): Live Traffic NSW — Transport for NSW (CC BY 4.0)'},{key:"telegeography",html:'Submarine cables: © TeleGeography — submarinecablemap.com (CC BY-NC-SA 3.0 — NonCommercial)'}],DN={key:"tomtom",html:'Traffic flow data © TomTom'},BM={key:"natural-earth",html:'Physical region boundaries from Natural Earth (public domain)'};function VM(e){const t=n=>String(n).replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""");return{key:`transit-${e.id}`,html:`Transit (${t(e.attribution)}): ${t(e.license)}`}}const t_=new Set;function gm(e,t){const n=e==null?void 0:e.creditDisplay;return!n||typeof n.addStaticCredit!="function"||!(t!=null&&t.key)||!(t!=null&&t.html)?!1:(t_.has(t.key)||(n.addStaticCredit(new Cesium.Credit(t.html,!1)),t_.add(t.key)),!0)}function HM(e,t=OM){const n=e==null?void 0:e.creditDisplay;if(!(!n||typeof n.addStaticCredit!="function"))for(const{html:i}of t)n.addStaticCredit(new Cesium.Credit(i,!1))}const ON=Object.freeze(Object.defineProperty({__proto__:null,DATA_CREDITS:OM,NATURAL_EARTH_CREDIT:BM,TOMTOM_CREDIT:DN,registerDataCredits:HM,registerDynamicCredit:gm,transitFeedCredit:VM},Symbol.toStringTag,{value:"Module"})),BN=6e6,VN=1e9;function zt(e){if(!e)return!1;const{x:t,y:n,z:i}=e;if(!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(i))return!1;const o=Math.hypot(t,n,i);return o>=BN&&o<=VN}const HN=Object.freeze(Object.defineProperty({__proto__:null,isPickedWorldPosition:zt},Symbol.toStringTag,{value:"Module"}));function $M({boundarySource:e,signal:t}={}){if(typeof(e==null?void 0:e.query)!="function")throw new TypeError("Annotation boundaries require a query service");t==null||t.throwIfAborted();const n=new Map,i=new Map,o=new Map,r=6e4;function s(Q,X){const ie=Q.get(X);if(ie){if(ie.value!==null)return ie.value;if(Date.now()-ie.at<=r)return null;Q.delete(X)}}function a(Q,X,ie){t!=null&&t.aborted||Q.set(X,{value:ie,at:Date.now()})}function c(Q,X,ie,ce=!0){ie!=null&&ie.aborted||ce&&a(Q,X,null)}function l(Q,X){if(!X)return()=>{};if(X.aborted)return Q.abort(),()=>{};const ie=()=>Q.abort();return X.addEventListener("abort",ie,{once:!0}),()=>X.removeEventListener("abort",ie)}async function u({placeSearch:Q=So,viewer:X,target:ie,latitude:ce,longitude:ue,footprint:fe=!1,intent:Me="the_thing",entityKind:Te=null,labelHint:Re=null,deferFootprint:we=!1,allowDistant:Ae=!1,screenX:xe,screenY:ge,signal:Ee}){Ee=t?Ee?AbortSignal.any([t,Ee]):t:Ee,Ee==null||Ee.throwIfAborted();let Ie=Number(ue),Pe=Number(ce),Fe=null,De="coordinate",Qe=[],Ze=null,ze=null,nt=null,$e=[];const je={query:String(ie||"").trim(),places:"skipped",geocode:"none",osmSnap:"skipped"},Vt=!!S(ie,Te);if(!Number.isFinite(Pe)||!Number.isFinite(Ie)){const Oe=String(ie||"").trim();if(Oe){const ut=Ne(X,.5,.5)||U(X);if(ut&&(z(Oe)||j(Oe)||Te==="point_feature")){const Xe=await I(Oe,ut.lat,ut.lon,6e3,Ee,Q);Xe?(je.places=`${Xe.lat.toFixed(5)},${Xe.lon.toFixed(5)}`,Xe.distanceM<=p&&(Pe=Xe.lat,Ie=Xe.lon,Fe=Xe.label,ze=Xe.viewport||null,nt=Xe.label,$e=Xe.types||[],De="places")):je.places="miss"}if(De!=="places"){const Xe=await E(Oe,Le(X),Ee,Q);if(Xe&&(Pe=Xe.lat,Ie=Xe.lon,Fe=Xe.label,Qe=Xe.types||[],Ze=Xe.primaryName||null,ze=Xe.viewport||null,De="geocode",je.geocode=`${Xe.lat.toFixed(5)},${Xe.lon.toFixed(5)}`),ut&&je.places==="skipped"&&!Vt&&!Ae){let Be=De!=="geocode";if(De==="geocode"&&ve(ut.lat,ut.lon,Pe,Ie)/1e3>f&&(Be=!0),Be){const ot=await I(Oe,ut.lat,ut.lon,6e3,Ee,Q);ot&&ot.distanceM<=p?(Pe=ot.lat,Ie=ot.lon,Fe=ot.label,ze=ot.viewport||null,nt=ot.label,$e=ot.types||[],Qe=[],Ze=null,De="places",je.places=`${ot.lat.toFixed(5)},${ot.lon.toFixed(5)} (recovery)`):je.places=ot?"far-ignored":"miss"}}}}}if((!Number.isFinite(Pe)||!Number.isFinite(Ie))&&Number.isFinite(Number(xe))&&Number.isFinite(Number(ge))){const Oe=Ne(X,Number(xe),Number(ge));Oe&&(Pe=Oe.lat,Ie=Oe.lon,De="pixel")}if(!Number.isFinite(Pe)||!Number.isFinite(Ie))return null;if(De==="geocode"&&(z(ie)||Te==="point_feature")){const Oe=Ne(X,.5,.5)||U(X);if(Oe){const ut=await se(Oe.lat,Oe.lon,ie);ut?(Pe=ut.lat,Ie=ut.lon,Fe=Fe||ut.label,De="osm-local",je.osmSnap="hit"):je.osmSnap="miss"}}const _n=De==="geocode",ht=U(X),bt=(Oe,ut)=>{if(!ht)return null;const Xe=ve(ht.lat,ht.lon,Oe,ut)/1e3,Be=Math.max(d*ht.radiusKm,f);return Xe>Be?{driftKm:Xe,limitKm:Be}:null};if(_n&&!Vt&&!Ae){const Oe=bt(Pe,Ie);if(Oe)return je.query&&console.log(`[Resolver] "${je.query}": places=${je.places} geocode=${je.geocode} osmSnap=${je.osmSnap} → FINAL source=rejected (proximity gate, ${Oe.driftKm.toFixed(0)}km > ${Oe.limitKm.toFixed(0)}km)`),null}const st=Ze&&/[a-z]/i.test(Ze)?Ze:null,Bn=nt&&/[a-z]/i.test(nt)?nt:null,Wt=st||Bn||String(ie||"").trim(),os=A(R(Qe),Te),rs=ne(ie,Te,$e,Re),zo=ee(ie,Re,Te),di=async()=>{let Oe=os;const ut=Oe==="country"||Oe==="state"||Oe==="county"||Oe==="city",Xe=Me==="around_the_thing";if(!ut&&Oe!=="street"&&!Xe){const Kt=await NN(ie,Pe,Ie).catch(()=>null);if(Kt){gm(X,BM);const it=Ce(Kt.ring);return{ring:Kt.ring,footprintKind:"area",buildingHeight:null,synthesized:!1,naturalRegion:Kt.name,lat:(it==null?void 0:it.lat)??Pe,lon:(it==null?void 0:it.lon)??Ie,height:Se(X,(it==null?void 0:it.lon)??Ie,(it==null?void 0:it.lat)??Pe)}}}let Be=null;if(Xe&&!zo&&!ut&&Oe!=="street"&&Oe!=="neighborhood")Be=y(Pe,Ie,_);else if(ut)Be=await P(Pe,Ie,Wt,Oe,Ee);else if(Oe==="neighborhood"){const Kt=await LN(Pe,Ie,Wt);if(Kt&&(Be={ring:Kt.ring,kind:"area",heightM:null}),!Be){let it=await P(Pe,Ie,Wt,Oe,Ee);if(it&&M(it,Oe)&&(it=null),it)Be=it;else if(it===null){const Hn=await V(Pe,Ie,Wt,Oe,Ee,"strict");if(Hn)Be=Hn;else if(Hn===null){const Cn=await V(Pe,Ie,Wt,Oe,Ee,"loose");Cn&&Cn.kind!=="building"?Be=Cn:Cn===null?Be=y(Pe,Ie,g):Cn===void 0&&(Be=void 0)}else Be=void 0}else Be=void 0}}else if(Oe==="street")Be=await D(Pe,Ie,Wt,Ee);else if(Be=await V(Pe,Ie,Wt,Oe,Ee,rs?"point":_n&&!st?"anchored":"loose"),zo&&(Be===null||(Be==null?void 0:Be.kind)==="building")){const it=await B(Pe,Ie,Ee,Wt);it?(Be=it,Oe="compound"):it===null?Be=y(Pe,Ie,v(ze)):(Be==null?void 0:Be.kind)==="building"&&(Be=void 0)}if(Be&&!Be.synthesized&&Array.isArray(Be.ring)&&Be.ring.length>=3&&M(Be,Oe)&&(Be=null),L(Be))return Be;if(Be===void 0)return;if(!Be||!Array.isArray(Be.ring)||Be.ring.length<3)return null;const ot=Ce(Be.ring);return!ot||_n&&!Vt&&bt(ot.lat,ot.lon)?null:{ring:Be.ring,footprintKind:Be.kind,buildingHeight:Be.heightM,synthesized:!!Be.synthesized,lat:ot.lat,lon:ot.lon,height:Se(X,ot.lon,ot.lat)}};let hi=null,jo=null,qo=null,bn=!1;if(fe&&!we){const Oe=await di();Oe&&!L(Oe)&&(hi=Oe.ring,jo=Oe.footprintKind,qo=Oe.buildingHeight,bn=Oe.synthesized,Pe=Oe.lat,Ie=Oe.lon,De="footprint")}const Vn=Se(X,Ie,Pe);return je.query&&console.log(`[Resolver] "${je.query}": places=${je.places} geocode=${je.geocode} osmSnap=${je.osmSnap} → FINAL source=${De} ${Pe.toFixed(5)},${Ie.toFixed(5)}`+(fe&&we?" (outline pending)":"")),{lon:Ie,lat:Pe,height:Vn,ring:hi,footprintKind:jo,buildingHeight:qo,label:Fe,source:De,synthesized:bn,viewport:ze,...fe&&we?{resolveOutline:di}:{}}}const h={building:6e5,compound:6e7,neighborhood:8e7,city:9e9,county:12e10},d=8,f=50,p=8e3,g=750,_=400,m=300,b=150,C=1200;function y(Q,X,ie){const ue=111320*Math.cos(Q*Math.PI/180),fe=[],Me=44;for(let Te=0;Te<=Me;Te++){const Re=Te/Me*Math.PI*2;fe.push([X+Math.cos(Re)*ie/ue,Q+Math.sin(Re)*ie/111320])}return{ring:fe,kind:"area",heightM:null,synthesized:!0}}function v(Q){const X=Q==null?void 0:Q.low,ie=Q==null?void 0:Q.high;if(!X||!ie||![X.latitude,X.longitude,ie.latitude,ie.longitude].every(Number.isFinite))return m;const ue=ve(X.latitude,X.longitude,ie.latitude,ie.longitude)/2;return!Number.isFinite(ue)||ue<=0?m:Math.max(b,Math.min(C,ue))}function M(Q,X){const ie=h[X];return ie?w(Q.ring)>ie:!1}function w(Q){if(!Array.isArray(Q)||Q.length<3)return 0;const X=111320,ie=X*Math.cos(Cesium.Math.toRadians(Q[0][1]));let ce=0;for(let ue=0,fe=Q.length-1;ueNumber.isFinite(Ie==null?void 0:Ie.latitude)&&Number.isFinite(Ie==null?void 0:Ie.longitude)):null;if(!ge)return c(Me,Re,ue,!0),null;const Ee={lat:ge.latitude,lon:ge.longitude,label:ge.name||null,distanceM:ve(X,ie,ge.latitude,ge.longitude),viewport:ge.viewport||null,id:ge.id||null,primaryType:ge.primaryType||null,types:Array.isArray(ge.types)?ge.types:[]};return a(Me,Re,Ee),Ee}catch{return c(Me,Re,ue,!1),null}}function R(Q){const X=new Set((Q||[]).map(ie=>String(ie).toLowerCase()));return X.has("country")?"country":X.has("administrative_area_level_1")?"state":X.has("administrative_area_level_2")||X.has("administrative_area_level_3")?"county":X.has("locality")||X.has("postal_town")?"city":X.has("sublocality")||X.has("sublocality_level_1")||X.has("neighborhood")?"neighborhood":X.has("route")||X.has("intersection")?"street":X.has("premise")||X.has("subpremise")||X.has("street_address")?"building":X.has("shopping_mall")||X.has("university")||X.has("hospital")||X.has("airport")||X.has("park")||X.has("stadium")||X.has("amusement_park")||X.has("campus")||X.has("zoo")||X.has("cemetery")||X.has("tourist_attraction")||X.has("natural_feature")?"compound":"auto"}function S(Q,X){if(typeof X=="string"&&X.trim()){const ce=X.trim().toLowerCase();return ce==="country"||ce==="state"||ce==="county"?ce:null}const ie=String(Q||"").trim().toLowerCase();return/\b(?:country|nation)\s+of\s+\S/.test(ie)?"country":/^(?:the\s+)?state\s+of\s+\S/.test(ie)?"state":/\bcounty\s+of\s+\S/.test(ie)||/\bcounty$/.test(ie)?"county":null}function A(Q,X){return Q!=="auto"?Q:X==="building"?"building":X==="compound"?"compound":X==="district"?"neighborhood":X==="street"?"street":Q}function L(Q){return(Q==null?void 0:Q.rateLimited)===!0}async function F(Q,X=14e3,ie){const ce=new AbortController,ue=l(ce,ie),fe=window.setTimeout(()=>ce.abort(),X);try{return await e.query(Q,{signal:t?AbortSignal.any([t,ce.signal]):ce.signal})}catch{return null}finally{window.clearTimeout(fe),ue()}}async function P(Q,X,ie,ce,ue){const fe=`admin|${ce}|${Q.toFixed(4)},${X.toFixed(4)}|${ie.toLowerCase()}`,Me=s(n,fe);if(Me!==void 0)return Me;const Te=await F(`[out:json][timeout:25];is_in(${Q},${X})->.a;area.a["boundary"="administrative"]["admin_level"];out tags;`,14e3,ue);if(L(Te))return Te;if(!Te)return;const Re=te(ie),we=[];for(const Ee of Te){if(Ee.type!=="area"||!Ee.tags)continue;const Ie=te([Ee.tags.name,Ee.tags["name:en"]].filter(Boolean).join(" ")),Pe=te([Ee.tags.name,Ee.tags["name:en"],Ee.tags.official_name].filter(Boolean).join(" ")),Fe=de(Re,Pe);if(!Fe)continue;const De=Re.size?Fe/Re.size:0;if(De<.5)continue;const Qe=de(Re,Ie),Ze=Ie.size?Qe/Ie.size:0,ze=Ie.size===Re.size&&Qe===Re.size,nt=Number(Ee.tags.admin_level)||99;let $e;ce==="city"||ce==="neighborhood"?$e=nt*14:ce==="county"?$e=-Math.abs(nt-6)*14:$e=-nt*14;const je=De*1200+Ze*500+(ze?900:0)+$e;we.push({el:Ee,score:je,coverage:De})}we.sort((Ee,Ie)=>Ie.score-Ee.score||Ee.el.id-Ie.el.id);const Ae=we.length?we[0].el:null,xe=we.length?we[0].coverage:0;if(ce==="neighborhood"&&(!Ae||xe<.8)){const Ee=await O(Q,X,ie,ue);return L(Ee)?Ee:Ee?(a(n,fe,Ee),Ee):Ee===void 0?void 0:(c(n,fe,ue,!0),null)}if(!Ae)return c(n,fe,ue,!0),null;let ge=!1;for(const Ee of we.slice(0,4)){const Ie=await F(`[out:json][timeout:25];area(${Ee.el.id})->.x;rel(pivot.x);out geom;`,28e3,ue);if(L(Ie))return Ie;if(Ie===null){ge=!0;break}const Pe=Ie.find(ze=>ze.type==="relation");if(!Pe)continue;const Fe=ae(Pe);if(Fe.length<3)continue;let De=he(Fe.map(ze=>[ze.lon,ze.lat]));De=N(De,ce==="neighborhood"?6:ce==="city"?12:ce==="county"?40:120);const Ze={ring:De,kind:"area",heightM:null};if(M(Ze,ce)){if(ce==="neighborhood"){const ze=await O(Q,X,ie,ue);return L(ze)?ze:ze?(a(n,fe,ze),ze):ze===void 0?void 0:(c(n,fe,ue,!0),null)}continue}return a(n,fe,Ze),Ze}if(!ge){if(ce==="neighborhood"){const Ee=await O(Q,X,ie,ue);if(L(Ee))return Ee;if(Ee)return a(n,fe,Ee),Ee;if(Ee===void 0)return}return c(n,fe,ue,!0),null}}async function O(Q,X,ie,ce){const ue=te(ie),fe=await F(`[out:json][timeout:20];(way(around:1500,${Q},${X})["place"~"neighbourhood|suburb|quarter|borough"]["name"];relation(around:1500,${Q},${X})["place"~"neighbourhood|suburb|quarter|borough"]["name"];relation(around:1500,${Q},${X})["boundary"="place"]["name"];);out tags geom;`,14e3,ce);if(L(fe))return fe;if(fe===null)return;let Me=null,Te=0;for(const Re of fe){const we=ae(Re);if(we.length<3)continue;const Ae=Re.tags||{},xe=te([Ae.name,Ae["name:en"]].filter(Boolean).join(" ")),ge=de(ue,xe);if(!ge)continue;const Ee=xe.size?ge/xe.size:0;if(Ee<.6||ye(we)>8e7)continue;const Ie=Ee*1e3+(pe(X,Q,we)?400:0)+ge*50;Ie>Te&&(Te=Ie,Me=he(we.map(Pe=>[Pe.lon,Pe.lat])))}return Me?{ring:Me,kind:"area",heightM:null}:null}async function D(Q,X,ie,ce){const ue=`street|${Q.toFixed(4)},${X.toFixed(4)}|${ie.toLowerCase()}`,fe=s(n,ue);if(fe!==void 0)return fe;const Me=te(ie),Te=await F(`[out:json][timeout:20];(way(around:450,${Q},${X})["place"~"quarter|neighbourhood|suburb|city_block"];relation(around:450,${Q},${X})["place"~"quarter|neighbourhood|suburb"];way(around:450,${Q},${X})["landuse"~"commercial|retail"]["name"];relation(around:450,${Q},${X})["landuse"~"commercial|retail"]["name"]["type"="multipolygon"];);out tags geom;`,14e3,ce);if(L(Te))return Te;if(Te){let Ae=null,xe=0;for(const ge of Te){const Ee=ae(ge);if(Ee.length<3)continue;const Ie=ge.tags||{},Pe=te([Ie.name,Ie["name:en"]].filter(Boolean).join(" ")),Fe=de(Me,Pe);if(!Fe||ye(Ee)>2e6)continue;const De=Fe*1e3+(pe(X,Q,Ee)?300:0);De>xe&&(xe=De,Ae=he(Ee.map(Qe=>[Qe.lon,Qe.lat])))}if(Ae){const ge={ring:Ae,kind:"area",heightM:null};return a(n,ue,ge),ge}}const Re=await F(`[out:json][timeout:20];way(around:320,${Q},${X})["highway"]["name"];out geom;`,14e3,ce);if(L(Re))return Re;if(Re){const Ae=[];for(const xe of Re){const ge=xe.tags||{},Ee=te([ge.name,ge["name:en"]].filter(Boolean).join(" "));if(!de(Me,Ee))continue;const Ie=(xe.geometry||[]).filter(Pe=>Number.isFinite(Pe==null?void 0:Pe.lat)&&Number.isFinite(Pe==null?void 0:Pe.lon));Ie.length>=2&&Ae.push(Ie.map(Pe=>[Pe.lon,Pe.lat]))}if(Ae.length){const xe=$(Ae);if(xe.length>=2){const ge={ring:x(xe,11),kind:"area",heightM:null};return a(n,ue,ge),ge}}}const we=Te!==null&&Re!==null;return c(n,ue,ce,we),we?null:void 0}function $(Q){const X=(fe,Me)=>ve(fe[1],fe[0],Me[1],Me[0])<2,ie=Q.map(fe=>fe.slice());let ce=ie.shift(),ue=!0;for(;ue&&ie.length;){ue=!1;for(let fe=0;fe[we*ce,Ae*ue]),Me=[],Te=[];for(let we=0;we[we/ce,Ae/ue])}function N(Q,X){if(Q.length<=24)return Q;let ie=Q;if(ie.length>4e3){const Me=Math.ceil(ie.length/4e3);ie=ie.filter((Te,Re)=>Re%Me===0||Re===Q.length-1)}const ce=ie[0][1],ue=X/(111320*Math.cos(ce*Math.PI/180)),fe=G(ie,ue);return fe.length>=4?fe:Q}function G(Q,X){const ie=Q.length;if(ie<3)return Q.slice();const ce=new Uint8Array(ie);ce[0]=1,ce[ie-1]=1;const ue=[[0,ie-1]];for(;ue.length;){const Me=ue.pop(),Te=Me[0],Re=Me[1];let we=-1,Ae=0;const xe=Q[Te],ge=Q[Re];for(let Ee=Te+1;EeAe&&(Ae=Ie,we=Ee)}Ae>X&&we>Te&&(ce[we]=1,ue.push([Te,we]),ue.push([we,Re]))}const fe=[];for(let Me=0;Me[Vt.lon,Vt.lat])),ze=w(Ze);if(ze<=0||ze>h.compound)continue;const nt=te([(Ee=De.tags)==null?void 0:Ee.name,(Ie=De.tags)==null?void 0:Ie["name:en"],(Pe=De.tags)==null?void 0:Pe.official_name,(Fe=De.tags)==null?void 0:Fe.alt_name].filter(Boolean).join(" ")),$e=de(Re,nt)>0;(zeString(fe).toLowerCase()));return ue.has("monument")||ue.has("sculpture")}function ee(Q,X,ie){return ie?ie==="compound":j(Q)||j(X)}const re=new Map;async function se(Q,X,ie,ce){const ue=`${Q.toFixed(2)},${X.toFixed(2)}`;let fe=s(i,ue);if(fe===void 0){let we=re.get(ue);if(!we){const Ae=` + [out:json][timeout:20]; + ( + nwr(around:${q},${Q},${X})["historic"~"memorial|monument|statue|tomb"]; + nwr(around:${q},${Q},${X})["tourism"="artwork"]["name"]; + nwr(around:${q},${Q},${X})["memorial"]["name"]; + ); + out center tags; + `;we=F(Ae,6e3).then(xe=>{var Ee,Ie,Pe,Fe;if(xe===null||L(xe))return null;const ge=[];for(const De of xe){const Qe=((Ee=De.tags)==null?void 0:Ee.name)||((Ie=De.tags)==null?void 0:Ie["name:en"])||((Pe=De.tags)==null?void 0:Pe.official_name)||((Fe=De.tags)==null?void 0:Fe.alt_name);if(!Qe)continue;const Ze=Number.isFinite(De.lat)?{lat:De.lat,lon:De.lon}:De.center?{lat:De.center.lat,lon:De.center.lon}:null;Ze&&ge.push({name:Qe,lat:Ze.lat,lon:Ze.lon,words:te(Qe)})}return a(i,ue,ge),ge}).finally(()=>re.delete(ue)),re.set(ue,we)}if(fe=await we,fe===null)return null}if(!fe.length)return null;const Me=te(ie);if(!Me.size)return null;let Te=null,Re=0;for(const we of fe){const Ae=de(we.words,Me);if(!Ae)continue;const xe=we.words.size?Ae/we.words.size:0;if(xe<.6)continue;const ge=Ae*10+xe;ge>Re&&(Re=ge,Te=we)}return Te?{lat:Te.lat,lon:Te.lon,label:Te.name}:null}const me=6e4;function be(Q,X,ie,ce,ue="loose"){const fe=ue==="strict",Me=te(ce);let Te=null,Re=-1/0;for(const we of Q){const Ae=ae(we);if(Ae.length<3)continue;const xe=we.tags||{},ge=!!xe.building,Ee=ye(Ae),Ie=te([xe.name,xe["name:en"],xe.official_name,xe.alt_name,xe.short_name].filter(Boolean).join(" ")),Pe=de(Me,Ie),Fe=Ie.size?Pe/Ie.size:0,De=Pe>0;if(fe&&(!De||ge||Ee<3e5))continue;if(ue==="point"){const $e=Me.size?Pe/Me.size:0;if(!De||$e<.5||Fe<.6||Ee>me)continue}if(ge){if(Ee<40||Ee>4e5)continue}else if(Ee<200||!De&&Ee>6e5||De&&Ee>8e7)continue;const Qe=pe(ie,X,Ae);if(ue==="anchored"&&!Qe){const $e=Me.size?Pe/Me.size:0;if(!De||$e<.5||Fe<.6)continue}const Ze=Ce(Ae.map($e=>[$e.lon,$e.lat])),ze=Ze?ve(X,ie,Ze.lat,Ze.lon):9999;let nt=Pe*1e3+Fe*600+(Qe?450:0)-ze*.25-Math.sqrt(Ee)*.05;!De&&ge&&Qe&&(nt+=250),nt>Re&&(Re=nt,Te={ring:he(Ae.map($e=>[$e.lon,$e.lat])),kind:ge?"building":"area",heightM:ge?J(xe,Ee):null})}return Te}function J(Q,X){const ie=Z(Q.height||Q["building:height"]);if(ie)return ie;const ce=Number.parseFloat(Q["building:levels"]),ue=Z(Q["roof:height"])||0;if(Number.isFinite(ce)&&ce>0)return ce*3.3+ue;const fe=Math.sqrt(Math.max(1,X));return Math.max(10,Math.min(70,fe*.6))}function Z(Q){if(Q==null)return 0;const X=Number.parseFloat(String(Q).replace(",","."));return!Number.isFinite(X)||X<=0?0:/\b(ft|feet|foot)\b/i.test(String(Q))?X*.3048:X}function ae(Q){if(Array.isArray(Q.geometry))return Q.geometry.filter(ie=>Number.isFinite(ie==null?void 0:ie.lat)&&Number.isFinite(ie==null?void 0:ie.lon));if(!Array.isArray(Q.members))return[];const X=Q.members.filter(ie=>(ie.role==="outer"||!ie.role)&&Array.isArray(ie.geometry)).map(ie=>ie.geometry.filter(ce=>Number.isFinite(ce==null?void 0:ce.lat)&&Number.isFinite(ce==null?void 0:ce.lon))).filter(ie=>ie.length>=2);return oe(X)}function oe(Q){if(!Q.length)return[];const X=K(Q);if(!X.length)return[];const ie=30,ce=X.filter(Me=>_e(Me)<=ie);if(ce.length)return le(ce);const ue=le(X),fe=Math.min(Y(ue)*.15,1200);return _e(ue)<=fe?ue:[]}function le(Q){let X=Q[0],ie=ye(X);for(let ce=1;ceie&&(ie=ue,X=Q[ce])}return X}function Y(Q){let X=1/0,ie=-1/0,ce=1/0,ue=-1/0;for(const fe of Q)fe.latie&&(ie=fe.lat),fe.lonue&&(ue=fe.lon);return ve(X,ce,ie,ue)}function K(Q){const X=(ue,fe)=>Math.abs(ue.lon-fe.lon)<1e-7&&Math.abs(ue.lat-fe.lat)<1e-7,ie=Q.map(ue=>ue.slice()),ce=[];for(;ie.length;){let ue=ie.shift(),fe=!0;for(;fe;){fe=!1;const Me=ue[0],Te=ue[ue.length-1];for(let Re=0;ReX!=Te.lat>X&&Q<(Te.lon-Me.lon)*(X-Me.lat)/(Te.lat-Me.lat||Number.EPSILON)+Me.lon&&(ce=!ce)}return ce}function te(Q){return new Set(String(Q||"").toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g," ").trim().split(/\s+/).filter(X=>X.length>2))}function de(Q,X){let ie=0;for(const ce of Q)X.has(ce)&&ie++;return ie}function U(Q){var X;try{const ie=(X=Q==null?void 0:Q.camera)==null?void 0:X.positionCartographic;if(!ie)return null;const ce=Cesium.Math.toDegrees(ie.latitude),ue=Cesium.Math.toDegrees(ie.longitude),fe=Math.max(ie.height/1e3*3,5);return[ce,ue,fe].every(Number.isFinite)?{lat:ce,lon:ue,radiusKm:fe}:null}catch{return null}}function Le(Q){var X,ie;try{const ce=(ie=(X=Q==null?void 0:Q.camera)==null?void 0:X.computeViewRectangle)==null?void 0:ie.call(X);if(!ce)return null;const ue=Cesium.Math.toDegrees(ce.south).toFixed(4),fe=Cesium.Math.toDegrees(ce.west).toFixed(4),Me=Cesium.Math.toDegrees(ce.north).toFixed(4),Te=Cesium.Math.toDegrees(ce.east).toFixed(4);return[ue,fe,Me,Te].some(Re=>Re==="NaN")?null:`${ue},${fe}|${Me},${Te}`}catch{return null}}async function ke(Q,X,ie=null,ce=void 0,ue=No){const fe=Ne(Q,.5,.5)||U(Q);if(!fe||!(!ie||ve(fe.lat,fe.lon,ie.lat,ie.lon)/1e3>f))return null;const Te=await I(X,fe.lat,fe.lon,6e3,ce,ue);return Te&&Te.distanceM<=p?Te:null}function Ne(Q,X,ie){var ge;const ce=Q==null?void 0:Q.scene;if(!ce)return null;const ue=ce.canvas,fe=ue.clientWidth||ue.width||0,Me=ue.clientHeight||ue.height||0;if(!fe||!Me)return null;const Te=Math.max(0,Math.min(1,X))*fe,Re=Math.max(0,Math.min(1,ie))*Me,we=new Cesium.Cartesian2(Te,Re);let Ae=null;if(ce.pickPositionSupported&&typeof ce.pickPosition=="function")try{Ae=ce.pickPosition(we)}catch{Ae=null}if(!zt(Ae)&&typeof Q.camera.pickEllipsoid=="function")try{Ae=Q.camera.pickEllipsoid(we,Cesium.Ellipsoid.WGS84)}catch{Ae=null}if(!zt(Ae)&&typeof Q.camera.getPickRay=="function")try{const Ee=Q.camera.getPickRay(we);Ae=Ee&&((ge=ce.globe)==null?void 0:ge.pick(Ee,ce))||null}catch{Ae=null}if(!zt(Ae))return null;const xe=Cesium.Cartographic.fromCartesian(Ae);return xe?{lat:Cesium.Math.toDegrees(xe.latitude),lon:Cesium.Math.toDegrees(xe.longitude),height:Number.isFinite(xe.height)?xe.height:0}:null}function Se(Q,X,ie){var fe,Me;const ce=Q==null?void 0:Q.scene;if(!ce)return 0;try{if(ce.clampToHeightSupported&&typeof ce.clampToHeight=="function"){const Te=Cesium.Cartographic.fromDegrees(X,ie),Re=Cesium.Cartographic.toCartesian(Te),we=ce.clampToHeight(Re);if(we){const Ae=Cesium.Cartographic.fromCartesian(we).height;if(Number.isFinite(Ae))return Ae}}}catch{}const ue=(Me=(fe=ce.globe)==null?void 0:fe.getHeight)==null?void 0:Me.call(fe,Cesium.Cartographic.fromDegrees(X,ie));return Number.isFinite(ue)&&ue>0?ue:0}function Ue(Q){return Q&&String(Q).split(",")[0].trim()||null}async function rt(Q,X,ie=So){var Re,we;X=t?X?AbortSignal.any([t,X]):t:X,X==null||X.throwIfAborted();const ce=String(Q||"").trim();if(!ce)return null;const ue=await SN(ce).catch(()=>null);if((Re=ue==null?void 0:ue.polygons)!=null&&Re.length){const Ae=[...ue.polygons].sort((xe,ge)=>ge.length-xe.length)[0];if((Ae==null?void 0:Ae.length)>=3)return{name:ue.name,ring:Ae}}const fe=await E(ce,null,X,ie).catch(()=>null);if(!fe)return null;const Me=R(fe.types);if(!["country","state","county","city"].includes(Me))return null;const Te=await P(fe.lat,fe.lon,ce,Me,X).catch(()=>null);return((we=Te==null?void 0:Te.ring)==null?void 0:we.length)>=3?{name:ce,ring:Te.ring}:null}return t==null||t.addEventListener("abort",()=>{n.clear(),i.clear(),o.clear(),T=new WeakMap,re.clear()},{once:!0}),{resolveAnnotationTarget:u,refineScope:A,isRateLimitedOutcome:L,isGroundsLikeAsk:ee,selectFootprint:be,viewportBias:Le,placesNearViewRecovery:ke,resolveRegionRingForQuery:rt,pickWorldFromScreen:Ne,sampleGroundHeight:Se}}const $N=$M({boundarySource:ts.boundaries}),{resolveAnnotationTarget:GM,refineScope:GN,isRateLimitedOutcome:UM,isGroundsLikeAsk:UN,selectFootprint:zN,viewportBias:zM,placesNearViewRecovery:jM,resolveRegionRingForQuery:qM,pickWorldFromScreen:WM,sampleGroundHeight:_h}=$N,jN=Object.freeze(Object.defineProperty({__proto__:null,isGroundsLikeAsk:UN,isRateLimitedOutcome:UM,pickWorldFromScreen:WM,placesNearViewRecovery:jM,refineScope:GN,resolveAnnotationTarget:GM,resolveRegionRingForQuery:qM,sampleGroundHeight:_h,selectFootprint:zN,viewportBias:zM},Symbol.toStringTag,{value:"Module"})),Ot={austin:{name:"Austin",groundElevation:150,viewBounds:{southwest:{lat:30.1,lng:-97.95},northeast:{lat:30.52,lng:-97.55}},pois:[{name:"Texas State Capitol",lat:30.2747,lon:-97.7403,alt:550,pitch:-28,heading:180,buildingHeight:35},{name:"Frost Bank Tower",lat:30.2674,lon:-97.7434,alt:550,pitch:-22,heading:30,buildingHeight:80},{name:"Pennybacker Bridge",lat:30.3451,lon:-97.7951,alt:500,pitch:-25,heading:90,buildingHeight:40},{name:"The Jenga Tower",lat:30.2642,lon:-97.75,alt:500,pitch:-18,heading:45,buildingHeight:60},{name:"UT Tower",lat:30.2862,lon:-97.7394,alt:500,pitch:-22,heading:180,buildingHeight:50}]},sf:{name:"San Francisco",groundElevation:15,viewBounds:{southwest:{lat:37.7,lng:-122.53},northeast:{lat:37.84,lng:-122.35}},pois:[{name:"Golden Gate Bridge",lat:37.8199,lon:-122.4783,alt:1400,pitch:-20,heading:45,buildingHeight:100},{name:"Transamerica Pyramid",lat:37.7952,lon:-122.4028,alt:500,pitch:-25,heading:30,buildingHeight:85},{name:"Salesforce Tower",lat:37.7897,lon:-122.3972,alt:680,pitch:-25,heading:330,buildingHeight:100},{name:"Alcatraz Island",lat:37.8267,lon:-122.423,alt:800,pitch:-30,heading:0,buildingHeight:20},{name:"Coit Tower",lat:37.8024,lon:-122.4058,alt:420,pitch:-30,heading:45,buildingHeight:30}]},nyc:{name:"New York",groundElevation:10,viewBounds:{southwest:{lat:40.477,lng:-74.259},northeast:{lat:40.918,lng:-73.7}},pois:[{name:"Statue of Liberty",lat:40.6892,lon:-74.0445,alt:450,pitch:-25,heading:315,buildingHeight:45},{name:"Empire State Building",lat:40.7484,lon:-73.9857,alt:850,pitch:-12,heading:30,buildingHeight:130,buildingBounds:{height:443,width:130,depth:75}},{name:"One World Trade Center",lat:40.7127,lon:-74.0134,alt:850,pitch:-25,heading:0,buildingHeight:170},{name:"Brooklyn Bridge",lat:40.7061,lon:-73.9969,alt:850,pitch:-25,heading:45,buildingHeight:40},{name:"Chrysler Building",lat:40.7516,lon:-73.9755,alt:700,pitch:-20,heading:225,buildingHeight:100}]},tokyo:{name:"Tokyo",groundElevation:40,viewBounds:{southwest:{lat:35.52,lng:139.55},northeast:{lat:35.9,lng:139.92}},pois:[{name:"Tokyo Tower",lat:35.6586,lon:139.7454,alt:850,pitch:-25,heading:0,buildingHeight:110},{name:"Tokyo Skytree",lat:35.7101,lon:139.8107,alt:900,pitch:-25,heading:30,buildingHeight:200},{name:"Imperial Palace",lat:35.6852,lon:139.7528,alt:900,pitch:-35,heading:0,buildingHeight:20},{name:"Senso-ji Temple",lat:35.7148,lon:139.7967,alt:400,pitch:-30,heading:180,buildingHeight:25},{name:"Mode Gakuen Cocoon Tower",lat:35.6929,lon:139.6925,alt:350,pitch:-20,heading:30,buildingHeight:70}]},london:{name:"London",groundElevation:15,viewBounds:{southwest:{lat:51.28,lng:-.51},northeast:{lat:51.7,lng:.33}},pois:[{name:"Tower Bridge",lat:51.5055,lon:-.0754,alt:400,pitch:-25,heading:270,buildingHeight:65},{name:"The Shard",lat:51.5045,lon:-.0865,alt:850,pitch:-20,heading:0,buildingHeight:100},{name:"Big Ben / Parliament",lat:51.5007,lon:-.1246,alt:600,pitch:-25,heading:180,buildingHeight:50},{name:"St. Paul's Cathedral",lat:51.5138,lon:-.0984,alt:400,pitch:-30,heading:270,buildingHeight:55},{name:"The Gherkin",lat:51.5145,lon:-.0803,alt:350,pitch:-20,heading:30,buildingHeight:60}]},paris:{name:"Paris",groundElevation:35,viewBounds:{southwest:{lat:48.815,lng:2.224},northeast:{lat:48.902,lng:2.47}},pois:[{name:"Eiffel Tower",lat:48.8584,lon:2.2945,alt:750,pitch:-25,heading:315,buildingHeight:150},{name:"Arc de Triomphe",lat:48.8738,lon:2.295,alt:400,pitch:-28,heading:45,buildingHeight:25},{name:"Notre-Dame",lat:48.853,lon:2.3499,alt:400,pitch:-25,heading:225,buildingHeight:35},{name:"Sacré-Cœur",lat:48.8867,lon:2.3431,alt:400,pitch:-30,heading:180,buildingHeight:40},{name:"Louvre Pyramid",lat:48.8606,lon:2.3376,alt:500,pitch:-35,heading:0,buildingHeight:10}]},dubai:{name:"Dubai",groundElevation:5,viewBounds:{southwest:{lat:24.95,lng:54.9},northeast:{lat:25.35,lng:55.55}},pois:[{name:"Burj Khalifa",lat:25.1972,lon:55.2744,alt:600,pitch:-20,heading:200,buildingHeight:270},{name:"Burj Al Arab",lat:25.1412,lon:55.1853,alt:500,pitch:-25,heading:90,buildingHeight:100},{name:"Palm Jumeirah",lat:25.1124,lon:55.139,alt:1200,pitch:-40,heading:0,buildingHeight:20},{name:"Dubai Frame",lat:25.235,lon:55.3003,alt:400,pitch:-25,heading:270,buildingHeight:75},{name:"Museum of the Future",lat:25.2197,lon:55.2806,alt:350,pitch:-20,heading:30,buildingHeight:35}]},dc:{name:"Washington DC",groundElevation:10,viewBounds:{southwest:{lat:38.79,lng:-77.12},northeast:{lat:38.995,lng:-76.91}},pois:[{name:"US Capitol",lat:38.8897,lon:-77.0091,alt:550,pitch:-25,heading:270,buildingHeight:45},{name:"Washington Monument",lat:38.8895,lon:-77.0353,alt:500,pitch:-30,heading:0,buildingHeight:85},{name:"Lincoln Memorial",lat:38.8893,lon:-77.0502,alt:400,pitch:-25,heading:90,buildingHeight:20},{name:"Pentagon",lat:38.8711,lon:-77.0559,alt:800,pitch:-40,heading:0,buildingHeight:20},{name:"Jefferson Memorial",lat:38.8814,lon:-77.0365,alt:400,pitch:-30,heading:0,buildingHeight:25}]},tallinn:{name:"Tallinn",groundElevation:15,viewBounds:{southwest:{lat:59.36,lng:24.6},northeast:{lat:59.52,lng:24.92}},pois:[{name:"Viru Square",lat:59.4366,lon:24.7527,alt:450,pitch:-28,heading:60,buildingHeight:25},{name:"Old Town / Raekoja plats",lat:59.4372,lon:24.7452,alt:400,pitch:-30,heading:180,buildingHeight:20},{name:"Teatri väljak",lat:59.4344,lon:24.7514,alt:400,pitch:-25,heading:220,buildingHeight:25},{name:"Port of Tallinn",lat:59.4445,lon:24.7675,alt:700,pitch:-30,heading:90,buildingHeight:20},{name:"Ülemiste",lat:59.421,lon:24.792,alt:600,pitch:-28,heading:45,buildingHeight:30}]}},ho=Object.freeze({heightM:18e6,pitchDeg:-90,durationS:2.8});function _m(e,t={}){const n=e.camera.positionCartographic,i=Cesium.Math.toDegrees(n.longitude),o=Cesium.Math.toDegrees(n.latitude);return e.camera.cancelFlight(),e.camera.flyTo({destination:Cesium.Cartesian3.fromDegrees(i,o,ho.heightM),orientation:{heading:0,pitch:Cesium.Math.toRadians(ho.pitchDeg),roll:0},duration:To(t.duration)||ho.durationS,endTransform:Cesium.Matrix4.IDENTITY,complete:t.onComplete,cancel:t.onCancel}),{latitude:o,longitude:i,heightM:ho.heightM}}const qN=Object.entries(Ot).map(([e,t])=>({id:e,name:t.name,lat:t.pois[0].lat,lon:t.pois[0].lon}));function ji(e,t,n,i={}){var w;const{range:o=500,pitch:r=-30,heading:s=0,buildingHeight:a=30,groundElevation:c=0,duration:l=3,onStart:u=null,onComplete:h=null,onCancel:d=null,buildingBounds:f=null}=i,p=Cesium.Cartographic.fromDegrees(n,t),g=(w=e.scene.globe)==null?void 0:w.getHeight(p),_=g!=null&&g>0?g:c,m=eD(f),b=m?_+m.height/2:_+a,C=Cesium.Cartesian3.fromDegrees(n,t,b),y=m?tD(m):0,v=m?Math.max(nD(e,y),y*1.35):o,M=new Cesium.HeadingPitchRange(Cesium.Math.toRadians(s),Cesium.Math.toRadians(r),v);if(typeof u=="function")try{u()}catch{}return e.camera.flyToBoundingSphere(new Cesium.BoundingSphere(C,y),{offset:M,duration:l,complete:()=>{if(e.camera.lookAt(C,M),e.camera.lookAtTransform(Cesium.Matrix4.IDENTITY),typeof h=="function")try{h()}catch{}},cancel:()=>{if(typeof d=="function")try{d()}catch{}}}),{targetPosition:C,boundingRadius:y,range:v,buildingBounds:m}}function bm(e,t,n={}){const i=Ot[t];if(!i)return null;if(n.viewMode==="overview"&&!To(n.range)&&i.viewBounds)return tw(e,i.viewBounds,{duration:n.duration,onStart:n.onStart,onComplete:n.onComplete,onCancel:n.onCancel,navigationMode:"city-overview"});const o=i.pois[0];return ji(e,o.lat,o.lon,{range:o.alt,pitch:o.pitch,heading:o.heading||0,buildingHeight:o.buildingHeight||30,buildingBounds:o.buildingBounds||null,groundElevation:i.groundElevation||0,...n})}function Cm(e,t,n,i={}){const o=Ot[t];if(!o||!o.pois[n])return null;const r=o.pois[n];return ji(e,r.lat,r.lon,{range:r.alt,pitch:r.pitch,heading:r.heading||0,buildingHeight:r.buildingHeight||30,buildingBounds:r.buildingBounds||null,groundElevation:o.groundElevation||0,...i})}const WN=new Set(["the","a","an","at","of","in","on","to"]);function n_(e){return new Set(String(e||"").toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(t=>t&&!WN.has(t)))}function KM(e){const t=n_(e);if(t.size===0)return null;let n=null;for(const[i,o]of Object.entries(Ot))o.pois.forEach((r,s)=>{const a=n_(r.name);if(a.size<2)return;[...a].every(l=>t.has(l))&&(!n||a.size>n.size)&&(n={cityId:i,index:s,size:a.size})});return n?{cityId:n.cityId,index:n.index}:null}const dr=Object.freeze({cancelled:!0});async function wa(e,t,n={}){const{placeSearch:i=So,signal:o}=n;o==null||o.throwIfAborted();const r=typeof n.beforeFly=="function"?n.beforeFly:null,s=()=>!(o!=null&&o.aborted)&&(r===null||r()!==!1),a=await i.geocode(t,{bias:zM(e),signal:o});o==null||o.throwIfAborted();const c=a.place;let l=c==null?void 0:c.lat,u=c==null?void 0:c.lng,h=(c==null?void 0:c.label)||t,d=(c==null?void 0:c.types)||[],f=(c==null?void 0:c.viewport)||null;const p=c!=null&&c.exact?null:await(n.recoverNearView||jM)(e,t,c&&!a.fallbackUsed?{lat:l,lon:u}:null,o);if(o==null||o.throwIfAborted(),p)l=p.lat,u=p.lon,h=p.label||h,d=p.types||[],f=KN(p.viewport)||f;else if(!c)return null;const g=To(n.range),_=To(n.duration)||3,m=YM(d),b=n.viewMode==="overview";if(!g&&!n.forceClose&&(JN(m)||b)){const w=m==="area-overview"?ew(f):null;if((w==null?void 0:w.mode)==="swath")return s()?(ji(e,w.centerLat,w.centerLng,{range:w.rangeM,pitch:w.pitchDeg,heading:w.headingDeg,buildingHeight:0,duration:_,onStart:n.onStart,onComplete:n.onComplete,onCancel:n.onCancel}),{label:h,navigationMode:"natural-region-swath",rangeM:w.rangeM}):dr;const k=!b&&(m==="city-overview"||m==="region-overview")?JM(f,l,u,d):f,T=tw(e,k,{duration:_,navigationMode:m,beforeFly:s,onStart:n.onStart,onComplete:n.onComplete,onCancel:n.onCancel});if(T===dr)return dr;if(T)return{label:h,navigationMode:m,rangeM:null}}const y=m==="precise-place"?await oD(l,u,t,n.boundaries):null,v=g||ZN(m);if(!s())return dr;const M=ji(e,(y==null?void 0:y.lat)??l,(y==null?void 0:y.lon)??u,{range:v,pitch:iD(y),heading:30,buildingHeight:30,buildingBounds:y,duration:_,onStart:n.onStart,onComplete:n.onComplete,onCancel:n.onCancel});return{label:h,navigationMode:g?"explicit-range":n.forceClose?m.replace("-overview","-close"):m,rangeM:Math.round(M.range)}}function KN(e){const t=e==null?void 0:e.low,n=e==null?void 0:e.high;return[t==null?void 0:t.latitude,t==null?void 0:t.longitude,n==null?void 0:n.latitude,n==null?void 0:n.longitude].every(Number.isFinite)?{southwest:{lat:t.latitude,lng:t.longitude},northeast:{lat:n.latitude,lng:n.longitude}}:null}function YM(e){const t=new Set(e);return t.has("country")||t.has("administrative_area_level_1")||t.has("administrative_area_level_2")?"region-overview":t.has("locality")||t.has("postal_town")?"city-overview":t.has("sublocality")||t.has("sublocality_level_1")||t.has("neighborhood")||t.has("postal_code")?"neighborhood-close":t.has("route")||t.has("intersection")?"street-corridor":t.has("park")||t.has("natural_feature")||t.has("campus")||t.has("university")||t.has("airport")||t.has("stadium")||t.has("amusement_park")||t.has("zoo")||t.has("cemetery")||t.has("shopping_mall")?"area-overview":"precise-place"}const XM=400,YN=28e4,XN=-35,ac=111.32;function ou(e){const t=e==null?void 0:e.southwest,n=e==null?void 0:e.northeast;if(!Number.isFinite(t==null?void 0:t.lat)||!Number.isFinite(t==null?void 0:t.lng)||!Number.isFinite(n==null?void 0:n.lat)||!Number.isFinite(n==null?void 0:n.lng))return null;const i=n.lat-t.lat,o=((n.lng-t.lng)%360+360)%360,r=(t.lat+n.lat)/2;let s=t.lng+o/2;s>180&&(s-=360);const a=Math.abs(i)*ac,c=o*ac*Math.cos(Cesium.Math.toRadians(r));return{latSpanDeg:i,lonSpanDeg:o,latSpanKm:a,lonSpanKm:c,spanKm:Math.hypot(a,c),centerLat:r,centerLng:s}}function i_(e){return((e+180)%360+360)%360-180}const QM=300,ZM=.15,o_=20;function QN(e,t,n,i){const o=Cesium.Math.toRadians(n-e),r=Cesium.Math.toRadians(i-t),s=Math.sin(o/2)**2+Math.cos(Cesium.Math.toRadians(e))*Math.cos(Cesium.Math.toRadians(n))*Math.sin(r/2)**2;return 6371*2*Math.asin(Math.min(1,Math.sqrt(s)))}function JM(e,t,n,i=[]){if(Array.isArray(i)&&i.includes("country"))return e;const o=ou(e);if(!o||o.spanKm<=QM||!Number.isFinite(t)||!Number.isFinite(n)||QN(t,n,o.centerLat,o.centerLng)<=o.spanKm*ZM)return e;const s=o_/ac,a=Math.max(.05,Math.cos(Cesium.Math.toRadians(t))),c=o_/(ac*a),l=u=>((u+180)%360+360)%360-180;return{southwest:{lat:Math.max(-89.9,t-s),lng:l(n-c)},northeast:{lat:Math.min(89.9,t+s),lng:l(n+c)}}}function ew(e){const t=ou(e);if(!t)return null;const{latSpanKm:n,lonSpanKm:i,spanKm:o,centerLat:r,centerLng:s}=t;return o<=XM?{mode:"full",spanKm:o}:{mode:"swath",spanKm:o,centerLat:r,centerLng:s,rangeM:YN,pitchDeg:XN,headingDeg:n>=i?0:90}}function ZN(e){return e==="area-overview"?1400:e==="street-corridor"?900:250}function JN(e){return e==="region-overview"||e==="city-overview"||e==="area-overview"||e==="street-corridor"}function tw(e,t,n={}){const{duration:i=3,beforeFly:o=null,onStart:r=null,onComplete:s=null,onCancel:a=null,navigationMode:c="overview"}=n,l=t==null?void 0:t.southwest,u=t==null?void 0:t.northeast;if(!Number.isFinite(l==null?void 0:l.lat)||!Number.isFinite(l==null?void 0:l.lng)||!Number.isFinite(u==null?void 0:u.lat)||!Number.isFinite(u==null?void 0:u.lng))return!1;const h=ou(t),d=Math.max(.05,Math.abs(h.latSpanDeg)*.12),f=Math.max(.05,h.lonSpanDeg*.12),p=h.lonSpanDeg+f*2,g=Math.max(-89.9,l.lat-d),_=Math.min(89.9,u.lat+d),m=p>=360?Cesium.Rectangle.fromDegrees(-180,g,180,_):Cesium.Rectangle.fromDegrees(i_(l.lng-f),g,i_(l.lng+h.lonSpanDeg+f),_);if(typeof o=="function"&&o()===!1)return dr;if(typeof r=="function")try{r()}catch{}return e.camera.flyTo({destination:m,duration:i,endTransform:Cesium.Matrix4.IDENTITY,complete:()=>{if(typeof s=="function")try{s()}catch{}},cancel:()=>{if(typeof a=="function")try{a()}catch{}}}),{targetPosition:Cesium.Cartesian3.fromDegrees(h.centerLng,h.centerLat,0),boundingRadius:0,range:null,viewBounds:t,navigationMode:c}}function eD(e){if(!e)return null;const t=To(e.height),n=To(e.width),i=To(e.depth);return!t||!n||!i?null:{...e,height:t,width:n,depth:i}}function tD(e){const t=e.height/2,n=e.width/2,i=e.depth/2;return Math.hypot(t,n,i)*1.18}function nD(e,t){const n=e.camera.frustum,i=Number(n==null?void 0:n.fov)||Cesium.Math.toRadians(60),o=Math.max(.5,Number(n==null?void 0:n.aspectRatio)||1),r=2*Math.atan(Math.tan(i/2)*o),c=Math.min(i,r)*.57/2;return t/Math.sin(c)*1.05}function iD(e){if(!e)return-25;const t=Math.max(e.width,e.depth),n=e.height/Math.max(t,1);return n>=2.5?-12:n>=1.2?-22:n<=.35?-45:-32}async function oD(e,t,n,i=ts.boundaries){const o=` + [out:json][timeout:10]; + ( + way(around:180,${e},${t})["building"]; + relation(around:180,${e},${t})["building"]; + way(around:180,${e},${t})["man_made"]; + relation(around:180,${e},${t})["man_made"]; + way(around:180,${e},${t})["tourism"="attraction"]; + relation(around:180,${e},${t})["tourism"="attraction"]; + ); + out tags center geom; + `,r=new AbortController,s=window.setTimeout(()=>r.abort(),6e3);try{const a=await i.query(o,{signal:r.signal});return rD(Array.isArray(a)?a:[],e,t,n)}catch{return null}finally{window.clearTimeout(s)}}function rD(e,t,n,i){const o=s_(i),r=[];for(const c of e){const l=sD(c);if(l.length<3)continue;const u=aD(l,t);if(!u||u.width<2||u.depth<2)continue;const h=c.tags||{},d=c.center||cD(l),f=bh(t,n,d.lat,d.lon),p=s_([h.name,h["name:en"],h.official_name,h.alt_name].filter(Boolean).join(" ")),g=uD(o,p),_=dD(n,t,l),m=lD(h,u);r.push({lat:d.lat,lon:d.lon,height:m,width:u.width,depth:u.depth,osmName:h.name||h["name:en"]||null,osmType:c.type,osmId:c.id,score:g*1e3+(_?500:0)-f})}if(!r.length)return null;r.sort((c,l)=>l.score-c.score);const{score:s,...a}=r[0];return a}function sD(e){return Array.isArray(e.geometry)?e.geometry.filter(t=>Number.isFinite(t==null?void 0:t.lat)&&Number.isFinite(t==null?void 0:t.lon)):Array.isArray(e.members)?e.members.flatMap(t=>Array.isArray(t.geometry)?t.geometry.filter(n=>Number.isFinite(n==null?void 0:n.lat)&&Number.isFinite(n==null?void 0:n.lon)):[]):[]}function aD(e,t){const n=e.map(c=>c.lat),i=e.map(c=>c.lon),o=Math.min(...n),r=Math.max(...n),s=Math.min(...i),a=Math.max(...i);return{width:bh(t,s,t,a),depth:bh(o,s,r,s)}}function lD(e,t){const n=r_(e.height||e["building:height"]);if(n)return n;const i=Number.parseFloat(e["building:levels"]),o=r_(e["roof:height"])||0;return Number.isFinite(i)&&i>0?i*3.3+o:Math.max(12,Math.min(80,Math.max(t.width,t.depth)*.8))}function r_(e){if(e==null)return 0;const t=Number.parseFloat(String(e).replace(",","."));return!Number.isFinite(t)||t<=0?0:/\b(ft|feet|foot)\b/i.test(String(e))?t*.3048:t}function cD(e){const t=e.reduce((n,i)=>({lat:n.lat+i.lat,lon:n.lon+i.lon}),{lat:0,lon:0});return{lat:t.lat/e.length,lon:t.lon/e.length}}function s_(e){return new Set(String(e||"").toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g," ").trim().split(/\s+/).filter(t=>t.length>2))}function uD(e,t){let n=0;for(const i of e)t.has(i)&&n++;return n}function dD(e,t,n){let i=!1;for(let o=0,r=n.length-1;ot!=a.lat>t&&e<(a.lon-s.lon)*(t-s.lat)/(a.lat-s.lat||Number.EPSILON)+s.lon&&(i=!i)}return i}function bh(e,t,n,i){const r=111320*Math.cos(Cesium.Math.toRadians((e+n)/2));return Math.hypot((n-e)*111320,(i-t)*r)}function To(e){const t=Number(e);return Number.isFinite(t)&&t>0?t:0}const hD=Object.freeze(Object.defineProperty({__proto__:null,CANCELLED_SEARCH:dr,CITY_POIS:Ot,GLOBE_VIEW:ho,LOCATIONS:qN,PLACE_ANCHOR_OFFSET_RATIO:ZM,PLACE_VIEWPORT_MAX_SPAN_KM:QM,REGION_SWATH_SPAN_KM:XM,findPoiByName:KM,flyToGlobeView:_m,flyToLandmark:ji,flyToPOI:Cm,flyToPresetLocation:bm,geocodeNavigationMode:YM,placeFramingViewport:JM,regionFramingPlan:ew,searchAndFlyTo:wa,viewportMetrics:ou},Symbol.toStringTag,{value:"Module"}));function fD({surface:e,source:t}){const{terrain:n,groundFloor:i,meshFloor:o}=e;return xS({source:t,services:{sprites:Ki,activation:SS,overlays:ui,locations:hD,picking:rn,terrain:n,ground:i,mesh:o,focus:ma,render:Pt}})}const a_=80,nw=Object.freeze(` +AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ +CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR +GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO +JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR +MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO +RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV +TW TZ UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS YE YT ZA ZM ZW +`.trim().split(/\s+/)),mD=new Set(nw),Ar=typeof(Intl==null?void 0:Intl.DisplayNames)=="function"?new Intl.DisplayNames(["en"],{type:"region"}):null;function ym(e){return String(e||"").normalize("NFKC").toLocaleLowerCase("en").replace(/[‐‑‒–—-]+/g," ").replace(/[.’']/g,"").replace(/&/g," and ").replace(/\s+/g," ").trim()}const vm=new Map;for(const e of nw){const t=Ar==null?void 0:Ar.of(e);t&&t!==e&&vm.set(ym(t),e)}for(const[e,t]of Object.entries({america:"US","united states of america":"US",usa:"US","u s":"US","u s a":"US",britain:"GB","great britain":"GB",uk:"GB","u k":"GB","south korea":"KR","north korea":"KP",russia:"RU",vietnam:"VN","czech republic":"CZ","ivory coast":"CI",laos:"LA",bolivia:"BO",tanzania:"TZ",moldova:"MD",brunei:"BN","cape verde":"CV","the netherlands":"NL",turkey:"TR",turkiye:"TR",myanmar:"MM",burma:"MM",uae:"AE",holland:"NL",swaziland:"SZ","east timor":"TL","cabo verde":"CV",vatican:"VA"}))vm.set(ym(e),t);function pD(e){return(Ar==null?void 0:Ar.of(e))||e}function lc(e){if(e==null||e==="")return Object.freeze({valid:!0,empty:!0,code:"",name:""});if(typeof e!="string"||e.length>a_)return Object.freeze({valid:!1,empty:!1,code:"",name:""});const t=e.normalize("NFKC").trim().replace(/\s+/g," ");if(!t||t.length>a_||/[\u0000-\u001f\u007f]/.test(t)||!/^[\p{L}\p{M}.&'’()\-\s]+$/u.test(t))return Object.freeze({valid:!1,empty:!1,code:"",name:""});const n=t.toUpperCase(),i=mD.has(n)?n:vm.get(ym(t))||"";return Object.freeze(i?{valid:!0,empty:!1,code:i,name:pD(i)}:{valid:!1,empty:!1,code:"",name:""})}const Yn="radio:",gD="/api/radio/stations",_D=250,bD=1,CD=2.5,l_=5,Ha=8,Mm=750,Gu=Mm,yD=.018,c_=12e3,vD=10080*60*1e3,MD=300*1e3,iw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Tn="radio",wm=64,wD=16,ED=32,u_=48,Xn=5e7,TD=13e6,kD=Object.freeze({cohortLimit:wm,collisionCapacity:96,moving:!1}),AD=Object.freeze([[0,-Ha],[Ha,0],[0,Ha],[-Ha,0],[6,-6],[6,6],[-6,6],[-6,-6]]),cc="all",ow=2e6,d_=Object.freeze([["alternative","Alternative"],["ambient","Ambient"],["blues","Blues"],["classical","Classical"],["country","Country"],["dance","Dance"],["electronic","Electronic"],["folk","Folk"],["funk","Funk"],["hip hop","Hip-Hop"],["house","House"],["indie","Indie"],["jazz","Jazz"],["latin","Latin"],["metal","Metal"],["oldies","Oldies"],["pop","Pop"],["punk","Punk"],["r&b","R&B"],["reggae","Reggae"],["rock","Rock"],["soul","Soul"],["techno","Techno"],["trance","Trance"],["world","World"]]),h_=Object.freeze({news:["news","current affairs","journalism"],talk:["talk","spoken word","interview","podcast"],weather:["weather","emergency","noaa"],"public-safety":["public safety","scanner","police","fire","ems","dispatch","emergency"],"aviation-marine":["aviation","air traffic","atc","airport","marine","maritime","coast guard"],"traffic-transit":["traffic","transit","transport","rail","metro"]}),Ds=Object.freeze({all:"#b9fbff",news:"#44adff",talk:"#f2b84b",weather:"#ff5c78","public-safety":"#ff8b4a","aviation-marine":"#a87cff","traffic-transit":"#ffd166",music:"#54d17a",other:"#9aa7b3"}),f_=Object.freeze({news:"NEWS",talk:"TALK",weather:"WEATHER","public-safety":"SAFETY","aviation-marine":"AIR / SEA","traffic-transit":"TRANSIT",music:"MUSIC",other:"OTHER"}),Uu=Object.freeze(["news","public-safety","weather","aviation-marine","traffic-transit","talk","music"]),Ch=.8,Hr=Object.freeze({instance:null,generation:null,updatedAt:null,stations:Object.freeze([]),stationIds:Object.freeze([])}),ID=650,RD=1800,m_=30,p_=typeof(Intl==null?void 0:Intl.Segmenter)=="function"?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;function LD({state:e,services:t,parts:n,source:i}){function o(l){const u=l.split(".");if(u.length!==4||u.some(g=>!/^\d{1,3}$/.test(g)))return!1;const h=u.map(Number);if(h.some(g=>g>255))return!0;const[d,f,p]=h;return d===0||d===10||d===127||d>=224||d===100&&f>=64&&f<=127||d===169&&f===254||d===172&&f>=16&&f<=31||d===192&&f===0||d===192&&f===88&&p===99||d===192&&f===168||d===198&&(f===18||f===19)||d===198&&f===51&&p===100||d===203&&f===0&&p===113}function r(l){if(typeof l!="string"||!l)return!1;try{const u=new URL(l),h=u.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"");return u.protocol!=="https:"||u.username||u.password||!h?!1:!(h==="localhost"||h.endsWith(".localhost")||h.endsWith(".local")||o(h)||h.includes(":"))}catch{return!1}}function s(l){const u=(d,f,{allowEmpty:p=!0}={})=>typeof d=="string"&&d.length<=f&&(p||d.trim().length>0)&&!/[\u0000-\u001f\u007f]/.test(d)&&d===d.trim()&&!/\s{2,}/.test(d),h=(d,f,p)=>Array.isArray(d)&&d.length<=f&&d.every(g=>u(g,p,{allowEmpty:!1}));return!!(l&&iw.test(l.id)&&u(l.name,140,{allowEmpty:!1})&&Number.isFinite(l.lat)&&l.lat>=-90&&l.lat<=90&&Number.isFinite(l.lon)&&l.lon>=-180&&l.lon<=180&&r(l.streamUrl)&&(l.homepage===null||r(l.homepage))&&h(l.tags,24,80)&&h(l.languages,8,40)&&u(l.state,80)&&u(l.country,80)&&u(l.countryCode,2)&&(l.countryCode===""||lc(l.countryCode).valid)&&l.metadataTrust==="untrusted-community"&&u(l.codec,16,{allowEmpty:!1})&&/^(?:MP3|AAC(?:\+|-LC|-HE)?|HE-AAC)$/i.test(l.codec)&&(l.bitrate===null||Number.isInteger(l.bitrate)&&l.bitrate>=8&&l.bitrate<=1024))}function a(l){return Object.freeze({id:l.id,name:l.name,lat:l.lat,lon:l.lon,streamUrl:l.streamUrl,homepage:l.homepage,tags:Object.freeze([...l.tags]),languages:Object.freeze([...l.languages]),state:l.state,country:l.country,countryCode:l.countryCode,metadataTrust:l.metadataTrust,codec:l.codec,bitrate:l.bitrate})}function c(l,u,h,d){if(!Number.isSafeInteger(u)||u<1||typeof l!="string"||!l)return null;const f=Object.freeze(d.map(a));return Object.freeze({instance:l,generation:u,updatedAt:h,stations:f,stationIds:Object.freeze(f.map(p=>p.id))})}return{isNonGlobalRadioIpv4:o,isSafeRadioHttpsUrl:r,isValidRadioDirectoryStation:s,freezeRadioStation:a,createAcceptedCatalogSnapshot:c}}function PD({state:e,services:t,parts:n,source:i}){function o(h,d){const f=String(h||"").replace(/\s+/g," ").trim(),p=p_?[...p_.segment(f)].map(g=>g.segment):Array.from(f);return p.length<=d?f:`${p.slice(0,Math.max(1,d-1)).join("").trimEnd()}…`}function r(h){return String(h||"").replace(/^[\s|:·\-–—]+|[\s|:·\-–—]+$/g,"").replace(/\s+/g," ").replace(/\s+\([^()]{1,40}\)$/,"").replace(/\s+FM$/i,"").trim()}function s(h){const d=String((h==null?void 0:h.name)||"").replace(/\s+/g," ").trim();if(!d)return"";let f=null,p="";const _=[...d.matchAll(/(\d{2,3}(?:\.\d{1,2})?)\s*FM\b/gi)].find(C=>{const y=Number(C[1]);return y>=64&&y<=108});if(_){f=_[1];const C=r(d.slice(0,_.index)),y=r(d.slice(_.index+_[0].length));p=C||y}else{const C=d.match(/^(\d{2,3}\.\d{1,2})(?:\s+|\s*[-–—]\s*)(.+)$/),y=Number(C==null?void 0:C[1]);C&&y>=87.5&&y<=108&&(f=C[1],p=r(C[2].split(/\s+[-–—]\s+/)[0]))}if(!f)return o(d,m_);const m=`${f} FM`;if(!p)return m;const b=m_-m.length-3;return`${m} — ${o(p,b)}`}function a(h,d){return!(h!=null&&h.id)||!(h!=null&&h.name)||!d?null:{id:`selected:${h.id}`,position:d,variant:"selected",selected:!0,protected:!0,paintLane:"selected",collisionGroup:"ambient-label",priority:Number.MAX_SAFE_INTEGER,title:s(h),accent:n.model.radioCategoryColor(n.model.radioStationCategoryId(h)),interactive:!1,anchorRadiusPx:20,minAnchorGapPx:8,verticalOnly:!0,placement:"above",gapPx:8,edgeFade:"keyhole",horizonCull:!0,terrainOcclusion:!1,maxDistance:Xn}}function c({id:h,position:d,text:f,accent:p,stationCount:g}){return!h||!d||!f?null:{id:`cluster:${h}`,position:d,variant:"label",paintLane:"ambient-label",collisionGroup:"ambient-label",priority:Math.max(1,Number(g)||1),title:f,accent:p||Ds.other,interactive:!1,anchorRadiusPx:Math.min(13,6+Math.log2(Math.max(1,Number(g)||1))*.8),minAnchorGapPx:4,verticalOnly:!0,placement:"above",gapPx:6,stateless:!0,edgeFade:"none",horizonCull:!0,terrainOcclusion:!1,maxDistance:Xn,distanceScale:{near:1e5,nearValue:1.08,far:Xn,farValue:.92}}}function l({station:h,position:d,priority:f=1}){return!(h!=null&&h.id)||!(h!=null&&h.name)||!d?null:{id:`station:${h.id}`,position:d,variant:"label",paintLane:"ambient-label",collisionGroup:"ambient-label",priority:Math.max(1,Number(f)||1),title:s(h),accent:n.model.radioCategoryColor(n.model.radioStationCategoryId(h)),interactive:!1,anchorRadiusPx:9,minAnchorGapPx:4,verticalOnly:!0,placement:"above",gapPx:5,stateless:!0,edgeFade:"keyhole",horizonCull:!0,terrainOcclusion:!1,maxDistance:Xn,distanceScale:{near:1e5,nearValue:1,far:Xn,farValue:.86}}}function u(h=Ds.other){return``}return{compactRadioLabelText:o,cleanRadioLabelName:r,radioGlobeLabel:s,createRadioSelectedOverlayEntry:a,createRadioClusterOverlayEntry:c,createRadioSingletonOverlayEntry:l,radioSelectionBracketSvg:u}}function xD({state:e,services:t,parts:n,source:i}){function o(h){const d=Math.max(0,Number(h)||0);return d>=ow?wD:d>=25e4?ED:u_}function r(h,d=u_){const f=p=>{const g=Number(p==null?void 0:p.distanceM);return Number.isFinite(g)?g:Number.POSITIVE_INFINITY};return[...h||[]].sort((p,g)=>{var _,m;return f(p)-f(g)||String(((_=p==null?void 0:p.station)==null?void 0:_.id)||(p==null?void 0:p.id)||"").localeCompare(String(((m=g==null?void 0:g.station)==null?void 0:m.id)||(g==null?void 0:g.id)||""))}).slice(0,Math.max(0,Math.floor(Number(d)||0)))}function s(h,d=wm){return[...h||[]].sort((f,p)=>(Number(p==null?void 0:p.stationCount)||0)-(Number(f==null?void 0:f.stationCount)||0)||String((f==null?void 0:f.id)||"").localeCompare(String((p==null?void 0:p.id)||""))).slice(0,Math.max(0,Math.floor(Number(d)||0)))}function a(h,d=[],f=null){const p=(Array.isArray(h)?h:[]).map((k,T)=>{const I=[...new Set(((k==null?void 0:k.stationIds)||[]).map(S=>String(S)))].sort(),R=String((k==null?void 0:k.id)||`membership:${I.join("|")}`);return{...k,_reconcileIndex:T,_reconcileMembershipId:R,_reconcileCanonicalKey:`${R}\0${I.join("\0")}`,stationIds:I}}),g=new Map;for(const k of Array.isArray(d)?d:[]){const T=String((k==null?void 0:k.identityId)||(k==null?void 0:k.id)||"");if(!T)continue;g.has(T)||g.set(T,new Set);const I=g.get(T);for(const R of(k==null?void 0:k.stationIds)||[])I.add(String(R))}const _=[...g].map(([k,T])=>({identityId:k,stationIds:[...T].sort()})).filter(k=>k.stationIds.length).sort((k,T)=>k.identityId.localeCompare(T.identityId)),m=new Map;for(let k=0;k<_.length;k+=1)for(const T of _[k].stationIds)m.has(T)||m.set(T,[]),m.get(T).push(k);const b=[],C=new Map,y=new Map;for(let k=0;k0?R/A:0,F=S>0?R/S:0;b.push({currentIndex:k,priorIndex:I,overlap:R,score:L,similarity:F}),C.set(k,Math.max(C.get(k)||0,R)),y.set(I,Math.max(y.get(I)||0,R))}}const v=b.filter(k=>k.overlap===C.get(k.currentIndex)&&k.overlap===y.get(k.priorIndex));v.sort((k,T)=>T.overlap-k.overlap||T.score-k.score||T.similarity-k.similarity||p[k.currentIndex]._reconcileCanonicalKey.localeCompare(p[T.currentIndex]._reconcileCanonicalKey)||_[k.priorIndex].identityId.localeCompare(_[T.priorIndex].identityId));const M=new Map,w=new Set;for(const k of v){const T=_[k.priorIndex].identityId;M.has(k.currentIndex)||w.has(T)||(M.set(k.currentIndex,_[k.priorIndex].identityId),w.add(T))}const E=new Map;if(typeof f=="function"){const k=p.map((T,I)=>({candidate:T,index:I})).filter(({index:T})=>!M.has(T)).sort((T,I)=>T.candidate._reconcileCanonicalKey.localeCompare(I.candidate._reconcileCanonicalKey));for(const{candidate:T,index:I}of k)E.set(I,String(f(T,I)||""))}return p.map((k,T)=>{const I=k._reconcileMembershipId,R=M.get(T),S=E.get(T)||"",A=R||S||I,{_reconcileIndex:L,_reconcileMembershipId:F,_reconcileCanonicalKey:P,...O}=k;return{...O,membershipId:I,identityId:A,id:A}})}function c(){e._clusterOverlayIdentities=[]}function l(){return{entryCount:0,selectedCount:0,singletonTexts:[],singletonIds:[],clusterTexts:[],clusterIds:[],clusterMemberships:[]}}function u(h,d){const f=new Set((d||[]).map(p=>String((p==null?void 0:p.id)||"")).filter(Boolean));return(h||[]).filter(p=>Array.isArray(p==null?void 0:p.stationIds)&&p.stationIds.length>0&&p.stationIds.every(g=>f.has(String(g))))}return{radioSingletonLabelLimit:o,selectRadioSingletonCandidates:r,selectRadioClusterCandidates:s,reconcileRadioClusterCandidates:a,resetRadioClusterOverlayIdentities:c,emptyRadioOverlayDiagnostics:l,retainRadioClusterIdentitiesForStations:u}}function FD({state:e,services:t,parts:n,source:i}){function o(u){return Math.min(1,Math.max(0,Number(u)||0))}function r(){e._volumeTransitionGeneration+=1,e._voiceRestoreTimer&&clearTimeout(e._voiceRestoreTimer),e._voiceRestoreTimer=null,e._volumeFadeFrame&&(typeof cancelAnimationFrame=="function"?cancelAnimationFrame(e._volumeFadeFrame):clearTimeout(e._volumeFadeFrame)),e._volumeFadeFrame=null}function s(u){return typeof requestAnimationFrame=="function"?requestAnimationFrame(u):setTimeout(()=>u(Date.now()),16)}function a(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function c(u){if(!n.interaction.radioPresentationAllowed())return!1;const h=o(u);return e._userVolume=h,n.playback.installAudio(),e._voiceDucked||(r(),e._voiceRestoring=!1,e._audio&&(e._audio.volume=h)),n.tuningNoise.syncTuningNoiseGain(),n.presentation.emitState(),!0}function l(u,{restoreDelayMs:h=ID,restoreDurationMs:d=RD}={}){const f=!!u;if(f===e._voiceDucked&&(f||e._voiceRestoring)||!f&&!e._voiceDucked&&!e._voiceRestoring&&(!e._audio||Math.abs(e._audio.volume-e._userVolume)<.001))return;if(r(),e._voiceDucked=f,e._voiceRestoring=!1,f){e._audio&&(e._audio.volume=0),n.tuningNoise.syncTuningNoiseGain(),n.presentation.emitState();return}if(!e._audio){n.tuningNoise.syncTuningNoiseGain(),e._voiceRestoring=!1,n.presentation.emitState();return}const p=e._volumeTransitionGeneration;n.tuningNoise.syncTuningNoiseGain(),e._voiceRestoring=!0,n.presentation.emitState();const g=()=>{if(e._voiceRestoreTimer=null,p!==e._volumeTransitionGeneration||e._voiceDucked||!e._audio)return;const m=a(),b=e._audio.volume,C=Math.max(0,Number(d)||0),y=v=>{if(p!==e._volumeTransitionGeneration||e._voiceDucked||!e._audio)return;const M=C===0?1:Math.min(1,Math.max(0,(v-m)/C)),w=M*M*(3-2*M);if(e._audio.volume=o(b+(e._userVolume-b)*w),M<1){e._volumeFadeFrame=s(y);return}e._volumeFadeFrame=null,e._voiceRestoring=!1,n.presentation.emitState()};e._volumeFadeFrame=s(y)},_=Math.max(0,Number(h)||0);_>0?e._voiceRestoreTimer=setTimeout(g,_):g()}return{clampRadioVolume:o,cancelRadioVolumeTransition:r,scheduleVolumeFrame:s,volumeClock:a,setRadioVolume:c,setRadioVoiceDucking:l}}function SD({state:e,services:t,parts:n,source:i}){const{isFullGlobeInsideKeyhole:o,GLOBE_ENTER_CLEARANCE_PX:r,projectEarthDiscToViewport:s,earthDiscScreenRadius:a,getKeyholeGeometry:c}=t.globe;function l(T,I,R=bD){if(!T||!I)return!0;const S=Number(I.x)-Number(T.x),A=Number(I.y)-Number(T.y),L=Number(I.z)-Number(T.z);if(![S,A,L].every(Number.isFinite))return!0;const F=Math.max(0,Number(R)||0);return S*S+A*A+L*L>F*F}function u(T){return Number.isFinite(T)&&Math.round(T)>=ow}function h(T,I={}){const R=Number(T==null?void 0:T.lat),S=Number(T==null?void 0:T.lon),A=Math.max(1,Number(I.height)||1),L=Number.isFinite(I.heading)?I.heading:0,F=Number.isFinite(I.pitch)?I.pitch:-Math.PI/2,P=Number.isFinite(I.roll)?I.roll:0;if(!Number.isFinite(R)||!Number.isFinite(S))return null;const O=Math.min(Math.PI/2,Math.max(.08,Math.abs(Math.min(-.001,F)))),$=(O>Math.PI/2-1e-6?0:Math.min(2e6,A/Math.max(.08,Math.tan(O))))/6378137,x=R*Math.PI/180,N=L+Math.PI,G=Math.asin(Math.sin(x)*Math.cos($)+Math.cos(x)*Math.sin($)*Math.cos(N)),V=((S*Math.PI/180+Math.atan2(Math.sin(N)*Math.sin($)*Math.cos(x),Math.cos($)-Math.sin(x)*Math.sin(G)))*180/Math.PI+540)%360-180;return{lat:G*180/Math.PI,lon:V,height:A,heading:L,pitch:F,roll:P}}function d(T){if(!T||o(T,!1))return!1;const I={...T,earthCenterX:T.keyholeCenterX,earthCenterY:T.keyholeCenterY};if(o(I,!1))return!0;if(![T.earthCenterX,T.earthCenterY,T.earthRadius,T.keyholeCenterX,T.keyholeCenterY].every(Number.isFinite)||T.earthRadius<=0)return!1;const S=Math.hypot(T.earthCenterX-T.keyholeCenterX,T.earthCenterY-T.keyholeCenterY);return T.earthRadius-S(I=e._viewer)==null?void 0:I.camera)()){var R;return T?{height:(R=T.positionCartographic)==null?void 0:R.height,heading:T.heading,pitch:T.pitch,roll:T.roll}:null}function g(T=e._viewer){return!!(T!=null&&T.camera)&&!T.trackedEntity}function _(T=e._viewer){var D,$;const I=T==null?void 0:T.camera,R=(D=T==null?void 0:T.scene)==null?void 0:D.canvas,S=(R==null?void 0:R.clientWidth)||(R==null?void 0:R.width),A=(R==null?void 0:R.clientHeight)||(R==null?void 0:R.height),L=I==null?void 0:I.positionCartographic;if(!I||!L||!(S>0)||!(A>0))return null;const F=s(T,S,A,e._radioEarthScreenCenter,e._radioEarthToCenter);let P=!1;if(F){if(!d(F))return null;P=o({...F,earthCenterX:F.keyholeCenterX,earthCenterY:F.keyholeCenterY},!1)}else{const x=a(Cesium.Cartesian3.magnitude(I.positionWC),A,($=I.frustum)==null?void 0:$.fovy),N=Cesium.Cartesian3.dot(I.directionWC,e._radioEarthToCenter)>0;if(!x||N)return null;const G=c(S,A);P=x+r<=G.radius}const O=f(L.height,P);return O==null?null:{destination:Cesium.Cartesian3.fromRadians(L.longitude,L.latitude,O),cameraState:{...p(I),height:O,heading:0,pitch:-Cesium.Math.PI_OVER_TWO,roll:0}}}function m(T){return!!(T&&T.generation===e._radioCameraNavigationGeneration&&e._enabled&&g(e._viewer))}function b(){!e._activeRadioCameraFlight||!g(e._viewer)||(e._activeRadioCameraFlight=null,e._viewer.camera.cancelFlight())}function C(){e._radioCameraNavigationGeneration+=1,b(),e._activeRadioCameraFlight=null}function y(T,I){var R;return!!(T&&I&&T.generation===e._radioCameraNavigationGeneration&&((R=T.target)==null?void 0:R.id)===I.id)}function v(T,I,R){if(!m(T))return!1;const S=++e._radioCameraFlightSequence;e._activeRadioCameraFlight={generation:T.generation,token:S};const A=L=>{var F;((F=e._activeRadioCameraFlight)==null?void 0:F.token)===S&&(e._activeRadioCameraFlight=null),L&&m(T)&&(R==null||R())};return e._viewer.camera.flyTo({...I,complete:()=>A(!0),cancel:()=>A(!1)}),!0}function M(T){if(!m(T)||!T.target)return!1;const I=h(T.target,T.cameraState);return I?(T.phase="focusing",v(T,{destination:Cesium.Cartesian3.fromDegrees(I.lon,I.lat,I.height),orientation:{heading:I.heading,pitch:I.pitch,roll:I.roll},duration:T.duration},()=>{T.phase="settled"})):!1}function w(T=null){const I=++e._radioCameraNavigationGeneration;if(!g(e._viewer)||!e._enabled)return null;b();const R=_(e._viewer);return{generation:I,phase:"idle",recentered:!1,recenterPlan:R,cameraState:(R==null?void 0:R.cameraState)||T||p(),target:null,duration:.35}}function E(T,I=.35,R=null,S=null){const A=S||w(R);if(!T||!m(A))return!1;if(A.target=T,A.duration=I,A.phase==="recentering")return!0;if(A.phase==="focusing"&&b(),A.recenterPlan&&!A.recentered){A.phase="recentering";const L=Math.min(.9,Math.max(.65,I));return v(A,{destination:A.recenterPlan.destination,orientation:{heading:A.cameraState.heading,pitch:A.cameraState.pitch,roll:A.cameraState.roll},duration:L,easingFunction:Cesium.EasingFunction.CUBIC_IN_OUT},()=>{A.recentered=!0,A.phase="idle",M(A)})}return M(A)}function k(T){return e._radioCameraNavigationGeneration+=1,!T||!g(e._viewer)?!1:(b(),e._viewer.camera.flyTo({destination:Cesium.Cartesian3.fromDegrees(T.lon,T.lat,85e3),duration:1.1}),!0)}return{radioCameraPositionChanged:l,radioViewIsGlobal:u,radioStationCameraPlan:h,radioGlobeNeedsRecentering:d,radioGlobeRecenterHeight:f,radioCameraState:p,radioCameraNavigationAllowed:g,radioGlobeRecenterPlan:_,radioCameraNavigationIsCurrent:m,cancelActiveRadioCameraFlight:b,invalidateRadioCameraNavigation:C,radioCameraNavigationOwnsSelection:y,startRadioCameraFlight:v,focusRadioNavigationTarget:M,beginRadioCameraNavigation:w,rotateRadioStationIntoView:E,focusStation:k}}function ND({state:e,services:t,parts:n,source:i}){function o(d){return String(d??"").trim().toLocaleLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").slice(0,80)}function r(d){return Array.isArray(d==null?void 0:d.tags)?d.tags.map(o).filter(Boolean):String((d==null?void 0:d.tags)??"").split(",").map(o).filter(Boolean)}function s(d,f){const p=r(d);return f.some(g=>p.some(_=>_===g||_.includes(g)))}function a(d){return d_.filter(([f])=>s(d,[f])).map(([f])=>f)}function c(d,f){return f==="all"?!0:f.startsWith("genre:")?a(d).includes(f.slice(6)):f==="music"?a(d).length>0||s(d,["music","hits","songs"]):f==="other"?!Object.entries(h_).some(([p])=>c(d,p))&&!c(d,"music"):s(d,h_[f]||[])}function l(d){const f=Array.isArray(d)?d:[],p=[{id:"all",label:"All"},{id:"news",label:"News"},{id:"talk",label:"Talk"},{id:"weather",label:"Weather / Emergency"},{id:"public-safety",label:"Public Safety"},{id:"aviation-marine",label:"Aviation / Marine"},{id:"traffic-transit",label:"Traffic / Transit"},{id:"music",label:"Music"}];for(const[g,_]of d_){const m=`genre:${g}`;f.some(b=>c(b,m))&&p.push({id:m,label:_})}return p.push({id:"other",label:"Other"}),p.map(g=>({...g,color:n.model.radioCategoryColor(g.id),count:f.filter(_=>c(_,g.id)).length}))}function u(d,f="all"){return(Array.isArray(d)?d:[]).filter(p=>c(p,f))}function h(d){return(Array.isArray(d==null?void 0:d.languages)?d.languages:[]).some(p=>{const g=o(p);return g==="en"||g==="eng"||g.startsWith("english")})}return{normalizeRadioTag:o,stationTags:r,hasTag:s,detectedGenres:a,stationMatchesRadioCategory:c,buildRadioCategories:l,filterRadioStations:u,isEnglishRadioStation:h}}function DD({state:e,services:t,parts:n,source:i}){function o(h="other"){const d=String(h||"other"),f=d.startsWith("genre:")?"music":d;return Ds[f]||Ds.other}function r(h="other",d=0){const f=String(h||"other"),p=f.startsWith("genre:")?"music":f,g=f_[p]||f_.other;return`${Math.max(0,Math.floor(Number(d)||0))} ${g}`}function s(h,d="all"){const f=String(d||"all");if(f!=="all")return f.startsWith("genre:")||Uu.includes(f)||f==="other"?f:"other";const p=new Map;for(const m of Array.isArray(h)?h:[]){const b=a(m);p.set(b,(p.get(b)||0)+1)}let g="other",_=0;for(const m of Uu){const b=p.get(m)||0;b>_&&(g=m,_=b)}return(p.get("other")||0)>_?"other":g}function a(h){return Uu.find(d=>n.categories.stationMatchesRadioCategory(h,d))||"other"}function c(h,d,f,p=null,g=p){return h===d&&!!f&&p===g}function l(h,d){if(!h||!d)return!1;for(const f of["id","name","lat","lon","streamUrl","homepage","state","country","countryCode","metadataTrust","codec","bitrate"])if(h[f]!==d[f])return!1;return["tags","languages"].every(f=>{const p=Array.isArray(h[f])?h[f]:[],g=Array.isArray(d[f])?d[f]:[];return p.length===g.length&&p.every((_,m)=>_===g[m])})}function u(h){return h&&e._tuningStationById.get(String(h))||null}return{radioCategoryColor:o,radioClusterBadgeText:r,radioClusterCategoryId:s,radioStationCategoryId:a,radioRequestIsCurrent:c,radioStationResolutionMatches:l,tuningResolutionStation:u}}function OD({state:e,services:t,parts:n,source:i}){function o(d,f){const p=Cesium.Math.toRadians(Number(f==null?void 0:f.lat)),g=Cesium.Math.toRadians(Number(f==null?void 0:f.lon)),_=Cesium.Math.toRadians(Number(d==null?void 0:d.lat)),m=Cesium.Math.toRadians(Number(d==null?void 0:d.lon));if(![p,g,_,m].every(Number.isFinite))return Number.POSITIVE_INFINITY;const b=_-p,C=m-g,y=Math.sin(b/2)**2+Math.cos(p)*Math.cos(_)*Math.sin(C/2)**2;return 2*Math.asin(Math.min(1,Math.sqrt(Math.max(0,y))))}function r(d,f,{preferEnglish:p=!1}={}){return(Array.isArray(d)?d:[]).map((g,_)=>({station:g,index:_,distance:o(g,f),languageTier:p&&!n.categories.isEnglishRadioStation(g)?1:0})).sort((g,_)=>g.languageTier-_.languageTier||g.distance-_.distance||g.index-_.index).map(({station:g})=>g)}function s(d,{categoryId:f="all",anchor:p=null,country:g="",stationQuery:_=""}={}){const m=lc(g);if(!m.valid)return[];const b=n.categories.normalizeRadioTag(_);let C=n.categories.filterRadioStations(d,f);return(m.code||m.name)&&(C=C.filter(y=>{const v=String((y==null?void 0:y.countryCode)||"").trim().toUpperCase(),M=lc(y==null?void 0:y.country);return m.code&&v===m.code||m.code&&M.valid&&M.code===m.code})),b&&(C=C.filter(y=>[y==null?void 0:y.id,y==null?void 0:y.name,y==null?void 0:y.state,y==null?void 0:y.country,y==null?void 0:y.countryCode,...Array.isArray(y==null?void 0:y.tags)?y.tags:[]].some(v=>n.categories.normalizeRadioTag(v).includes(b)))),p?r(C,p):C.slice()}function a(){return e._selectedId&&e._stationById.get(e._selectedId)||null}function c(){return e._tuningActive?n.model.tuningResolutionStation(e._tuningPreviewId):e._cancelledTuningPresentationStation||a()}function l(){return n.categories.filterRadioStations(e._stations,e._filter)}function u(){var m,b,C,y;const d=(m=e._viewer)==null?void 0:m.camera,f=(b=e._viewer)==null?void 0:b.scene;if(!d)return null;const p=Number((C=d.positionCartographic)==null?void 0:C.height);let g=null;const _=f==null?void 0:f.canvas;if(_&&typeof d.pickEllipsoid=="function"){const v=new Cesium.Cartesian2(_.clientWidth/2,_.clientHeight/2),M=d.pickEllipsoid(v,((y=f.globe)==null?void 0:y.ellipsoid)||Cesium.Ellipsoid.WGS84);M&&(g=Cesium.Cartographic.fromCartesian(M))}return g||(g=d.positionCartographic||null),g?{lat:Cesium.Math.toDegrees(g.latitude),lon:Cesium.Math.toDegrees(g.longitude),altitudeM:p,globalView:n.navigation.radioViewIsGlobal(p)}:null}function h(){const d=u();return r(l(),d,{preferEnglish:!!(d!=null&&d.globalView)})}return{radioAngularDistance:o,rankRadioStationsForViewport:r,rankRadioStationsForRequest:s,selectedStation:a,selectedPresentationStation:c,visibleStations:l,viewportRadioAnchor:u,rankedVisibleStations:h}}function BD({state:e,services:t,parts:n,source:i}){const{resolvePickId:o,isOwnedByOtherLayer:r,registerPickOwner:s,unregisterPickOwner:a}=t.picking,{setOverlaySourceVisible:c}=t.overlays;function l(g){var b;const _=[g==null?void 0:g.id,(b=g==null?void 0:g.primitive)==null?void 0:b.id],m=new Set;for(;_.length;){const C=_.shift();if(typeof C=="string"||typeof C=="number"){const y=String(C);if(y.startsWith(`${Yn}selected:`))return y.slice(`${Yn}selected:`.length);if(y.startsWith(Yn))return y.slice(Yn.length);continue}!C||typeof C!="object"||m.has(C)||(m.add(C),Array.isArray(C)?_.push(...C):(_.push(C.id),C.primitive&&_.push(C.primitive.id)))}return null}function u(g){var v;const _=(v=e._viewer)==null?void 0:v.scene;if(!_||!g)return null;const m=M=>{const w=l(M);return w&&e._stationById.has(w)?w:null},b=_.pick(g),C=m(b);if(C)return C;const y=o(b);if(y&&r("radio",y))return null;if(typeof _.drillPick=="function"){const M=_.drillPick(g,16)||[];for(const w of M){const E=m(w);if(E)return E}}for(const[M,w]of AD){const E=new Cesium.Cartesian2(g.x+M,g.y+w),k=_.pick(E),T=o(k);if(T&&r("radio",T))continue;const I=m(k);if(I)return I}return null}function h(){return e._managerLifecyclePresentation?e._enabled&&e._managerLifecyclePresentation.lifecycleState==="enabled"&&e._managerLifecyclePresentation.enabled&&!e._managerLifecyclePresentation.uncertain:e._enabled}function d(){const g=h();e._dataSource&&(e._dataSource.show=g),c(Tn,g),g?(f(),n.rendering.updateSelectionEntity(),n.rendering.updateRenderVisibility(),n.rendering.scheduleRadioOverlayPublish()):(p(),e._selectedEntity&&e._viewer&&e._viewer.entities.remove(e._selectedEntity),e._selectedEntity=null)}function f(){!e._viewer||e._clickHandler||(s("radio",g=>g.startsWith(Yn)),e._clickHandler=new Cesium.ScreenSpaceEventHandler(e._viewer.scene.canvas),e._clickHandler.setInputAction(g=>{if(!Bt()||!h())return;const _=u(g.position);_&&(e._playFallbackId=null,e._playFallbackFocus=null,n.selection.selectRadioStation(_,{autoplay:!0,origin:"user"}),typeof document<"u"&&document.dispatchEvent(new CustomEvent("gev:radio-selected",{detail:{stationId:_}})))},Cesium.ScreenSpaceEventType.LEFT_CLICK),e._horizonTimer=setInterval(()=>n.rendering.updateRenderVisibility({force:!1}),_D))}function p(){var g;a("radio"),(g=e._clickHandler)==null||g.destroy(),e._clickHandler=null,e._horizonTimer&&clearInterval(e._horizonTimer),e._horizonTimer=null}return{radioStationIdFromPick:l,pickedRadioStationAt:u,radioPresentationAllowed:h,syncRadioLifecyclePresentation:d,installInteraction:f,removeInteraction:p}}function VD({state:e,services:t,parts:n,source:i}){function o(f,p,g=Gu){const _=Math.min(Mm,Math.max(1,Math.floor(Number(g)||Gu)));return(Array.isArray(f)?f:[]).slice(0,_)}function r(){return e._acceptedCatalogSnapshot}function s(f=Gu){return!n.interaction.radioPresentationAllowed()||!e._acceptedCatalogSnapshot.stations.length?[]:o(n.queries.visibleStations(),n.queries.selectedStation(),f)}function a(){if(!n.interaction.radioPresentationAllowed()||!n.queries.visibleStations().length)return!1;const f=r();return!Number.isSafeInteger(f.generation)||!f.stations.length?!1:(e._tuningResolutionSnapshot=f,e._tuningStationById=new Map(e._tuningResolutionSnapshot.stations.map(p=>[p.id,p])),e._tuningUnavailableStationId=null,e._tuningActive=!0,e._tuningStatic=!1,e._tuningAwaitingStationId=null,e._cancelledTuningPresentationStation=null,e._tuningStartStationId=e._selectedId,e._tuningPreviewId=e._selectedId,n.tuningNoise.installTuningNoise(),n.playback.pauseRadioPlayback({origin:"user"}),n.tuningNoise.syncTuningNoiseGain(),n.presentation.emitState(),!0)}function c(f){if(!n.interaction.radioPresentationAllowed()||!e._tuningActive)return!1;const p=!!f;return p===e._tuningStatic||(e._tuningStatic=p,n.tuningNoise.syncTuningNoiseGain(),n.presentation.emitState()),!0}function l(f,{rotate:p=!0}={}){if(!n.interaction.radioPresentationAllowed()||!e._tuningActive)return!1;const g=n.model.tuningResolutionStation(f),_=(g==null?void 0:g.id)||null,m=_!==e._tuningPreviewId;if(e._tuningPreviewId=_,e._tuningStatic=!g,m)if(n.rendering.updateSelectionEntity(),g&&p){const b=n.navigation.radioCameraState();e._tuningCameraNavigation=n.navigation.beginRadioCameraNavigation(b),n.navigation.rotateRadioStationIntoView(g,.35,b,e._tuningCameraNavigation)}else p&&(e._tuningCameraNavigation=null,n.navigation.invalidateRadioCameraNavigation());return n.tuningNoise.syncTuningNoiseGain(),n.presentation.emitState(),!!g}function u(){!e._tuningActive&&!e._tuningStatic&&!e._tuningAwaitingStationId&&!e._tuningNoiseSource&&!e._cancelledTuningPresentationStation||n.tuningNoise.clearRadioTuningNoise()}function h(){if(!e._tuningActive)return!1;const f=n.model.tuningResolutionStation(e._tuningStartStationId);return n.tuningNoise.clearRadioTuningNoise({restoredStation:f}),!0}function d(f,{origin:p="programmatic"}={}){const g=n.model.tuningResolutionStation(f),_=e._stationById.get(String(f))||null,m=e._tuningResolutionSnapshot.generation;if(!n.interaction.radioPresentationAllowed()||!e._tuningActive||!g)return u(),Object.freeze({ok:!1,reason:"not-tuning",stationId:String(f||""),generation:m});if(!n.model.radioStationResolutionMatches(g,_)){const y=g.id;return e._selectedId=null,e._selectionGeneration+=1,n.tuningNoise.clearRadioTuningNoise({emit:!1}),e._tuningUnavailableStationId=y,n.presentation.emitState(),Object.freeze({ok:!1,reason:"station-unavailable",stationId:y,generation:m})}e._tuningActive=!1,e._tuningStatic=!0,e._tuningAwaitingStationId=g.id,e._tuningPreviewId=null,e._tuningStartStationId=null,e._tuningUnavailableStationId=null;const b=e._tuningCameraNavigation;e._tuningCameraNavigation=null,e._tuningResolutionSnapshot=Hr,e._tuningStationById=new Map,e._playFallbackId=null,e._playFallbackFocus=null,e._playFallbackOrigin="programmatic",e._playFallbackAttemptId=null,n.tuningNoise.syncTuningNoiseGain(),n.presentation.emitState();const C=n.selection.selectRadioStation(g.id,{autoplay:!0,focus:!1,origin:p,cameraNavigation:b});return Object.freeze({ok:C,reason:C?null:"station-unavailable",stationId:g.id,generation:m})}return{buildRadioTunerBand:o,captureRadioTuningResolutionSnapshot:r,getRadioTunerStations:s,beginRadioTuning:a,setRadioTuningStatic:c,previewRadioTuningStation:l,endRadioTuning:u,cancelRadioTuning:h,commitRadioTuningStation:d}}function HD({state:e,services:t,parts:n,source:i}){function o({tuningActive:l=!1,tuningStatic:u=!1,awaitingStationId:h=null,voiceDucked:d=!1}={}){return!!(u&&!d&&(l||h))}function r(){var l,u;if(e._tuningNoiseSource){try{e._tuningNoiseSource.stop()}catch{}try{e._tuningNoiseSource.disconnect()}catch{}}try{(l=e._tuningNoiseFilter)==null||l.disconnect()}catch{}try{(u=e._tuningNoiseGain)==null||u.disconnect()}catch{}e._tuningNoiseSource=null,e._tuningNoiseFilter=null,e._tuningNoiseGain=null}function s(){if(!e._tuningNoiseContext||!e._tuningNoiseGain)return;const u=o({tuningActive:e._tuningActive,tuningStatic:e._tuningStatic,awaitingStationId:e._tuningAwaitingStationId,voiceDucked:e._voiceDucked})?Math.min(yD,e._userVolume*.03):0,h=e._tuningNoiseContext.currentTime;e._tuningNoiseGain.gain.cancelScheduledValues(h),e._tuningNoiseGain.gain.setValueAtTime(e._tuningNoiseGain.gain.value,h),e._tuningNoiseGain.gain.linearRampToValueAtTime(u,h+.025)}function a(){var p,g;const l=globalThis.AudioContext||globalThis.webkitAudioContext;if(!l)return!1;e._tuningNoiseContext||(e._tuningNoiseContext=new l);const u=(g=(p=e._tuningNoiseContext).resume)==null?void 0:g.call(p);if(u!=null&&u.catch&&u.catch(()=>{}),e._tuningNoiseSource)return!0;const h=Math.max(1,Math.floor(e._tuningNoiseContext.sampleRate*.75)),d=e._tuningNoiseContext.createBuffer(1,h,e._tuningNoiseContext.sampleRate),f=d.getChannelData(0);for(let _=0;_{}),l&&n.presentation.emitState()}return{radioTuningStaticShouldPlay:o,stopTuningNoiseSource:r,syncTuningNoiseGain:s,installTuningNoise:a,clearRadioTuningNoise:c}}function $D({state:e,services:t,parts:n,source:i}){const{cachedGroundFloor:o}=t.ground,{clearOverlaySource:r,setOverlaySourceVisible:s,setOverlayEntries:a}=t.overlays,{governorRequestRender:c}=t.render;function l(m,b=CD){const C=o(m.lat,m.lon);return Cesium.Cartesian3.fromDegrees(m.lon,m.lat,(Number.isFinite(C)?C:0)+b)}function u(){e._selectedEntity&&e._viewer&&e._viewer.entities.remove(e._selectedEntity),e._selectedEntity=null;const m=n.queries.selectedPresentationStation();if(!n.interaction.radioPresentationAllowed()||!e._viewer||!m){f();return}const b=n.model.radioCategoryColor(n.model.radioStationCategoryId(m)),C=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(n.labels.radioSelectionBracketSvg(b))}`;e._selectedEntity=e._viewer.entities.add({id:`${Yn}selected:${m.id}`,position:l(m,l_),point:{pixelSize:14,color:Cesium.Color.fromCssColorString(b),outlineColor:Cesium.Color.BLACK,outlineWidth:2,disableDepthTestDistance:Number.POSITIVE_INFINITY,distanceDisplayCondition:new Cesium.DistanceDisplayCondition(0,Xn)},billboard:{image:C,width:40,height:40,horizontalOrigin:Cesium.HorizontalOrigin.CENTER,verticalOrigin:Cesium.VerticalOrigin.CENTER,disableDepthTestDistance:Number.POSITIVE_INFINITY,distanceDisplayCondition:new Cesium.DistanceDisplayCondition(0,Xn),scaleByDistance:new Cesium.NearFarScalar(1e5,1,12e6,.72)}}),f()}function h(){var m,b;return((b=(m=e._dataSource)==null?void 0:m.clustering)==null?void 0:b._clusterPointCollection)||null}function d(){var T,I,R,S,A;if(e._overlayPublishTimer=null,!n.interaction.radioPresentationAllowed()){n.clustering.resetRadioClusterOverlayIdentities(),e._overlayDiagnostics=n.clustering.emptyRadioOverlayDiagnostics(),r(Tn),s(Tn,!1);return}const m=[],b=n.queries.selectedPresentationStation();if(b){const L=n.labels.createRadioSelectedOverlayEntry(b,l(b,l_));L&&m.push(L)}const C=[],y=new Set,v=h();for(let L=0;L<((v==null?void 0:v.length)||0);L+=1){const F=v.get(L);if(!(F!=null&&F.show)||!F.position||!Array.isArray(F.id)||F.id.length<3)continue;const P=F.id.map($=>String(($==null?void 0:$.id)||"").slice(Yn.length)).filter($=>{const x=e._stationById.get($);return x&&n.categories.stationMatchesRadioCategory(x,e._filter)}).sort();if(P.length<3)continue;for(const $ of P)y.add($);const O=P.map($=>e._stationById.get($)),D=n.model.radioClusterCategoryId(O,e._filter);C.push({id:`${P[0]}:${P.at(-1)}:${P.length}`,stationIds:P,point:F,text:n.model.radioClusterBadgeText(D,P.length),accent:n.model.radioCategoryColor(D),stationCount:P.length})}const M=n.clustering.selectRadioClusterCandidates(C);e._clusterOverlayIdentities=n.clustering.reconcileRadioClusterCandidates(M,e._clusterOverlayIdentities,()=>`stable:${++e._clusterOverlayIdentitySequence}`);for(const L of e._clusterOverlayIdentities){const F=n.labels.createRadioClusterOverlayEntry({...L,position:()=>L.point.position});F&&m.push(F)}const w=(I=(T=e._viewer)==null?void 0:T.camera)==null?void 0:I.positionWC,E=Math.min(n.clustering.radioSingletonLabelLimit((A=(S=(R=e._viewer)==null?void 0:R.camera)==null?void 0:S.positionCartographic)==null?void 0:A.height),Math.max(0,wm-M.length)),k=n.clustering.selectRadioSingletonCandidates([...e._renderById.values()].filter(L=>{var F,P,O;return((F=L.entity)==null?void 0:F.show)&&((P=L.station)==null?void 0:P.id)!==(b==null?void 0:b.id)&&!y.has((O=L.station)==null?void 0:O.id)}).map(L=>({...L,distanceM:w?Cesium.Cartesian3.distance(w,L.position):Number.POSITIVE_INFINITY})),E);for(let L=0;LL.selected).length,singletonTexts:m.filter(L=>L.id.startsWith("station:")).map(L=>L.title),singletonIds:m.filter(L=>L.id.startsWith("station:")).map(L=>L.id),clusterTexts:m.filter(L=>L.id.startsWith("cluster:")).map(L=>L.title),clusterIds:m.filter(L=>L.id.startsWith("cluster:")).map(L=>L.id),clusterMemberships:e._clusterOverlayIdentities.map(L=>({membershipId:L.membershipId,entryId:`cluster:${L.id}`}))}}function f(){e._overlayPublishTimer&&clearTimeout(e._overlayPublishTimer);const m=e._sessionGeneration;e._overlayPublishTimer=setTimeout(()=>{m===e._sessionGeneration&&d()},0)}function p({force:m=!0}={}){var v,M,w;if(!e._viewer||!e._dataSource)return;const b=(v=e._viewer.camera)==null?void 0:v.positionWC;if(!m&&!n.navigation.radioCameraPositionChanged(e._lastHorizonCameraPosition,b))return;e._lastHorizonCameraPosition=b?{x:b.x,y:b.y,z:b.z}:null,e._horizonScanCount+=1;const C=Vo(e._viewer.camera);let y=!1;for(const[E,k]of e._renderById){const I=n.categories.stationMatchesRadioCategory(k.station,e._filter)&&C.isPointVisible(k.position);k.entity.show!==I&&(y=!0),k.entity.show=I}if(e._selectedEntity){const E=(w=(M=e._selectedEntity.position)==null?void 0:M.getValue)==null?void 0:w.call(M,Cesium.JulianDate.now()),k=!E||C.isPointVisible(E);e._selectedEntity.show!==k&&(y=!0),e._selectedEntity.show=k}f(),y&&c("radio-horizon")}function g(m){e._tuningActive||(e._cancelledTuningPresentationStation=null),e._clusterOverlayIdentities=n.clustering.retainRadioClusterIdentitiesForStations(e._clusterOverlayIdentities,m),e._stations=Object.freeze([...m]),e._stationById=new Map(m.map(b=>[b.id,b])),e._categories=Object.freeze(n.categories.buildRadioCategories(m).map(b=>Object.freeze(b))),e._filter===cc&&!n.categories.filterRadioStations(m,cc).length&&(e._filter="all"),e._selectedId&&!e._stationById.has(e._selectedId)&&(e._audioStationId===e._selectedId&&n.playback.stopRadioPlayback(),e._selectedId=null),e._dataSource&&e._dataSource.entities.removeAll(),e._renderById.clear();for(const b of m){const C=l(b),y=n.model.radioCategoryColor(n.model.radioStationCategoryId(b)),v=e._dataSource.entities.add({id:`${Yn}${b.id}`,position:C,point:{pixelSize:13,color:Cesium.Color.fromCssColorString(y).withAlpha(.86),outlineColor:Cesium.Color.fromCssColorString("#071b25"),outlineWidth:1,disableDepthTestDistance:Number.POSITIVE_INFINITY,scaleByDistance:new Cesium.NearFarScalar(1e5,1.15,12e6,1),distanceDisplayCondition:new Cesium.DistanceDisplayCondition(0,Xn)}});e._renderById.set(b.id,{station:b,entity:v,position:C})}u(),p()}function _(){if(!e._dataSource||e._removeClusterListener)return;const m=e._dataSource.clustering;m.enabled=!0,m.pixelRange=42,m.minimumClusterSize=3,m.clusterPoints=!0,m.clusterLabels=!1,m.clusterBillboards=!1,e._removeClusterListener=m.clusterEvent.addEventListener((b,C)=>{var w;const y=[];for(const E of b){const k=String(E.id||"").slice(Yn.length),T=(w=e._renderById.get(k))==null?void 0:w.station;T&&y.push(T)}const v=n.model.radioClusterCategoryId(y,e._filter),M=Cesium.Color.fromCssColorString(n.model.radioCategoryColor(v));C.point.id=b,C.billboard.id=b,C.label.show=!1,C.label.text="",C.point.show=!0,C.point.pixelSize=Math.min(26,12+Math.log2(b.length)*1.6),C.point.color=M.withAlpha(.9),C.point.outlineColor=Cesium.Color.BLACK,C.point.outlineWidth=2,C.point.disableDepthTestDistance=Number.POSITIVE_INFINITY,C.point.distanceDisplayCondition=new Cesium.DistanceDisplayCondition(0,Xn),f()})}return{markerPosition:l,updateSelectionEntity:u,clusterPointCollection:h,publishRadioOverlayEntries:d,scheduleRadioOverlayPublish:f,updateRenderVisibility:p,reconcileStations:g,installClusterStyling:_}}function GD({state:e,services:t,parts:n,source:i}){function o(){return e._acceptedCatalogSnapshot}function r(){var d,f;const u=n.queries.visibleStations(),h=n.queries.selectedStation();return Object.freeze({enabled:e._enabled,loading:e._loading,stale:e._stale,degraded:e._degraded,error:e._error,updatedAt:e._updatedAt,filter:e._filter,categories:e._categories,acceptedCatalogGeneration:e._acceptedCatalogSnapshot.generation,presentationActive:n.interaction.radioPresentationAllowed(),stationCount:e._stations.length,filteredCount:u.length,selected:h,selectedIndex:h?u.findIndex(p=>p.id===h.id):-1,audioState:e._audioState,audioError:e._audioError,playingStationId:e._audioStationId,volume:e._userVolume,effectiveVolume:((d=e._audio)==null?void 0:d.volume)??(e._voiceDucked?0:e._userVolume),voiceDucked:e._voiceDucked,voiceRestoring:e._voiceRestoring,tuningActive:e._tuningActive,tuningStatic:e._tuningStatic,tuningAwaitingStationId:e._tuningAwaitingStationId,tuningPreviewStationId:e._tuningPreviewId,tuningRestoredStationId:((f=e._cancelledTuningPresentationStation)==null?void 0:f.id)||null,tuningCatalogGeneration:e._tuningResolutionSnapshot.generation,tuningUnavailableStationId:e._tuningUnavailableStationId})}function s(){const u=r();for(const h of e._listeners)try{h(u)}catch{}}function a(u){return typeof u!="function"?()=>{}:(e._listeners.add(u),u(r()),()=>e._listeners.delete(u))}function c(u){return typeof u!="function"?()=>{}:(e._playbackControlListeners.add(u),()=>e._playbackControlListeners.delete(u))}function l(u,h,d=(f=>(f=e._activePlaybackAttempt)==null?void 0:f.id)()||null){const p={action:u,origin:h,attemptId:d};for(const g of e._playbackControlListeners)try{g(p)}catch{}}return{getRadioAcceptedCatalogSnapshot:o,getRadioUIState:r,emitState:s,subscribeToRadio:a,subscribeToRadioPlaybackControls:c,emitPlaybackControl:l}}function UD({state:e,services:t,parts:n,source:i}){function o(p){const g=e._activePlaybackAttempt;return e._audio===p&&!!g&&g.generation===e._playGeneration&&g.stationId===e._audioStationId}function r({replace:p=!1}={}){if(e._audio&&!p||typeof Audio>"u")return;const g=e._audio;if(e._audio=null,g){try{g.pause()}catch{}try{g.removeAttribute("src")}catch{}try{g.load()}catch{}}const _=new Audio;e._audio=_,_.preload="none",_.volume=e._voiceDucked?0:e._userVolume,_.addEventListener("playing",()=>{e._audio===_&&o(_)&&["loading","buffering","playing"].includes(e._audioState)&&(e._audioState="playing",e._audioError=null,e._tuningAwaitingStationId===e._audioStationId&&n.tuningNoise.clearRadioTuningNoise({emit:!1}),n.presentation.emitState())}),_.addEventListener("pause",()=>{e._audio===_&&(e._audioState==="stopped"||e._audioState==="loading"||(e._audioState="paused",n.presentation.emitState()))}),_.addEventListener("waiting",()=>{e._audio===_&&o(_)&&["loading","buffering","playing"].includes(e._audioState)&&(e._audioState="buffering",n.presentation.emitState())}),_.addEventListener("error",()=>{if(e._audio!==_||!o(_)||!["loading","buffering","playing"].includes(e._audioState))return;const m=e._audioStationId,b=e._activePlaybackAttempt;s(m,b==null?void 0:b.origin,b==null?void 0:b.id)||(e._audioState="error",e._audioError="Broadcaster stream is unavailable or blocked by the browser.",n.presentation.emitState())})}function s(p,g=e._playFallbackOrigin||"programmatic",_=e._playFallbackAttemptId){const m=e._playFallbackId,b=m?e._stationById.get(m):null,C=e._playFallbackFocus;if(e._playFallbackId=null,e._playFallbackFocus=null,e._playFallbackOrigin="programmatic",e._playFallbackAttemptId=null,!b||m===p||e._selectedId!==p)return!1;const y=typeof C=="function"?C(b):C,v=y&&typeof y=="object"?y:null,M=v?!1:!!y;return n.selection.selectRadioStation(m,{autoplay:!0,focus:M,origin:g||"programmatic",attemptId:_,cameraNavigation:v}),!0}function a(p){Promise.resolve().then(()=>i.recordClick(p)).catch(()=>{})}async function c({origin:p="programmatic",attemptId:g=null}={}){var C,y;const _=n.queries.selectedStation();if(!n.interaction.radioPresentationAllowed()||!(_!=null&&_.streamUrl)||(e._tuningActive&&n.tuning.endRadioTuning(),r({replace:!0}),!e._audio))return!1;const m=++e._playGeneration,b=g||`radio-play-${++e._playAttemptSequence}`;e._activePlaybackAttempt={id:b,origin:p,stationId:_.id,streamUrl:_.streamUrl,generation:m},e._playFallbackId&&(e._playFallbackOrigin=p,e._playFallbackAttemptId=b),e._audioError=null,e._audioState="loading",(e._audioStationId!==_.id||e._audio.src!==_.streamUrl)&&(e._audio.pause(),e._audio.src=_.streamUrl,e._audioStationId=_.id),n.presentation.emitState();try{const v=e._audio.play();return v!=null&&v.then&&await v,m!==e._playGeneration||e._audioStationId!==_.id||((C=e._activePlaybackAttempt)==null?void 0:C.id)!==b?!1:(e._audioState="playing",e._tuningAwaitingStationId===_.id&&n.tuningNoise.clearRadioTuningNoise({emit:!1}),e._playFallbackId=null,e._playFallbackFocus=null,e._playFallbackOrigin="programmatic",e._playFallbackAttemptId=null,a(_.id),n.presentation.emitState(),p==="user"&&n.presentation.emitPlaybackControl("play",p,b),!0)}catch(v){return m!==e._playGeneration||((y=e._activePlaybackAttempt)==null?void 0:y.id)!==b||s(_.id,p,b)||(e._audioState="error",e._audioError=(v==null?void 0:v.name)==="NotAllowedError"?"Playback requires a direct click or tap.":"Broadcaster stream could not be started.",n.presentation.emitState()),!1}}function l({startPlayback:p,subscribe:g,getState:_,timeoutMs:m=c_}={}){return typeof p!="function"||typeof g!="function"||typeof _!="function"?Promise.resolve(!1):new Promise(b=>{let C=!1,y=!1,v=()=>{},M=null;const w=k=>{C||(C=!0,M&&clearTimeout(M),v(),b(!!k))},E=k=>{if(!(!y||!k)){if(!k.voiceDucked&&["loading","buffering","playing"].includes(k.audioState)){w(!1);return}k.audioState==="playing"&&k.playingStationId&&k.voiceDucked?w(!0):k.audioState==="error"&&w(!1)}};v=g(E),y=!0,M=setTimeout(()=>w(!1),Math.max(1,Number(m)||c_)),Promise.resolve().then(p).then(k=>{const T=_();E(T),!k&&!["loading","buffering","playing"].includes(T==null?void 0:T.audioState)&&w(!1)}).catch(()=>w(!1))})}function u(p={}){return e._voiceDucked?l({startPlayback:()=>c({origin:"voice",attemptId:p.attemptId}),subscribe:n.presentation.subscribeToRadio,getState:n.presentation.getRadioUIState,timeoutMs:p.timeoutMs}):Promise.resolve(!1)}function h({origin:p="programmatic",attemptId:g=null}={}){var m,b;if(g&&((m=e._activePlaybackAttempt)==null?void 0:m.id)!==g)return!1;const _=((b=e._activePlaybackAttempt)==null?void 0:b.id)||null;return n.tuning.endRadioTuning(),e._playGeneration+=1,e._playFallbackId=null,e._playFallbackFocus=null,e._playFallbackOrigin="programmatic",e._playFallbackAttemptId=null,e._activePlaybackAttempt=null,e._audio&&(e._audio.pause(),e._audio.removeAttribute("src"),e._audio.load()),e._audioStationId=null,e._audioState="stopped",e._audioError=null,n.presentation.emitState(),(p==="user"||p==="voice")&&n.presentation.emitPlaybackControl("stop",p,_),!0}function d({origin:p="programmatic"}={}){var g;if(["loading","playing","buffering"].includes(e._audioState))return Promise.resolve(f({origin:p}));if(!n.interaction.radioPresentationAllowed())return Promise.resolve(!1);if(!e._selectedId){const _=n.queries.rankedVisibleStations();if(!_.length)return Promise.resolve(!1);e._playFallbackId=((g=_[1])==null?void 0:g.id)||null,e._playFallbackFocus=!1,n.selection.selectRadioStation(_[0].id,{autoplay:!1,focus:!1})}return c({origin:p})}function f({origin:p="programmatic"}={}){var _,m;if(!["loading","playing","buffering"].includes(e._audioState))return!1;const g=((_=e._activePlaybackAttempt)==null?void 0:_.id)||null;return e._tuningAwaitingStationId&&!e._tuningActive&&n.tuning.endRadioTuning(),e._playGeneration+=1,e._playFallbackId=null,e._playFallbackFocus=null,e._playFallbackOrigin="programmatic",e._playFallbackAttemptId=null,e._activePlaybackAttempt=null,(m=e._audio)==null||m.pause(),e._audioState="paused",n.presentation.emitState(),(p==="user"||p==="voice")&&n.presentation.emitPlaybackControl("pause",p,g),!0}return{audioEventBelongsToActiveAttempt:o,installAudio:r,tryRadioFallback:s,recordDirectoryClick:a,playSelectedRadio:c,confirmRadioPlayback:l,playPreparedRadioForVoice:u,stopRadioPlayback:h,toggleRadioPlayback:d,pauseRadioPlayback:f}}function zD({state:e,services:t,parts:n,source:i}){const{warmGroundFloor:o}=t.ground;function r(h={}){var b,C,y,v;const d=Object.hasOwn(h,"filter")?kf(h.filter):null;if(Object.hasOwn(h,"filter")&&!d)return!1;const f=Object.hasOwn(h,"volume")?Number(h.volume):null;if(Object.hasOwn(h,"volume")&&!Number.isFinite(f))return!1;const p=f===null?null:n.volume.clampRadioVolume(f);let g=!1,_=!1,m=!1;if(d!==null&&(_=d!==e._filter,_&&(e._tuningActive||e._tuningAwaitingStationId)&&n.tuning.endRadioTuning(),m=!!e._cancelledTuningPresentationStation,e._cancelledTuningPresentationStation=null,e._filter=d,m&&n.rendering.updateSelectionEntity(),_&&n.clustering.resetRadioClusterOverlayIdentities(),g||(g=_||m)),p!==null&&p!==e._userVolume&&(e._userVolume=p,e._audio&&!e._voiceDucked&&(n.volume.cancelRadioVolumeTransition(),e._voiceRestoring=!1,e._audio.volume=p),n.tuningNoise.syncTuningNoiseGain(),g=!0),g&&n.interaction.radioPresentationAllowed()){if(n.rendering.updateRenderVisibility(),_&&((C=(b=e._dataSource)==null?void 0:b.clustering)!=null&&C.enabled)){const M=e._dataSource.clustering.clusterPoints;e._dataSource.clustering.clusterPoints=!M,e._dataSource.clustering.clusterPoints=M,(v=(y=e._viewer)==null?void 0:y.scene)==null||v.requestRender()}n.rendering.scheduleRadioOverlayPublish()}return n.presentation.emitState(),!0}function s(){return{filter:e._filter,volume:e._userVolume}}function a(h,{autoplay:d=!1,focus:f=!1,origin:p="programmatic",attemptId:g=null,cameraNavigation:_=null}={}){if(!n.interaction.radioPresentationAllowed())return!1;const m=e._stationById.get(String(h));if(!m)return!1;e._tuningUnavailableStationId=null,n.navigation.radioCameraNavigationOwnsSelection(_,m)||n.navigation.invalidateRadioCameraNavigation(),(e._tuningActive||e._tuningAwaitingStationId&&e._tuningAwaitingStationId!==m.id)&&n.tuning.endRadioTuning(),e._cancelledTuningPresentationStation=null,e._selectedId=m.id;const b=++e._selectionGeneration,C=e._sessionGeneration;return n.rendering.updateSelectionEntity(),o([{lat:m.lat,lon:m.lon}]),e._selectionTimer&&clearTimeout(e._selectionTimer),e._selectionTimer=setTimeout(()=>{e._selectionTimer=null,C===e._sessionGeneration&&b===e._selectionGeneration&&e._selectedId===m.id&&n.rendering.updateSelectionEntity()},1300),f&&n.navigation.focusStation(m),n.presentation.emitState(),d&&n.playback.playSelectedRadio({origin:p,attemptId:g}),!0}function c(h=1,{rotate:d=!1,stationIds:f=null,autoplay:p=!0,origin:g="programmatic"}={}){if(!n.interaction.radioPresentationAllowed())return!1;const _=Array.isArray(f)&&f.length?f.slice(0,Mm).map(M=>e._stationById.get(String(M))).filter(M=>M&&n.categories.stationMatchesRadioCategory(M,e._filter)):n.queries.rankedVisibleStations();if(!_.length)return!1;const m=_.findIndex(M=>M.id===e._selectedId),b=m<0?0:(m+(h<0?-1:1)+_.length)%_.length;e._playFallbackId=_.length>1?_[(b+1)%_.length].id:null;const C=d?n.navigation.radioCameraState():null,y=d?n.navigation.beginRadioCameraNavigation(C):null;e._playFallbackFocus=d?M=>(n.navigation.rotateRadioStationIntoView(M,.65,C,y),y):!1;const v=_[b];return d&&n.navigation.rotateRadioStationIntoView(v,.65,C,y),a(v.id,{autoplay:p,focus:!1,origin:g,cameraNavigation:y})}function l(h={},{autoplay:d=!0,origin:f="programmatic"}={}){var m;if(!n.interaction.radioPresentationAllowed())return null;const p=String(h.categoryId||"all"),g=e._categories.some(b=>b.id===p)?p:"all";u(g);const _=n.queries.rankRadioStationsForRequest(e._stations,{...h,categoryId:g,anchor:h.anchor||n.queries.viewportRadioAnchor()});return _.length?(e._playFallbackId=((m=_[1])==null?void 0:m.id)||null,e._playFallbackFocus=!1,a(_[0].id,{autoplay:d,focus:!1,origin:f}),_[0]):null}function u(h){var _,m,b,C;if(!n.interaction.radioPresentationAllowed())return!1;const f=e._categories.some(y=>y.id===h)?h:"all",p=f!==e._filter;p&&(e._tuningActive||e._tuningAwaitingStationId)&&n.tuning.endRadioTuning();const g=!!e._cancelledTuningPresentationStation;if(e._cancelledTuningPresentationStation=null,e._filter=f,g&&n.rendering.updateSelectionEntity(),p&&n.clustering.resetRadioClusterOverlayIdentities(),n.rendering.updateRenderVisibility(),p&&((m=(_=e._dataSource)==null?void 0:_.clustering)!=null&&m.enabled)){const y=e._dataSource.clustering.clusterPoints;e._dataSource.clustering.clusterPoints=!y,e._dataSource.clustering.clusterPoints=y,(C=(b=e._viewer)==null?void 0:b.scene)==null||C.requestRender()}return n.rendering.scheduleRadioOverlayPublish(),n.presentation.emitState(),!0}return{setRadioParams:r,getRadioParams:s,selectRadioStation:a,cycleRadioStation:c,selectRequestedRadioStation:l,setRadioFilter:u}}function jD({state:e,services:t,parts:n,source:i}){return{methods:{id:"radio",name:"Radio",icon:"◉",source:"Radio Browser",updateInterval:27e5,setLifecyclePresentation({lifecycleState:r=null,enabled:s=!1,uncertain:a=!1}={}){const c=s?"enabled":"disabled",l=["enabling","enabled","disabling","disabled"].includes(r)?r:c;e._managerLifecyclePresentation={lifecycleState:l,enabled:!!s,uncertain:!!a},n.interaction.syncRadioLifecyclePresentation(),n.presentation.emitState()},getStats(){return{count:e._stations.length,filtered:n.queries.visibleStations().length,selected:e._selectedId,playing:e._audioStationId,stale:e._stale,degraded:e._degraded,loading:e._loading,error:e._error,lastUpdate:e._updatedAt?Date.parse(e._updatedAt):null,horizonScans:e._horizonScanCount,overlayEntries:e._overlayDiagnostics.entryCount}},subscribe:n.presentation.subscribeToRadio,subscribePlaybackControls:n.presentation.subscribeToRadioPlaybackControls,getAcceptedCatalogSnapshot:n.presentation.getRadioAcceptedCatalogSnapshot,getUIState:n.presentation.getRadioUIState,getParams:n.selection.getRadioParams,setParams:n.selection.setRadioParams,getOverlayDiagnostics:()=>({...e._overlayDiagnostics,singletonTexts:[...e._overlayDiagnostics.singletonTexts],singletonIds:[...e._overlayDiagnostics.singletonIds],clusterTexts:[...e._overlayDiagnostics.clusterTexts],clusterIds:[...e._overlayDiagnostics.clusterIds],clusterMemberships:e._overlayDiagnostics.clusterMemberships.map(r=>({...r}))}),getTunerStations:n.tuning.getRadioTunerStations,beginTuning:n.tuning.beginRadioTuning,setTuningStatic:n.tuning.setRadioTuningStatic,previewTuningStation:n.tuning.previewRadioTuningStation,commitTuningStation:n.tuning.commitRadioTuningStation,cancelTuning:n.tuning.cancelRadioTuning,endTuning:n.tuning.endRadioTuning,setFilter:n.selection.setRadioFilter,selectStation:n.selection.selectRadioStation,selectRequestedStation:n.selection.selectRequestedRadioStation,cycleStation:n.selection.cycleRadioStation,togglePlayback:n.playback.toggleRadioPlayback,play:n.playback.playSelectedRadio,playForVoice:n.playback.playPreparedRadioForVoice,pause:n.playback.pauseRadioPlayback,stopPlayback:n.playback.stopRadioPlayback,setVolume:n.volume.setRadioVolume,setVoiceDucked:n.volume.setRadioVoiceDucking}}}function qD({state:e,services:t,parts:n,source:i}){const{clearOverlaySource:o,setOverlaySourceVisible:r}=t.overlays;return{methods:{init(a){e._sessionGeneration+=1,e._viewer=a,n.clustering.resetRadioClusterOverlayIdentities(),n.playback.installAudio(),e._dataSource||(e._dataSource=new Cesium.CustomDataSource("Radio stations"),a.dataSources.add(e._dataSource),n.rendering.installClusterStyling()),e._dataSource.show=!1,o(Tn),r(Tn,!1)},enable(){e._enabled=!0,n.interaction.syncRadioLifecyclePresentation(),n.presentation.emitState()},disable(){var a;e._sessionGeneration+=1,e._enabled=!1,n.navigation.invalidateRadioCameraNavigation(),e._requestGeneration+=1,(a=e._abortController)==null||a.abort(),e._abortController=null,e._loading=!1,e._selectionGeneration+=1,e._selectionTimer&&clearTimeout(e._selectionTimer),e._selectionTimer=null,n.interaction.removeInteraction(),n.tuning.endRadioTuning(),e._cancelledTuningPresentationStation=null,e._tuningUnavailableStationId=null,n.playback.stopRadioPlayback({origin:"layer-disable"}),e._dataSource&&(e._dataSource.show=!1),e._selectedEntity&&e._viewer&&e._viewer.entities.remove(e._selectedEntity),e._selectedEntity=null,e._overlayPublishTimer&&clearTimeout(e._overlayPublishTimer),e._overlayPublishTimer=null,n.clustering.resetRadioClusterOverlayIdentities(),e._overlayDiagnostics=n.clustering.emptyRadioOverlayDiagnostics(),o(Tn),r(Tn,!1),n.presentation.emitState()},destroy(){var c,l,u;this.disable(),n.volume.cancelRadioVolumeTransition(),e._voiceDucked=!1,e._voiceRestoring=!1,n.tuning.endRadioTuning();const a=(l=(c=e._tuningNoiseContext)==null?void 0:c.close)==null?void 0:l.call(c);a!=null&&a.catch&&a.catch(()=>{}),e._tuningNoiseContext=null,e._audio&&(e._audio.volume=Ch),e._audio=null,e._userVolume=Ch,(u=e._removeClusterListener)==null||u.call(e),e._removeClusterListener=null,e._dataSource&&e._viewer&&e._viewer.dataSources.remove(e._dataSource,!0),e._dataSource=null,o(Tn),e._stations=[],e._acceptedCatalogSnapshot=Hr,e._stationById.clear(),e._categories=Object.freeze([]),e._filter=cc,e._renderById.clear(),n.clustering.resetRadioClusterOverlayIdentities(),e._lastHorizonCameraPosition=null,e._horizonScanCount=0,e._selectedId=null,e._tuningPreviewId=null,e._tuningStartStationId=null,e._tuningResolutionSnapshot=Hr,e._tuningStationById=new Map,e._tuningUnavailableStationId=null,e._cancelledTuningPresentationStation=null,e._loading=!1,e._stale=!1,e._degraded=!1,e._error=null,e._updatedAt=null,e._managerLifecyclePresentation=null,e._viewer=null,n.presentation.emitState(),e._listeners.clear(),e._playbackControlListeners.clear()}}}}function WD({state:e,services:t,parts:n,source:i}){return{methods:{async update(){var a,c,l;if(!e._enabled)return;const r=++e._requestGeneration,s=e._sessionGeneration;(a=e._abortController)==null||a.abort(),e._abortController=new AbortController,e._loading=!0,e._error=null,n.presentation.emitState();try{const u=await i.getDirectory({signal:e._abortController.signal});if(!n.model.radioRequestIsCurrent(r,e._requestGeneration,e._enabled,s,e._sessionGeneration))return;if(!Array.isArray(u==null?void 0:u.stations))throw new Error("Radio directory response was malformed");const h=typeof u.updatedAt=="string"&&Number.isFinite(Date.parse(u.updatedAt))?u.updatedAt:null,d=h?Date.parse(h):NaN;if(!h||dDate.now()+MD||typeof u.stale!="boolean"||typeof u.degraded!="boolean")throw new Error("Radio directory freshness metadata was malformed");const f=u.stations,p=f.filter(n.catalogModel.isValidRadioDirectoryStation);if(!p.length)throw new Error("Radio directory returned no usable stations");if(p.length!==f.length)throw new Error("Radio directory response contained malformed stations");const g=u.acceptedGeneration;if(g!==null&&(!Number.isSafeInteger(g)||g<1))throw new Error("Radio directory generation metadata was malformed");if(!u.stale&&!u.degraded&&g===null)throw new Error("Radio directory omitted its accepted generation");const _=u.catalogInstance;if(!u.stale&&!u.degraded&&(typeof _!="string"||!_))throw new Error("Radio directory omitted its catalog instance");const m=e._stations.length>0&&(u.stale||u.degraded),C=((c=e._acceptedCatalogSnapshot)==null?void 0:c.instance)===_?(l=e._acceptedCatalogSnapshot)==null?void 0:l.generation:null;if(!u.stale&&!u.degraded&&Number.isSafeInteger(C)&&g0,e._degraded=e._stations.length>0}finally{r===e._requestGeneration&&s===e._sessionGeneration&&(e._loading=!1,e._abortController=null,n.presentation.emitState())}}}}}function KD({services:e}){const t={};return t._radioEarthScreenCenter=new Cesium.Cartesian2,t._radioEarthToCenter=new Cesium.Cartesian3,t._viewer=null,t._dataSource=null,t._enabled=!1,t._managerLifecyclePresentation=null,t._loading=!1,t._stale=!1,t._degraded=!1,t._error=null,t._updatedAt=null,t._acceptedCatalogSnapshot=Hr,t._stations=[],t._stationById=new Map,t._categories=[],t._renderById=new Map,t._filter=cc,t._selectedId=null,t._selectedEntity=null,t._selectionGeneration=0,t._selectionTimer=null,t._radioCameraNavigationGeneration=0,t._radioCameraFlightSequence=0,t._activeRadioCameraFlight=null,t._audio=null,t._audioStationId=null,t._audioState="stopped",t._audioError=null,t._userVolume=Ch,t._tuningActive=!1,t._tuningStatic=!1,t._tuningAwaitingStationId=null,t._tuningPreviewId=null,t._tuningStartStationId=null,t._tuningResolutionSnapshot=Hr,t._tuningStationById=new Map,t._tuningUnavailableStationId=null,t._cancelledTuningPresentationStation=null,t._tuningCameraNavigation=null,t._tuningNoiseContext=null,t._tuningNoiseSource=null,t._tuningNoiseFilter=null,t._tuningNoiseGain=null,t._voiceDucked=!1,t._voiceRestoring=!1,t._voiceRestoreTimer=null,t._volumeFadeFrame=null,t._volumeTransitionGeneration=0,t._playGeneration=0,t._playAttemptSequence=0,t._activePlaybackAttempt=null,t._playFallbackId=null,t._playFallbackFocus=null,t._playFallbackOrigin="programmatic",t._playFallbackAttemptId=null,t._clickHandler=null,t._horizonTimer=null,t._lastHorizonCameraPosition=null,t._horizonScanCount=0,t._abortController=null,t._requestGeneration=0,t._sessionGeneration=0,t._removeClusterListener=null,t._overlayPublishTimer=null,t._clusterOverlayIdentitySequence=0,t._clusterOverlayIdentities=[],t._overlayDiagnostics={entryCount:0,selectedCount:0,singletonTexts:[],singletonIds:[],clusterTexts:[],clusterIds:[],clusterMemberships:[]},t._listeners=new Set,t._playbackControlListeners=new Set,t}function YD({fetchImpl:e=(...t)=>globalThis.fetch(...t)}={}){return{async getDirectory({signal:t}={}){t==null||t.throwIfAborted();const n=await e(gD,{signal:t});if(!n.ok)throw new Error(`Radio directory returned ${n.status}`);const i=await n.json();return t==null||t.throwIfAborted(),i},async recordClick(t,{signal:n}={}){if(typeof t!="string"||!iw.test(t))throw new Error("Invalid radio station id");n==null||n.throwIfAborted();const i=await e(`/api/radio/click/${encodeURIComponent(t)}`,{method:"POST",signal:n});if(n==null||n.throwIfAborted(),!i.ok)throw new Error(`Radio click returned ${i.status}`)}}}function pi(e,t){const n=Math.max(0,Math.floor(Number(t)||0));if(!n)return{slot:0,max:0,locked:!1,stationIndex:-1,leftIndex:-1,rightIndex:-1};const i=Math.max(0,n-1),o=Math.min(i,Math.max(0,Math.round(Number(e)||0)));return{slot:o,max:i,locked:!0,stationIndex:o,leftIndex:o,rightIndex:o}}function XD(e,t){return pi(e,t)}function QD(e,t,n,i,o=7){const r=Math.max(0,Math.floor(Number(i)||0));if(!r)return{ratio:0,coordinate:0,stationIndex:-1};if(r===1)return{ratio:.5,coordinate:0,stationIndex:0};const s=Math.max(0,Number(o)||0),a=Math.max(1,(Number(n)||0)-s*2),c=Math.min(1,Math.max(0,((Number(e)||0)-(Number(t)||0)-s)/a)),l=c*(r-1);return{ratio:c,coordinate:l,stationIndex:Math.min(r-1,Math.max(0,Math.floor(l+.5)))}}function ZD(e,t,n,{insetPx:i=7,minPitchPx:o=14,speedFactor:r=5,overscan:s=2,labelStep:a=6}={}){const c=Math.max(0,Math.floor(Number(t)||0)),l=Math.max(0,Number(n)||0),u=Math.max(0,Number(i)||0),h=Math.max(0,l-u*2);if(!c)return{ticks:[],needleX:u,pitchPx:0,ratio:0};const d=Math.min(c-1,Math.max(0,Number(e)||0));if(c===1)return{ticks:[{stationIndex:0,channel:1,xPx:u+h/2,current:!0,label:"01"}],needleX:u+h/2,pitchPx:Math.max(1,Number(o)||14),ratio:.5};const f=h/(c-1),p=Math.max(Math.max(1,Number(o)||14),f*Math.max(1,Number(r)||5)),g=u+f*d,_=p*Math.max(0,Number(s)||0),m=Math.max(0,Math.ceil(d+(-_-g)/p)),b=Math.min(c-1,Math.floor(d+(l+_-g)/p)),C=Math.min(c-1,Math.max(0,Math.floor(d+.5))),y=Math.max(1,Math.floor(Number(a)||6)),v=Math.max(2,String(c).length),M=[];for(let w=m;w<=b;w+=1){const E=w+1,k=w===C,T=k||w===0||w===c-1||E%y===0;M.push({stationIndex:w,channel:E,xPx:g+p*(w-d),current:k,label:T?String(E).padStart(v,"0"):""})}return{ticks:M,needleX:g,pitchPx:p,ratio:d/(c-1)}}function JD({services:e,source:t}){var r;const n=KD({services:e}),i={},o={state:n,services:e,parts:i,source:t};return i.catalogModel=LD(o),i.labels=PD(o),i.clustering=xD(o),i.volume=FD(o),i.navigation=SD(o),i.categories=ND(o),i.model=DD(o),i.queries=OD(o),i.interaction=BD(o),i.tuning=VD(o),i.tuningNoise=HD(o),i.rendering=$D(o),i.presentation=GD(o),i.playback=UD(o),i.selection=zD(o),i.controls=jD(o),i.lifecycle=qD(o),i.ingestion=WD(o),Object.assign({},i.controls.methods,i.lifecycle.methods,(r=i.ingestion)==null?void 0:r.methods,{radioGlobeLabel:i.labels.radioGlobeLabel,createRadioSelectedOverlayEntry:i.labels.createRadioSelectedOverlayEntry,createRadioClusterOverlayEntry:i.labels.createRadioClusterOverlayEntry,createRadioSingletonOverlayEntry:i.labels.createRadioSingletonOverlayEntry,radioSingletonLabelLimit:i.clustering.radioSingletonLabelLimit,selectRadioSingletonCandidates:i.clustering.selectRadioSingletonCandidates,selectRadioClusterCandidates:i.clustering.selectRadioClusterCandidates,reconcileRadioClusterCandidates:i.clustering.reconcileRadioClusterCandidates,radioCameraPositionChanged:i.navigation.radioCameraPositionChanged,normalizeRadioTag:i.categories.normalizeRadioTag,stationMatchesRadioCategory:i.categories.stationMatchesRadioCategory,radioCategoryColor:i.model.radioCategoryColor,radioClusterBadgeText:i.model.radioClusterBadgeText,radioClusterCategoryId:i.model.radioClusterCategoryId,radioSelectionBracketSvg:i.labels.radioSelectionBracketSvg,radioStationCategoryId:i.model.radioStationCategoryId,buildRadioCategories:i.categories.buildRadioCategories,filterRadioStations:i.categories.filterRadioStations,isEnglishRadioStation:i.categories.isEnglishRadioStation,rankRadioStationsForViewport:i.queries.rankRadioStationsForViewport,rankRadioStationsForRequest:i.queries.rankRadioStationsForRequest,radioViewIsGlobal:i.navigation.radioViewIsGlobal,radioRequestIsCurrent:i.model.radioRequestIsCurrent,radioStationIdFromPick:i.interaction.radioStationIdFromPick,radioStationCameraPlan:i.navigation.radioStationCameraPlan,radioGlobeNeedsRecentering:i.navigation.radioGlobeNeedsRecentering,radioGlobeRecenterHeight:i.navigation.radioGlobeRecenterHeight,buildRadioTunerBand:i.tuning.buildRadioTunerBand,radioTuningStaticShouldPlay:i.tuningNoise.radioTuningStaticShouldPlay,getRadioAcceptedCatalogSnapshot:i.presentation.getRadioAcceptedCatalogSnapshot,radioStationResolutionMatches:i.model.radioStationResolutionMatches,getRadioUIState:i.presentation.getRadioUIState,subscribeToRadio:i.presentation.subscribeToRadio,subscribeToRadioPlaybackControls:i.presentation.subscribeToRadioPlaybackControls,getRadioTunerStations:i.tuning.getRadioTunerStations,beginRadioTuning:i.tuning.beginRadioTuning,setRadioTuningStatic:i.tuning.setRadioTuningStatic,radioCameraNavigationAllowed:i.navigation.radioCameraNavigationAllowed,previewRadioTuningStation:i.tuning.previewRadioTuningStation,endRadioTuning:i.tuning.endRadioTuning,cancelRadioTuning:i.tuning.cancelRadioTuning,commitRadioTuningStation:i.tuning.commitRadioTuningStation,playSelectedRadio:i.playback.playSelectedRadio,confirmRadioPlayback:i.playback.confirmRadioPlayback,playPreparedRadioForVoice:i.playback.playPreparedRadioForVoice,stopRadioPlayback:i.playback.stopRadioPlayback,toggleRadioPlayback:i.playback.toggleRadioPlayback,pauseRadioPlayback:i.playback.pauseRadioPlayback,setRadioVolume:i.volume.setRadioVolume,setRadioParams:i.selection.setRadioParams,getRadioParams:i.selection.getRadioParams,setRadioVoiceDucking:i.volume.setRadioVoiceDucking,selectRadioStation:i.selection.selectRadioStation,cycleRadioStation:i.selection.cycleRadioStation,selectRequestedRadioStation:i.selection.selectRequestedRadioStation,setRadioFilter:i.selection.setRadioFilter,retainRadioClusterIdentitiesForStations:i.clustering.retainRadioClusterIdentitiesForStations})}function eO({surface:e,source:t}){const{groundFloor:n}=e;return JD({source:t,services:{ground:n,picking:rn,overlays:ui,globe:Gf,render:Pt}})}const tO=8e3,nO=4500,iO=320,rw=3,oO=.6,yh=6e3,uc=80,rO=.35,sO=12,aO=!1,lO={motorway:25,trunk:20,primary:14,secondary:11,tertiary:8,residential:5,unclassified:5},cO={motorway:3,trunk:2.5,primary:2,secondary:1.5,tertiary:1,residential:.5,unclassified:.4},uO={motorway:6,trunk:6,primary:5,secondary:5,tertiary:4,residential:4,unclassified:4},sw={free:Cesium.Color.fromCssColorString("#2ecc71").withAlpha(.9),slow:Cesium.Color.fromCssColorString("#f0b23e").withAlpha(.9),jam:Cesium.Color.fromCssColorString("#e05252").withAlpha(.9)},g_=400,dO=9,hO=4,aw=.55,fO=.2,mO=Cesium.Color.fromCssColorString("#e05252"),__=Cesium.Color.fromCssColorString("#f0b23e").withAlpha(.2),lw=15e3,cw=.55,pO=2.2,gO=[1200,3e3],_O=[1500,5e3],bO=5,CO=64,yO=250,vO={surveillance:"mono",thermal:"mono",noir:"mono",retro:"crt"},Em={mono:{jam:{rgba:[255,255,255,.95],sizeDelta:3,outline:{rgba:[0,0,0,.9],width:2}},slow:{rgba:[255,255,255,.9],sizeDelta:1,outline:{rgba:[0,0,0,.85],width:1}},free:{rgba:[255,255,255,.85],sizeDelta:0,outline:{rgba:[0,0,0,.8],width:1}}},crt:{jam:{rgba:[255,59,48,.95],sizeDelta:3,outline:{rgba:[0,0,0,.9],width:2}},slow:{rgba:[255,179,0,.92],sizeDelta:2,outline:{rgba:[0,0,0,.85],width:1}},free:{rgba:[0,255,102,.9],sizeDelta:1,outline:null}}};function ns(e){return vO[e]||"normal"}function MO(e,t){var i;const n=(i=Em[ns(e)])==null?void 0:i[t];return n?n.rgba:null}function wO(e,t){var i;const n=(i=Em[ns(e)])==null?void 0:i[t];return n?n.sizeDelta:0}function uw(e,t){var i;const n=(i=Em[ns(e)])==null?void 0:i[t];return(n==null?void 0:n.outline)||null}function EO(e){return e==="free"||e==="slow"||e==="jam"?`veh_${e}`:e==="sim"?"veh_nodata":null}function TO({state:e,services:t,parts:n,source:i}){function o(){return e._presetDots==="on"&&ns(e._stylePreset)!=="normal"}function r(f){return e._presetDots==="on"?wO(e._stylePreset,f):0}function s(f,p){const g=uO[f]||4;return p&&o()?Math.max(g,bO):g}function a(){for(const f of["free","slow","jam"]){const p=e._presetDots==="on"?MO(e._stylePreset,f):null;e._activeBucketColors[f]=p?new Cesium.Color(p[0]/255,p[1]/255,p[2]/255,p[3]):sw[f]}}function c(f,p){const g=e._presetDots==="on"?uw(e._stylePreset,p):null;g?(f.outlineColor=new Cesium.Color(g.rgba[0]/255,g.rgba[1]/255,g.rgba[2]/255,g.rgba[3]),f.outlineWidth=g.width):f.outlineWidth=0}function l(){var f;if(a(),!(!e._dots.length&&!e._heatLineCount)){for(const p of e._dots){const g=p.bucket;g&&(p.point.color=e._activeBucketColors[g],p.point.pixelSize=s((f=p.road)==null?void 0:f.type,g)+(g==="jam"?1:0)+r(g),c(p.point,g))}n.rendering.rebuildHeatLines(n.rendering.visibleRoadsForAltitude(e._roads,e._lastRenderAltitude))}}function u(f){const p=typeof f=="string"&&f?f:"normal";p!==e._stylePreset&&(e._stylePreset=p,l())}function h(){return e._jamViz==="density"||e._jamViz==="both"}function d(){return e._jamViz==="heatline"||e._jamViz==="both"}return{presetProfileActive:o,activeSizeDelta:r,baseDotSize:s,refreshBucketColors:a,applyOutline:c,restyleDotsInPlace:l,setStylePreset:u,jamDensityOn:h,heatlineOn:d}}function kO({state:e,services:t,parts:n,source:i}){function o(){return{enabled:!!aO,marksInstalled:e._trafficTimingMoveEndRemover?1:0,traceObjectsCreated:e._trafficTimingTracesCreated,uncorrelatedTracesDropped:e._trafficTimingDroppedTraces}}function r(b,C,y){if(!b)return null;let v=b.passes.get(C);return v?y&&(v.source=y):(v={trace:b,pass:C,source:y||"unknown",proxyCache:null,proxyUpstream:null},b.passes.set(C,v)),v}function s(b,C,y={}){var v,M,w,E,k;return{trafficTiming:!0,segment:C,traceId:((v=b==null?void 0:b.trace)==null?void 0:v.id)??null,interactionId:((M=b==null?void 0:b.trace)==null?void 0:M.interactionId)??null,cameraChangeTimestamp:((w=b==null?void 0:b.trace)==null?void 0:w.cameraChangeTimestamp)??null,generation:((E=b==null?void 0:b.trace)==null?void 0:E.generation)??null,cacheKey:((k=b==null?void 0:b.trace)==null?void 0:k.cacheKey)??null,pass:(b==null?void 0:b.pass)||"load",source:(b==null?void 0:b.source)||"unknown",proxyCache:(b==null?void 0:b.proxyCache)||null,proxyUpstream:(b==null?void 0:b.proxyUpstream)||null,...y}}function a(b,C,y={},v){var T;const M=((T=b==null?void 0:b.trace)==null?void 0:T.id)??"interaction",w=(b==null?void 0:b.pass)||"load",E=`traffic:${M}:${w}:${C}:${++e._trafficTimingSequence}`,k={detail:s(b,C,y)};return Number.isFinite(v)&&(k.startTime=v),performance.mark(E,k),E}function c(b,C,y,v,M={}){performance.measure(`traffic:${b}:${(C==null?void 0:C.pass)||"load"}`,{start:y,end:v,detail:s(C,b,M)})}function l(b,C,y,v,M={}){const w=a(C,`${b}-aggregate-start`,M,y),E=a(C,`${b}-aggregate-end`,M,y+v);c(b,C,w,E,{aggregate:!0,...M})}function u(){const b=new Set(performance.getEntriesByType("mark").filter(y=>y.name.startsWith("traffic:")).map(y=>y.name)),C=new Set(performance.getEntriesByType("measure").filter(y=>y.name.startsWith("traffic:")).map(y=>y.name));for(const y of b)performance.clearMarks(y);for(const y of C)performance.clearMeasures(y)}function h(b){return`traffic:interaction:${b}:last-camera-change`}function d(){const b=++e._trafficTimingSequence,C=performance.now(),y={interactionId:b,timestamp:C};return e._trafficTimingCurrentAnchor=y,performance.mark(h(b),{startTime:C,detail:{trafficTiming:!0,segment:"last-camera-change",interactionId:b,timestamp:C}}),y}function f(){const b=++e._trafficTimingSequence,C=performance.now(),y=`traffic:diagnostic:${b}:camera-move-end`;performance.mark(y,{startTime:C,detail:{trafficTiming:!0,segment:"camera-move-end",diagnosticOnly:!0,cameraEventWaitTimeMs:500,fetchWaitsForMoveEnd:!1,timestamp:C}})}function p(b,C){var A,L,F,P,O;const y=r(C,(C==null?void 0:C.currentPass)||"full"),v=performance.now(),M=a(y,"road-parse-start",{},v);if(!b||!b.elements){const D=a(y,"road-parse-end",{roadCount:0});return c("road-parse-total",y,M,D,{roadCount:0}),l("sample-height-total",y,v,0,{sampleHeightCalls:0,sampleHeightMeanMs:0,distinctCells:0,roadCount:0}),l("waypoint-materialization",y,v,0,{roadCount:0}),[]}const w=[],E=new Set;let k=0,T=0,I=0;for(const D of b.elements){if(D.type!=="way"||!D.geometry||D.geometry.length<2)continue;const $=D.geometry.map(re=>[re.lon,re.lat]),x=$.length>uc?Math.ceil($.length/uc):1,N=[];for(let re=0;re<$.length;re+=x)N.push($[re]);const G=$[$.length-1],W=N[N.length-1];if((!W||W[0]!==G[0]||W[1]!==G[1])&&N.push(G),N.length<2)continue;const V=((A=D.tags)==null?void 0:A.highway)||"unclassified",H=(L=D.tags)==null?void 0:L.oneway,B=H==="yes"||H==="1"||H==="true"||((F=D.tags)==null?void 0:F.junction)==="roundabout"?1:H==="-1"?-1:0;let q=0;const z=N[0];if((O=(P=e._viewer)==null?void 0:P.scene)!=null&&O.sampleHeightSupported&&z){k+=1,E.add(`${z[1].toFixed(3)},${z[0].toFixed(3)}`);const re=Cesium.Cartographic.fromDegrees(z[0],z[1]),se=performance.now(),me=e._viewer.scene.sampleHeight(re);T+=performance.now()-se,Number.isFinite(me)&&(q=me)}const j=performance.now(),ne=N.map(([re,se])=>{const me=q+rw;return Cesium.Cartesian3.fromDegrees(re,se,me)}),ee=[];for(let re=0;re{var R;M==null||M(),(R=e._trafficTimingPostRenderRemovers)==null||R.delete(M);const k=performance.now(),T=a(b,"next-post-render",{renderId:y,...v},k),I=a(b,"first-visible-pixel",{renderId:y,visibleBoundary:"next-postRender",...v},k);c("render-to-post-render",b,C,T,{renderId:y,visibleBoundary:"next-postRender",...v}),c("last-camera-change-to-first-visible",b,b.trace.cameraChangeMark,I,{renderId:y,visibleBoundary:"next-postRender",...v})}),(E=e._trafficTimingPostRenderRemovers)==null||E.add(M)}async function m(b,C,y){const v=e._loadGeneration+1;if(!y||y!==e._trafficTimingCurrentAnchor){e._trafficTimingDroppedTraces+=1,await n.ingestion.loadRoadsForBounds(b,C);return}e._trafficTimingCurrentAnchor=null;const M=n.viewport.clampBounds(b),w={id:++e._trafficTimingSequence,interactionId:y.interactionId,cameraChangeTimestamp:y.timestamp,cameraChangeMark:h(y.interactionId),generation:v,cacheKey:`${M.south.toFixed(4)},${M.west.toFixed(4)},${M.north.toFixed(4)},${M.east.toFixed(4)}`,currentPass:null,renderSequence:0,passes:new Map};e._trafficTimingTracesCreated+=1,await n.ingestion.loadRoadsForBounds(b,C,w)}return{getTrafficTimingDiagnostics:o,trafficTimingPass:r,trafficTimingDetail:s,trafficTimingMark:a,trafficTimingMeasure:c,trafficTimingAggregate:l,clearTrafficTimingEntries:u,trafficTimingCameraChangeMarkName:h,markTrafficTimingCameraChange:d,markTrafficTimingMoveEnd:f,parseRoadsTimed:p,trafficTimingRenderState:g,scheduleTrafficTimingPostRender:_,loadRoadsForBoundsTimed:m}}const AO=.85,IO=.55;function Tm(e){return!Number.isFinite(e)||e>=AO?"free":e>=IO?"slow":"jam"}function dw(e){return Number.isFinite(e)?Math.min(1,Math.max(.15,e)):1}function RO(e,{jamBoost:t=!1}={}){return Number.isFinite(e)?t?Math.min(4,1/Math.max(e,.25)):Math.min(2.5,1/Math.max(e,.4)):1}function LO({state:e,services:t,parts:n,source:i}){function o(u){var d,f,p,g,_;if(!u||!u.elements)return[];const h=[];for(const m of u.elements){if(m.type!=="way"||!m.geometry||m.geometry.length<2)continue;const b=m.geometry.map(A=>[A.lon,A.lat]),C=b.length>uc?Math.ceil(b.length/uc):1,y=[];for(let A=0;A{const F=T+rw;return Cesium.Cartesian3.fromDegrees(A,L,F)}),S=[];for(let A=0;As(v,h)),p=new Array(u.length).fill(0);let g=Math.max(0,d);const _=f.map((v,M)=>({count:v,index:M})).sort((v,M)=>M.count-v.count);for(const v of _){if(g<=0)break;v.count<=0||(p[v.index]=1,g-=1)}if(g<=0)return p;let m=0;for(let v=0;v0&&b.length>0){b.sort((M,w)=>w.residual-M.residual);let v=0;for(;y>0&&b.length>0;){const M=b[v%b.length].index;if(p[M]b.length*3&&y>0)break}}return p}function c({liveMode:u=!1,fetching:h=!1,flowError:d=null,coveragePct:f=0,statusUnavailable:p=!1}={}){const g=u?"live":"sim";if(u&&d){const _=`SIMULATED — ${d}`;return{mode:g,error:_,loadingLabel:_}}return u?{mode:g,error:null,loadingLabel:h?"syncing LIVE traffic flow":`LIVE · TomTom flow · ${f}% cov`}:{mode:g,error:null,loadingLabel:p?"SIMULATED — traffic service unreachable":"SIMULATED — add TomTom key for live"}}function l(u){var f,p;if(!e._liveMode||!e._dots.length)return;e._bucketCounts={free:0,slow:0,jam:0,sim:0};let h=0;const d=Date.now();for(const g of e._dots){const _=g.road?g.road.flow:null;if(_!=null&&_.closure){g.point.show=!1,h+=1;continue}const m=_?Tm(_.level):null;g.bucket=m,g.point.color=m?e._activeBucketColors[m]:Cesium.Color.WHITE.withAlpha(.85),m==="jam"?g.point.pixelSize=n.style.baseDotSize((f=g.road)==null?void 0:f.type,m)+1+n.style.activeSizeDelta("jam"):m&&n.style.presetProfileActive()&&(g.point.pixelSize=n.style.baseDotSize((p=g.road)==null?void 0:p.type,m)+n.style.activeSizeDelta(m)),n.style.presetProfileActive()&&n.style.applyOutline(g.point,m),g.mps=g.baseMps*(_?dw(_.level):1),m==="jam"&&n.style.jamDensityOn()?(g.creep||(g.creep={moving:Math.random()<.4,until:d+Math.random()*2e3}),g.point.scaleByDistance=new Cesium.NearFarScalar(100,1.5,e._fadeScaleFar,cw),g.point.disableDepthTestDistance=lw):g.creep=null,e._bucketCounts[m||"sim"]+=1}e._closedRoads=e._roads.reduce((g,_)=>{var m;return g+((m=_.flow)!=null&&m.closure?1:0)},0),n.rendering.rebuildHeatLines(n.rendering.visibleRoadsForAltitude(e._roads,e._lastRenderAltitude)),console.log(`[Data:Traffic] Flow recolor (${u}): ${e._dots.length} dots, closedDots=${h}`)}return{parseRoads:o,estimateRoadLengthDeg:r,computeDotCount:s,allocateRoadDotBudgets:a,trafficFeedPresentation:c,recolorDotsInPlace:l}}function PO({state:e,services:t,parts:n,source:i}){const{fetchFlowForBounds:o}=i;async function r(l,u,h,d,{majorOnly:f=!1,timeoutSec:p=25,signal:g}={},_=null){const m=await i.requestRoads({south:l,west:u,north:h,east:d},{majorOnly:f,timeoutSec:p,signal:g});if(!m.ok)throw new Error(`Overpass API returned ${m.status}`);{const b=await m.json();if(g==null||g.throwIfAborted(),!Array.isArray(b==null?void 0:b.elements))throw new Error("Malformed road snapshot");return b}}function s(){e._activeFetchAbort&&(e._activeFetchAbort.abort(),e._activeFetchAbort=null)}async function a(l,u,h=null){const d=++e._loadGeneration;s(),clearTimeout(e._retryTimer),e._retryTimer=null,e._flowPending=0,e._activeFetchAbort=new AbortController;const f=e._activeFetchAbort.signal,p=n.viewport.clampBounds(l),g=`${p.south.toFixed(4)},${p.west.toFixed(4)},${p.north.toFixed(4)},${p.east.toFixed(4)}`;g!==e._retryBoundsKey&&(e._retryBoundsKey=g,e._retryDelayMs=1500),e._roadError=null,n.flow.ensureFlowStatus().then(()=>{e._liveMode&&e._enabled&&d===e._loadGeneration&&o(p,{signal:f}).catch(()=>{})}),e._fetching=!0;const _=e._lastBounds,m=e._lastViewCenter;e._lastBounds=p,e._lastViewCenter=n.viewport.getBoundsCenter(p);let b=!1;try{let C=e._tileCache.get(g);if(!C){if(e._tileCache.size>=CO){const v=e._tileCache.keys().next().value;e._tileCache.delete(v)}C={major:null,full:null},e._tileCache.set(g,C)}if(C.full){b=await n.flow.applyFlowThenRender(C.full,p,d,u,"Cache full",h);return}if(C.major){if(!await n.flow.applyFlowThenRender(C.major,p,d,u,"Cache major",h))return;b=!0}else{console.log(`[Data:Traffic] Fast fetch major roads [${g}]`);const v=await r(p.south,p.west,p.north,p.east,{majorOnly:!0,timeoutSec:12,signal:f},h);if(d!==e._loadGeneration||(C.major=e._parseRoads(v,h),!await n.flow.applyFlowThenRender(C.major,p,d,u,"Loaded major",h)))return;b=!0}if(u>nO)return;console.log(`[Data:Traffic] Full fetch local roads [${g}]`);const y=await r(p.south,p.west,p.north,p.east,{majorOnly:!1,timeoutSec:20,signal:f},h);if(d!==e._loadGeneration||(C.full=e._parseRoads(y,h),!await n.flow.applyFlowThenRender(C.full,p,d,u,"Loaded full",h)))return;b=!0}catch(C){if((C==null?void 0:C.name)==="AbortError")return;d===e._loadGeneration&&!b&&(e._roadError="Road data temporarily unavailable"),console.warn("[Data:Traffic] Fetch error:",C)}finally{d===e._loadGeneration&&(e._fetching=!1,b?e._retryDelayMs=1500:(e._lastBounds=_,e._lastViewCenter=m,e._enabled&&(e._retryTimer=setTimeout(()=>{e._retryTimer=null,n.viewport.onCameraChanged()},e._retryDelayMs),e._retryDelayMs=Math.min(e._retryDelayMs*2,3e4))))}}return{fetchRoads:r,cancelActiveFetch:s,loadRoadsForBounds:a,methods:{async update(){}}}}const xO=4,FO=5,SO=6,NO=6;function DO(e,t,n=Math.random){const i=[];if(!Number.isFinite(e)||e<=0||!(t>0))return i;let o=0;for(;o0&&(c+=SO+n()*NO);const u=s-c;a.push((u%e+e)%e)}i.push(a),o+=r}return i}function OO(e,t){let n=Math.max(0,t);const i=e.length-1;for(let o=0;o<=i;o++){const r=e[o]||0;if(r>0&&n<=r||o===i)return{segIdx:o,t:r>0?Math.min(1,n/r):0};n-=r}return{segIdx:0,t:0}}function BO({state:e,services:t,parts:n,source:i}){function o(c,l,u=null){const h=e._liveMode?c.flow:null;if(h!=null&&h.closure||e._liveMode&&!h&&e._uncoveredMode==="hide")return;const d=Number.isFinite(u)?Math.max(0,Math.floor(u)):n.model.computeDotCount(c,l),f=c.waypoints.length-1;if(f<1||d<=0)return;const p=lO[c.type]||5,g=h?Tm(h.level):null,_=n.style.baseDotSize(c.type,g)+(g==="jam"?1:0)+n.style.activeSizeDelta(g),m=g?e._activeBucketColors[g]:null,b=g&&e._presetDots==="on"?uw(e._stylePreset,g):null,C=b?new Cesium.Color(b.rgba[0]/255,b.rgba[1]/255,b.rgba[2]/255,b.rgba[3]):null,y=h?dw(h.level):1,v=Date.now();let M=null;if(g==="jam"&&n.style.jamDensityOn()){let w=0;for(const k of c.segmentDist)w+=k;const E=DO(w,d);if(E.length){M=[];for(let k=0;k=yh)return;const E=M?M[w].segIdx:Math.floor(Math.random()*f),k=M?M[w].t:Math.random(),T=p*e._speedScale*(.7+Math.random()*.6),I=T*y,R=M?M[w].direction:c.oneway?c.oneway:w%2===0?1:-1;Cesium.Cartesian3.lerp(c.waypoints[E],c.waypoints[E+1],k,e._scratchLerp);const S=g==="jam"&&n.style.jamDensityOn(),A=e._pointCollection.add({position:Cesium.Cartesian3.clone(e._scratchLerp),pixelSize:_,color:m||Cesium.Color.WHITE.withAlpha(.85),scaleByDistance:new Cesium.NearFarScalar(100,1.5,e._fadeScaleFar,S?cw:.3),translucencyByDistance:new Cesium.NearFarScalar(100,1,e._fadeTransFar,0),disableDepthTestDistance:S?lw:2e3,...b?{outlineColor:C,outlineWidth:b.width}:{}});e._bucketCounts[g||"sim"]+=1,e._dots.push({point:A,road:c,bucket:g,waypoints:c.waypoints,segmentDist:c.segmentDist,numSegments:f,segIdx:E,t:k,mps:I,baseMps:T,direction:R,stoppedUntil:0,creep:g==="jam"&&n.style.jamDensityOn()?{moving:Math.random()<.4,until:v+Math.random()*2e3}:null})}}function r(){var u;const c=Date.now(),l=e._lastAnimTime?Math.min((c-e._lastAnimTime)/1e3,.1):.016;e._lastAnimTime=c;for(let h=0;h=d.creep.until){d.creep.moving=!d.creep.moving;const[b,C]=d.creep.moving?gO:_O;d.creep.until=c+b+Math.random()*(C-b)}if(!d.creep.moving)continue;f=pO}const p=d.segmentDist[d.segIdx]||1,g=d.mps*f*l/p;d.t+=g*d.direction,d.t>=1?(d.t-=1,d.segIdx++,d.segIdx>=d.numSegments&&(d.segIdx=0,d.t=Math.random()*.3),s(d,c)):d.t<=0&&(d.t+=1,d.segIdx--,d.segIdx<0&&(d.segIdx=d.numSegments-1,d.t=1-Math.random()*.3),s(d,c));const _=d.waypoints[d.segIdx],m=d.waypoints[d.segIdx+1];Cesium.Cartesian3.lerp(_,m,d.t,e._scratchLerp),d.point.position=e._scratchLerp}(u=e._heatJamPrim)!=null&&u.appearance&&(e._heatJamPrim.appearance.material.uniforms.color.alpha=aw+fO*Math.sin(c/260)),e._animFrame++}function s(c,l){(c.segIdx<=1||c.segIdx>=c.numSegments-2)&&Math.random()<.008&&(c.stoppedUntil=l+2e3+Math.random()*4e3)}function a(){e._pointCollection&&e._pointCollection.removeAll(),n.rendering.removeHeatLines(),e._dots=[],e._roads=[],e._count=0,e._bucketCounts={free:0,slow:0,jam:0,sim:0},e._closedRoads=0}return{spawnDotsForRoad:o,animate:r,maybeStopLight:s,clearDots:a}}const hw=6371,Zn=e=>e*Math.PI/180,b_=e=>e*180/Math.PI;function VO(e,t,n,i){const o=Zn(e),r=Zn(n),s=Zn(n-e),a=Zn(i-t),c=Math.sin(s/2)**2+Math.cos(o)*Math.cos(r)*Math.sin(a/2)**2;return 2*hw*Math.asin(Math.min(1,Math.sqrt(c)))}function HO(e,t,n,i){const o=Zn(e),r=Zn(n),s=Zn(i-t),a=Math.sin(s)*Math.cos(r),c=Math.cos(o)*Math.sin(r)-Math.sin(o)*Math.cos(r)*Math.cos(s);return Math.atan2(a,c)}function $O(e,t,n,i){const o=i/hw,r=Zn(e),s=Zn(t),a=Math.asin(Math.sin(r)*Math.cos(o)+Math.cos(r)*Math.sin(o)*Math.cos(n)),c=s+Math.atan2(Math.sin(n)*Math.sin(o)*Math.cos(r),Math.cos(o)-Math.sin(r)*Math.sin(a)),l=(b_(c)+540)%360-180;return{lat:b_(a),lon:l}}function GO({nadirLat:e,nadirLon:t,hitLat:n,hitLon:i,maxPullKm:o=12}){if(!Number.isFinite(n)||!Number.isFinite(i))return{lat:e,lon:t,source:"nadir"};if(VO(e,t,n,i)<=o)return{lat:n,lon:i,source:"hit"};const s=HO(e,t,n,i),a=$O(e,t,s,o);return{lat:a.lat,lon:a.lon,source:"pulled"}}function C_(e,t,n=.05){const i=Math.min(e.north-e.south,n),o=Math.min(e.east-e.west,n);return{south:t.lat-i/2,north:t.lat+i/2,west:t.lon-o/2,east:t.lon+o/2}}function UO({state:e,services:t,parts:n,source:i}){function o(){const d=e._viewer.camera.positionCartographic;return d?d.height:1/0}function r(){const d=e._viewer.camera.computeViewRectangle();return d?{south:Cesium.Math.toDegrees(d.south),west:Cesium.Math.toDegrees(d.west),north:Cesium.Math.toDegrees(d.north),east:Cesium.Math.toDegrees(d.east)}:null}function s(){const d=e._viewer.camera.positionCartographic;if(!d)return null;const f=Cesium.Math.toDegrees(d.latitude),p=Cesium.Math.toDegrees(d.longitude);let g,_;const m=e._viewer.scene.canvas,b=m.clientWidth||m.width,C=m.clientHeight||m.height;if(b>0&&C>0){const y=e._viewer.camera.pickEllipsoid(new Cesium.Cartesian2(b/2,C/2),Cesium.Ellipsoid.WGS84);if(y){const v=Cesium.Cartographic.fromCartesian(y);g=Cesium.Math.toDegrees(v.latitude),_=Cesium.Math.toDegrees(v.longitude)}}return GO({nadirLat:f,nadirLon:p,hitLat:g,hitLon:_,maxPullKm:sO})}function a(d){return{lat:(d.south+d.north)/2,lon:(d.west+d.east)/2}}function c(d,f){const p=(d.lat-f.lat)*111,g=(d.lat+f.lat)/2*(Math.PI/180),_=(d.lon-f.lon)*111*Math.cos(g);return Math.sqrt(p*p+_*_)}function l(d,f,p){const g=Math.max(d.south,f.south),_=Math.min(d.north,f.north),m=Math.max(d.west,f.west),b=Math.min(d.east,f.east);if(_<=g||b<=m)return!1;const C=(_-g)*(b-m),y=(d.north-d.south)*(d.east-d.west);return y>0&&C/y>=p}function u(d){return C_(d,a(d))}function h(){if(!e._enabled)return;const d=o();if(d>tO){clearTimeout(e._fetchTimeout),clearTimeout(e._retryTimer),e._retryTimer=null,n.ingestion.cancelActiveFetch(),e._loadGeneration++,e._fetching=!1,e._flowPending=0,e._roadError=null,n.animation.clearDots(),e._lastBounds=null,e._lastViewCenter=null;return}const f=r();if(!f)return;const p=s(),g=p?C_(f,p):u(f),_=a(g);if(e._lastBounds&&e._lastViewCenter&&l(g,e._lastBounds,oO)&&c(_,e._lastViewCenter)e._loadRoadsForBounds(g,d,m),iO)}return{getCameraAltitude:o,getViewBounds:r,getFetchCenter:s,getBoundsCenter:a,distanceKm:c,boundsOverlap:l,clampBounds:u,onCameraChanged:h}}const y_=111320,cs=100,v_=35,zO=30,zu=7,jO=2;function qO(e){if(!Array.isArray(e)||e.length===0)return null;const t=[...e].sort((i,o)=>i-o),n=t.length>>1;return t.length%2===1?t[n]:(t[n-1]+t[n])/2}function M_(e,t){return Math.atan2(e,t)*180/Math.PI}function WO(e,t){let n=Math.abs(e-t)%360;return n>180&&(n=360-n),Math.min(n,180-n)}function KO(e,t,n,i,o,r){const s=o-n,a=r-i,c=s*s+a*a;let l=c>0?((e-n)*s+(t-i)*a)/c:0;l=Math.max(0,Math.min(1,l));const u=n+l*s,h=i+l*a;return(e-u)*(e-u)+(t-h)*(t-h)}function YO(e,t){var _;const n=Array.isArray(e)?e.length:0,i=new Array(n).fill(null),o={matches:i,matchedCount:0,candidateCount:0};if(n===0||!Array.isArray(t)||t.length===0)return o;const r=t.find(m=>Array.isArray(m==null?void 0:m.coords)&&m.coords.length>=2);if(!r)return o;const[s,a]=r.coords[0],c=y_*Math.cos(a*Math.PI/180),l=m=>(m-s)*c,u=m=>(m-a)*y_,h=new Map,d=(m,b)=>`${Math.floor(m/cs)},${Math.floor(b/cs)}`;for(const m of t){const b=m==null?void 0:m.coords;if(!Array.isArray(b)||b.length<2)continue;const C=m.trafficLevel,y=m.closure===!0;for(let v=0;v0))continue;const I=M_(E-M,k-w),R=Math.max(1,Math.ceil(T/cs));for(let S=0;S0&&(v[I]=v[I-1]+Math.hypot(C[I]-C[I-1],y[I]-y[I-1]));const M=v[b.length-1];if(!(M>0))continue;let w=!1;const E=[];let k=!1,T=1;for(let I=0;If||(w=!0,!(WO(W.bearing,F)>=zO)&&V<=$&&($=V,D=W))}}D&&(E.push(D.level),D.closure&&(k=!0))}w&&g++,E.length>=Math.max(jO,zu/2)&&(i[m]={level:qO(E),closure:k},p++)}return{matches:i,matchedCount:p,candidateCount:g}}function XO({state:e,services:t,parts:n,source:i}){const{registerDynamicCredit:o,TOMTOM_CREDIT:r}=t.credits,{fetchFlowForBounds:s}=i;function a(h){var p;if(!h||h.name==="AbortError")return null;const d=String(h.message||h),f=Number((p=d.match(/HTTP (\d{3})/))==null?void 0:p[1]);return f===503?"TomTom key unavailable":f===429?"TomTom daily budget reached":f===502||f===504?"TomTom upstream unreachable":Number.isFinite(f)?`TomTom flow error (HTTP ${f})`:"TomTom flow unavailable"}function c(){return e._flowStatusPromise||(e._flowStatusPromise=i.getStatus().then(h=>{e._liveMode=!!(h!=null&&h.hasKey),e._flowStatusUnavailable=!1,e._liveMode&&(console.log("[Data:Traffic] TomTom key present — live flow mode"),o(e._viewer,r))}).catch(h=>{e._liveMode=!1,e._flowStatusUnavailable=!0,console.warn("[Data:Traffic] TomTom status unreachable — simulated traffic:",(h==null?void 0:h.message)||h)})),e._flowStatusPromise}async function l(h,d,f){e._flowPending+=1;try{if(!e._flowStatusPromise||(await e._flowStatusPromise,!e._liveMode||!e._enabled)||f!==e._loadGeneration||!Array.isArray(h)||h.length===0)return;try{e._activeFetchAbort||(e._activeFetchAbort=new AbortController);const p=await s(d,{signal:e._activeFetchAbort.signal});if(f!==e._loadGeneration)return;const{matches:g,matchedCount:_,candidateCount:m}=YO(h,p);for(let b=0;b0?Math.round(_/m*100):0,e._flowError=null}catch(p){if((p==null?void 0:p.name)==="AbortError"||f!==e._loadGeneration||!e._enabled)return;e._flowError=a(p),e._flowCoveragePct=0,console.warn("[Data:Traffic] Flow fetch failed (sim colors remain):",(p==null?void 0:p.message)||p)}}finally{f===e._loadGeneration&&(e._flowPending-=1)}}async function u(h,d,f,p,g,_=null){const m=l(h,d,f),b=await Promise.race([m.then(()=>"flow"),new Promise(C=>setTimeout(()=>C("timeout"),yO))]);return f!==e._loadGeneration?!1:(n.rendering.renderRoadsForAltitude(h,p,g,_),b==="timeout"&&m.then(()=>{f===e._loadGeneration&&n.model.recolorDotsInPlace(g)}).catch(()=>{}),!0)}return{deriveTrafficFlowError:a,ensureFlowStatus:c,applyFlowToRoads:l,applyFlowThenRender:u}}function QO({state:e,services:t,parts:n,source:i}){function o(c,l){return l>5e3?c.filter(u=>u.type==="motorway"||u.type==="trunk"||u.type==="primary"):c}function r(){var c,l;e._heatJamPrim&&((c=e._viewer)==null||c.scene.groundPrimitives.remove(e._heatJamPrim),e._heatJamPrim=null),e._heatSlowPrim&&((l=e._viewer)==null||l.scene.groundPrimitives.remove(e._heatSlowPrim),e._heatSlowPrim=null),e._heatLineCount=0}function s(c){if(r(),!e._viewer||!e._liveMode||!n.style.heatlineOn()||(e._heatSupported===null&&(e._heatSupported=Cesium.GroundPolylinePrimitive.isSupported(e._viewer.scene),e._heatSupported||console.warn("[Data:Traffic] GroundPolylinePrimitive unsupported — heat-lines disabled")),!e._heatSupported))return;const l=[];for(const m of c){const b=m.flow;if(!b||b.closure)continue;const C=Tm(b.level);if(C==="free")continue;let y=0;for(const v of m.segmentDist)y+=v;l.push({road:m,bucket:C,len:y})}l.sort((m,b)=>m.bucket===b.bucket?b.len-m.len:m.bucket==="jam"?-1:1);const u=l.slice(0,g_),h=(m,b)=>u.filter(C=>C.bucket===m).map(C=>new Cesium.GeometryInstance({geometry:new Cesium.GroundPolylineGeometry({positions:C.road.waypoints,width:b})})),d=e._presetDots==="on"&&ns(e._stylePreset)==="mono",f=d?Cesium.Color.WHITE:mO,p=d?new Cesium.Color(.7,.7,.7,__.alpha):__,g=h("jam",dO);g.length&&(e._heatJamPrim=e._viewer.scene.groundPrimitives.add(new Cesium.GroundPolylinePrimitive({geometryInstances:g,classificationType:Cesium.ClassificationType.CESIUM_3D_TILE,appearance:new Cesium.PolylineMaterialAppearance({material:Cesium.Material.fromType("PolylineGlow",{color:f.withAlpha(aw),glowPower:.25})})})));const _=h("slow",hO);_.length&&(e._heatSlowPrim=e._viewer.scene.groundPrimitives.add(new Cesium.GroundPolylinePrimitive({geometryInstances:_,classificationType:Cesium.ClassificationType.CESIUM_3D_TILE,appearance:new Cesium.PolylineMaterialAppearance({material:Cesium.Material.fromType("Color",{color:p})})}))),e._heatLineCount=u.length,l.length>u.length&&console.log(`[Data:Traffic] Heat-lines capped at ${g_} (${l.length} congested roads in view)`)}function a(c,l,u,h=null){var g;n.animation.clearDots(),e._roads=c,e._lastRenderAltitude=l;const d=o(c,l);e._closedRoads=e._liveMode?d.reduce((_,m)=>{var b;return _+((b=m.flow)!=null&&b.closure?1:0)},0):0;let f=l;if(e._viewer&&d.length){const _=[d[0],d[Math.floor(d.length/2)],d[d.length-1]];for(const m of _){const b=(g=m==null?void 0:m.waypoints)==null?void 0:g[0];b&&(f=Math.max(f,Cesium.Cartesian3.distance(e._viewer.camera.positionWC,b)))}}e._fadeScaleFar=Math.max(8e3,f*1.5),e._fadeTransFar=Math.max(1e4,f*1.8);const p=n.model.allocateRoadDotBudgets(d,l,yh);for(let _=0;_=yh))break}s(d),e._count=e._dots.length,e._lastUpdate=Date.now(),console.log(`[Data:Traffic] ${u}: ${e._count} dots (roads=${c.length}, alt=${Math.round(l)}m)`)}return{visibleRoadsForAltitude:o,removeHeatLines:r,rebuildHeatLines:s,renderRoadsForAltitude:a}}function ZO({state:e,services:t,parts:n,source:i}){const{getFlowSessionStats:o}=i;return{methods:{id:"traffic",name:"Street Traffic",icon:"🚗",source:"OpenStreetMap",updateInterval:0,setParams(s={}){typeof s.densityScale=="number"&&(e._densityScale=Math.max(.2,Math.min(2.5,s.densityScale))),typeof s.speedScale=="number"&&(e._speedScale=Math.max(.3,Math.min(3,s.speedScale))),(s.uncoveredRoads==="sim"||s.uncoveredRoads==="hide")&&(e._uncoveredMode=s.uncoveredRoads),["none","density","heatline","both"].includes(s.jamViz)&&(e._jamViz=s.jamViz),(s.presetDots==="on"||s.presetDots==="off")&&s.presetDots!==e._presetDots&&(e._presetDots=s.presetDots,n.style.restyleDotsInPlace())},getParams(){return{densityScale:e._densityScale,speedScale:e._speedScale,uncoveredRoads:e._uncoveredMode,jamViz:e._jamViz,presetDots:e._presetDots}},getDetectableObjects(s={}){if(!e._enabled||e._dots.length===0)return[];const a=Number.isFinite(s.maxCount)?Math.max(1,Math.floor(s.maxCount)):e._dots.length,c=Number.isFinite(s.seed)?Math.floor(s.seed):0,l=Math.max(1,Math.ceil(e._dots.length/a)),u=c%l,h=[];for(let d=u;d=a)break}return h},getStats(){const s=e._fetching||e._flowPending>0,a=n.model.trafficFeedPresentation({liveMode:e._liveMode,fetching:s,flowError:e._flowError,coveragePct:e._flowCoveragePct,statusUnavailable:e._flowStatusUnavailable});return{count:e._count,lastUpdate:e._lastUpdate,loading:s,mode:a.mode,error:e._roadError||a.error,flowCoveragePct:e._flowCoveragePct,tilesFetched:o().tilesFetched,flowBuckets:{...e._bucketCounts},closedRoads:e._closedRoads,heatLines:e._heatLineCount,jamViz:e._jamViz,stylePreset:e._stylePreset,styleProfile:e._presetDots==="on"?ns(e._stylePreset):"normal",loadingLabel:a.loadingLabel}}}}}const dc=new WeakMap,JO=.5;function e2(e){let t=dc.get(e);return t||(t={base:Number.isFinite(e.percentageChanged)?e.percentageChanged:JO,claims:new Map},dc.set(e,t)),t}function fw(e,t){let n=t.base;for(const i of t.claims.values())i{var d;return n.style.setStylePreset((d=h==null?void 0:h.detail)==null?void 0:d.style)}),e._styleListenerBound=!0)),n.style.refreshBucketColors(),console.log("[Data:Traffic] Initialized")},enable(c){e._enabled=!0,o("traffic"),e._lastAnimTime=0,e._pointCollection.show=!0,n.flow.ensureFlowStatus(),e._preRenderRemover=c.scene.preRender.addEventListener(n.animation.animate),c.camera.changed.addEventListener(n.viewport.onCameraChanged),e._arrivalRemover=c.camera.moveEnd.addEventListener(n.viewport.onCameraChanged),km(c.camera,"traffic",.05),n.viewport.onCameraChanged(),clearInterval(e._enableKickTimer),e._enableKickTimer=setInterval(()=>{if(!e._enabled||e._lastUpdate){clearInterval(e._enableKickTimer),e._enableKickTimer=null;return}!e._fetching&&!e._retryTimer&&n.viewport.onCameraChanged()},1500)},disable(c){var l;e._enabled=!1,r("traffic"),clearTimeout(e._fetchTimeout),clearInterval(e._enableKickTimer),e._enableKickTimer=null,clearTimeout(e._retryTimer),e._retryTimer=null,e._retryDelayMs=1500,n.ingestion.cancelActiveFetch(),e._loadGeneration++,e._fetching=!1,e._flowPending=0,e._roadError=null,n.animation.clearDots(),e._lastViewCenter=null,e._flowError=null,e._preRenderRemover&&(e._preRenderRemover(),e._preRenderRemover=null),c.camera.changed.removeEventListener(n.viewport.onCameraChanged),(l=e._arrivalRemover)==null||l.call(e),e._arrivalRemover=null,hc(c.camera,"traffic"),e._pointCollection&&(e._pointCollection.show=!1)},destroy(c){this.disable(c),e._pointCollection&&(c.scene.primitives.remove(e._pointCollection),e._pointCollection=null),n.rendering.removeHeatLines(),e._tileCache.clear(),s(),e._count=0,e._lastUpdate=null}}}}function n2({services:e}){const t={};return t._viewer=null,t._pointCollection=null,t._dots=[],t._roads=[],t._enabled=!1,t._preRenderRemover=null,t._cameraRemover=null,t._arrivalRemover=null,t._fetchTimeout=null,t._lastBounds=null,t._fetching=!1,t._count=0,t._lastUpdate=null,t._loadGeneration=0,t._activeFetchAbort=null,t._densityScale=1,t._speedScale=1,t._lastViewCenter=null,t._prevPercentageChanged=null,t._liveMode=!1,t._flowError=null,t._flowStatusUnavailable=!1,t._flowPending=0,t._bucketCounts={free:0,slow:0,jam:0,sim:0},t._closedRoads=0,t._uncoveredMode="sim",t._jamViz="density",t._heatJamPrim=null,t._heatSlowPrim=null,t._heatLineCount=0,t._heatSupported=null,t._lastRenderAltitude=0,t._stylePreset="normal",t._presetDots="on",t._styleListenerBound=!1,t._activeBucketColors={...sw},t._fadeScaleFar=8e3,t._fadeTransFar=1e4,t._flowStatusPromise=null,t._enableKickTimer=null,t._retryTimer=null,t._retryDelayMs=1500,t._retryBoundsKey=null,t._roadError=null,t._flowCoveragePct=0,t._trafficTimingMoveEndRemover=null,t._trafficTimingPostRenderRemovers=null,t._trafficTimingCurrentAnchor=null,t._trafficTimingSequence=0,t._trafficTimingTracesCreated=0,t._trafficTimingDroppedTraces=0,t._tileCache=new Map,t._scratchLerp=new Cesium.Cartesian3,t._lastAnimTime=0,t._animFrame=0,t}const w_=85.05112878;function E_(e,t,n){const i=2**n,r=Math.max(-w_,Math.min(w_,t))*Math.PI/180,s=Math.floor((e+180)/360*i),a=Math.floor((1-Math.log(Math.tan(r)+1/Math.cos(r))/Math.PI)/2*i);return{x:Math.max(0,Math.min(i-1,s)),y:Math.max(0,Math.min(i-1,a))}}function i2(e,t=12,{maxTiles:n=64}={}){if(!e)return[];const{south:i,west:o,north:r,east:s}=e;if(![i,o,r,s].every(Number.isFinite))return[];const a=E_(Math.min(o,s),Math.max(i,r),t),c=E_(Math.max(o,s),Math.min(i,r),t),l=[];for(let u=a.y;u<=c.y;u++)for(let h=a.x;h<=c.x;h++){if(l.length>=n)return l;l.push({z:t,x:h,y:u})}return l}const T_=65536*65536,o2=12,k_=typeof TextDecoder>"u"?null:new TextDecoder("utf-8"),r2=0,s2=1,A_=2,a2=5;class l2{constructor(t){this.buf=ArrayBuffer.isView(t)?t:new Uint8Array(t),this.dataView=new DataView(this.buf.buffer,this.buf.byteOffset,this.buf.byteLength),this.pos=0,this.type=0,this._valueStart=-1,this.length=this.buf.length}readFields(t,n,i=this.length){let o;for(;o=this.nextField(i);)t(o,n,this);return n}readMessage(t,n){return this.readFields(t,n,this.readVarint()+this.pos)}readFixed32(){const t=this.dataView.getUint32(this.pos,!0);return this.pos+=4,t}readSFixed32(){const t=this.dataView.getInt32(this.pos,!0);return this.pos+=4,t}readFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*T_;return this.pos+=8,t}readSFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*T_;return this.pos+=8,t}readFloat(){const t=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,t}readDouble(){const t=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,t}readVarint(t){const n=this.buf,i=n[this.pos++];if(i<128)return i;let o=i&127,r;return r=n[this.pos++],o|=(r&127)<<7,r<128||(r=n[this.pos++],o|=(r&127)<<14,r<128)||(r=n[this.pos++],o|=(r&127)<<21,r<128)?o:(r=n[this.pos],o|=(r&15)<<28,c2(o,t,this))}readSVarint(){const t=this.readVarint();return t%2===1?(t+1)/-2:t/2}readBoolean(){return!!this.readVarint()}readString(){const t=this.readVarint()+this.pos,n=this.pos;return this.pos=t,t-n>=o2&&k_?k_.decode(this.buf.subarray(n,t)):u2(this.buf,n,t)}readBytes(){const t=this.readVarint()+this.pos,n=this.buf.subarray(this.pos,t);return this.pos=t,n}readPackedVarint(t=[],n){const i=this.readPackedEnd();for(;this.pos=t)return 0;const n=this.readVarint();return this.type=n&7,this._valueStart=this.pos,n>>>3}skip(t){const n=t&7;if(n===r2)for(;this.buf[this.pos++]>127;);else if(n===A_)this.pos=this.readVarint()+this.pos;else if(n===a2)this.pos+=4;else if(n===s2)this.pos+=8;else throw new Error(`Unimplemented type: ${n}`)}}function c2(e,t,n){const i=n.buf;let o,r;if(r=i[n.pos++],o=(r&112)>>4,r<128||(r=i[n.pos++],o|=(r&127)<<3,r<128)||(r=i[n.pos++],o|=(r&127)<<10,r<128)||(r=i[n.pos++],o|=(r&127)<<17,r<128)||(r=i[n.pos++],o|=(r&127)<<24,r<128)||(r=i[n.pos++],o|=(r&1)<<31,r<128))return Yo(e,o,t);throw new Error("Expected varint not more than 10 bytes")}function Yo(e,t,n){return n?t*4294967296+(e>>>0):(t>>>0)*4294967296+(e>>>0)}function u2(e,t,n){let i="",o=t;for(;o239?4:r>223?3:r>191?2:1;if(o+a>n)break;let c,l,u;a===1?r<128&&(s=r):a===2?(c=e[o+1],(c&192)===128&&(s=(r&31)<<6|c&63,s<=127&&(s=null))):a===3?(c=e[o+1],l=e[o+2],(c&192)===128&&(l&192)===128&&(s=(r&15)<<12|(c&63)<<6|l&63,(s<=2047||s>=55296&&s<=57343)&&(s=null))):a===4&&(c=e[o+1],l=e[o+2],u=e[o+3],(c&192)===128&&(l&192)===128&&(u&192)===128&&(s=(r&15)<<18|(c&63)<<12|(l&63)<<6|u&63,(s<=65535||s>=1114112)&&(s=null))),s===null?(s=65533,a=1):s>65535&&(s-=65536,i+=String.fromCharCode(s>>>10&1023|55296),s=56320|s&1023),i+=String.fromCharCode(s),o+=a}return i}function Jn(e,t){this.x=e,this.y=t}Jn.prototype={clone(){return new Jn(this.x,this.y)},add(e){return this.clone()._add(e)},sub(e){return this.clone()._sub(e)},multByPoint(e){return this.clone()._multByPoint(e)},divByPoint(e){return this.clone()._divByPoint(e)},mult(e){return this.clone()._mult(e)},div(e){return this.clone()._div(e)},rotate(e){return this.clone()._rotate(e)},rotateAround(e,t){return this.clone()._rotateAround(e,t)},matMult(e){return this.clone()._matMult(e)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(e){return this.x===e.x&&this.y===e.y},dist(e){return Math.sqrt(this.distSqr(e))},distSqr(e){const t=e.x-this.x,n=e.y-this.y;return t*t+n*n},angle(){return Math.atan2(this.y,this.x)},angleTo(e){return Math.atan2(this.y-e.y,this.x-e.x)},angleWith(e){return this.angleWithSep(e.x,e.y)},angleWithSep(e,t){return Math.atan2(this.x*t-this.y*e,this.x*e+this.y*t)},_matMult(e){const t=e[0]*this.x+e[1]*this.y,n=e[2]*this.x+e[3]*this.y;return this.x=t,this.y=n,this},_add(e){return this.x+=e.x,this.y+=e.y,this},_sub(e){return this.x-=e.x,this.y-=e.y,this},_mult(e){return this.x*=e,this.y*=e,this},_div(e){return this.x/=e,this.y/=e,this},_multByPoint(e){return this.x*=e.x,this.y*=e.y,this},_divByPoint(e){return this.x/=e.x,this.y/=e.y,this},_unit(){return this._div(this.mag()),this},_perp(){const e=this.y;return this.y=this.x,this.x=-e,this},_rotate(e){const t=Math.cos(e),n=Math.sin(e),i=t*this.x-n*this.y,o=n*this.x+t*this.y;return this.x=i,this.y=o,this},_rotateAround(e,t){const n=Math.cos(e),i=Math.sin(e),o=t.x+n*(this.x-t.x)-i*(this.y-t.y),r=t.y+i*(this.x-t.x)+n*(this.y-t.y);return this.x=o,this.y=r,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:Jn};Jn.convert=function(e){if(e instanceof Jn)return e;if(Array.isArray(e))return new Jn(+e[0],+e[1]);if(e.x!==void 0&&e.y!==void 0)return new Jn(+e.x,+e.y);throw new Error("Expected [x, y] or {x, y} point format")};class mw{constructor(t,n,i,o,r){for(this.properties=Object.create(null),this.extent=i,this.type=0,this.id=void 0,this._pbf=t,this._geometry=-1,this._keys=o,this._values=r;t.pos>3,s===0)continue}if(s--,r===1)a+=t.readSVarint(),c+=t.readSVarint(),o&&i.push(o),o=[new Jn(a,c)];else if(r===2)a+=t.readSVarint(),c+=t.readSVarint(),o&&o.push(new Jn(a,c));else if(r===7)o&&o.push(o[0].clone());else throw new Error(`unknown command ${r}`)}return o&&i.push(o),i}bbox(){if(this._geometry<0)throw new Error("feature has no geometry");const t=this._pbf;t.pos=this._geometry;const n=t.readVarint()+t.pos;let i=1,o=0,r=0,s=0,a=1/0,c=-1/0,l=1/0,u=-1/0;for(;t.pos>3,o===0)continue}if(o--,i===1||i===2)r+=t.readSVarint(),s+=t.readSVarint(),rc&&(c=r),su&&(u=s);else if(i!==7)throw new Error(`unknown command ${i}`)}return[a,l,c,u]}toGeoJSON(t,n,i){const o=this.extent*Math.pow(2,i),r=this.extent*t,s=this.extent*n,a=this.loadGeometry();function c(d){return[(d.x+r)*360/o-180,360/Math.PI*Math.atan(Math.exp((1-(d.y+s)*2/o)*Math.PI))-90]}function l(d){return d.map(c)}let u;if(this.type===1){const d=[];for(const p of a)d.push(p[0]);const f=l(d);u=d.length===1?{type:"Point",coordinates:f[0]}:{type:"MultiPoint",coordinates:f}}else if(this.type===2){const d=a.map(l);u=d.length===1?{type:"LineString",coordinates:d[0]}:{type:"MultiLineString",coordinates:d}}else if(this.type===3){const d=d2(a),f=[];for(const p of d)f.push(p.map(l));u=f.length===1?{type:"Polygon",coordinates:f[0]}:{type:"MultiPolygon",coordinates:f}}else throw new Error("unknown feature type");const h={type:"Feature",geometry:u,properties:this.properties};return this.id!=null&&(h.id=this.id),h}}mw.types=["Unknown","Point","LineString","Polygon"];function d2(e){const t=e.length;if(t<=1)return[e];const n=[];let i,o;for(let r=0;r=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];const n=this._pbf.readVarint()+this._pbf.pos;return new mw(this._pbf,n,this.extent,this._keys,this._values)}}function m2(e){let t=null;const n=e.readVarint()+e.pos;for(;e.posglobalThis.fetch(...t)}={}){const i=new Map;let o=0;function r(l,u){if(!i.has(l)&&i.size>=64){const h=i.keys().next().value;i.delete(h)}i.set(l,u)}async function s(l,{signal:u,zoom:h=12}={}){u==null||u.throwIfAborted();const d=i2(l,h);if(d.length===0)return[];const f=Date.now(),p=await Promise.allSettled(d.map(async({z:_,x:m,y:b})=>{const C=`${_}/${m}/${b}`,y=i.get(C);if(y&&f-y.at<12e4)return y.segments;o+=1;const v=await e(`/api/tomtom/flow/${_}/${m}/${b}.pbf`,{signal:u});if(!v.ok)throw new Error(`flow tile ${C}: HTTP ${v.status}`);const M=_2(await v.arrayBuffer(),_,m,b);return u==null||u.throwIfAborted(),r(C,{at:Date.now(),segments:M}),M}));u==null||u.throwIfAborted();const g=p.filter(_=>_.status==="fulfilled");if(g.length===0)throw p[0].reason instanceof Error?p[0].reason:new Error("flow fetch failed");return g.flatMap(_=>_.value)}function a(){return{tilesFetched:o}}function c(){i.clear()}return{fetchFlowForBounds:s,getFlowSessionStats:a,resetFlowTileCache:c}}function C2(e,t,n,i,{majorOnly:o=!1,timeoutSec:r=25}={}){return`[out:json][timeout:${r}];(way["highway"~"${o?"^(motorway|trunk|primary|secondary)$":"^(motorway|trunk|primary|secondary|tertiary|residential|unclassified)$"}"](${e},${t},${n},${i}););out geom qt;`}function y2({fetchImpl:e=(...t)=>globalThis.fetch(...t)}={}){return{...b2({fetchImpl:e}),async requestRoads({south:n,west:i,north:o,east:r},{majorOnly:s=!1,timeoutSec:a=25,signal:c}={}){if(![n,i,o,r].every(Number.isFinite)||n<-90||o>90||i<-180||r>180||o<=n||r<=i||o-n>10||r-i>10||!Number.isInteger(a)||a<1||a>30)throw new TypeError("A bounded road viewport and timeout are required");c==null||c.throwIfAborted();const l=C2(n,i,o,r,{majorOnly:s,timeoutSec:a}),u=await e("/api/overpass",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"data="+encodeURIComponent(l),signal:c});return c==null||c.throwIfAborted(),{ok:u.ok,status:u.status,headers:u.headers,async json(){const h=await u.json();return c==null||c.throwIfAborted(),h}}},async getStatus({signal:n}={}){n==null||n.throwIfAborted();const i=await e("/api/tomtom/status",{signal:n});if(!i.ok)throw new Error("HTTP "+i.status);const o=await i.json();if(n==null||n.throwIfAborted(),typeof(o==null?void 0:o.hasKey)!="boolean")throw new Error("Malformed traffic status");return o}}}function v2({services:e,source:t}){var r;if(!["requestRoads","getStatus","fetchFlowForBounds","getFlowSessionStats","resetFlowTileCache"].every(s=>typeof(t==null?void 0:t[s])=="function"))throw new TypeError("A traffic source is required");const n=n2({services:e}),i={},o={state:n,services:e,parts:i,source:t};return i.style=TO(o),i.timing=kO(o),i.model=LO(o),i.ingestion=PO(o),i.animation=BO(o),i.viewport=UO(o),i.flow=XO(o),i.rendering=QO(o),i.controls=ZO(o),i.lifecycle=t2(o),n._parseRoads=i.model.parseRoads,n._loadRoadsForBounds=i.ingestion.loadRoadsForBounds,Object.assign({},i.controls.methods,i.lifecycle.methods,(r=i.ingestion)==null?void 0:r.methods,{getTrafficTimingDiagnostics:i.timing.getTrafficTimingDiagnostics,deriveTrafficFlowError:i.flow.deriveTrafficFlowError,trafficFeedPresentation:i.model.trafficFeedPresentation})}function M2({source:e}){return v2({source:e,services:{credits:ON,render:Pt}})}function w2(e){return{stationInformationUrl:`https://gbfs.bcycle.com/${e}/station_information.json`,stationStatusUrl:`https://gbfs.bcycle.com/${e}/station_status.json`}}function pt({id:e,city:t,centerLat:n,centerLon:i,systemId:o,loadRadiusKm:r=100,provider:s="BCycle"}){return{id:e,city:t,centerLat:n,centerLon:i,loadRadiusKm:r,provider:s,...w2(o)}}const E2=[{id:"nyc-citibike",city:"New York, NY",centerLat:40.7484,centerLon:-73.9967,loadRadiusKm:140,stationInformationUrl:"https://gbfs.lyft.com/gbfs/2.3/bkn/en/station_information.json",stationStatusUrl:"https://gbfs.lyft.com/gbfs/2.3/bkn/en/station_status.json",provider:"Citi Bike"},{id:"chicago-divvy",city:"Chicago, IL",centerLat:41.8781,centerLon:-87.6298,loadRadiusKm:120,stationInformationUrl:"https://gbfs.lyft.com/gbfs/2.3/chi/en/station_information.json",stationStatusUrl:"https://gbfs.lyft.com/gbfs/2.3/chi/en/station_status.json",provider:"Divvy"},{id:"dc-capital-bikeshare",city:"Washington, DC",centerLat:38.9072,centerLon:-77.0369,loadRadiusKm:120,stationInformationUrl:"https://gbfs.lyft.com/gbfs/2.3/dca-cabi/en/station_information.json",stationStatusUrl:"https://gbfs.lyft.com/gbfs/2.3/dca-cabi/en/station_status.json",provider:"Capital Bikeshare"},{id:"sf-bay-wheels",city:"San Francisco, CA",centerLat:37.7749,centerLon:-122.4194,loadRadiusKm:110,stationInformationUrl:"https://gbfs.lyft.com/gbfs/2.3/bay/en/station_information.json",stationStatusUrl:"https://gbfs.lyft.com/gbfs/2.3/bay/en/station_status.json",provider:"Bay Wheels"},{id:"boston-bluebikes",city:"Boston, MA",centerLat:42.3601,centerLon:-71.0589,loadRadiusKm:100,stationInformationUrl:"https://gbfs.bluebikes.com/gbfs/en/station_information.json",stationStatusUrl:"https://gbfs.bluebikes.com/gbfs/en/station_status.json",provider:"Blue Bikes"},{id:"philadelphia-indego",city:"Philadelphia, PA",centerLat:39.9526,centerLon:-75.1652,loadRadiusKm:100,stationInformationUrl:"https://gbfs.bcycle.com/bcycle_indego/station_information.json",stationStatusUrl:"https://gbfs.bcycle.com/bcycle_indego/station_status.json",provider:"Indego"},{id:"portland-biketown",city:"Portland, OR",centerLat:45.5152,centerLon:-122.6784,loadRadiusKm:95,stationInformationUrl:"https://gbfs.biketownpdx.com/gbfs/2.3/en/station_information.json",stationStatusUrl:"https://gbfs.biketownpdx.com/gbfs/2.3/en/station_status.json",provider:"BIKETOWN"},{id:"la-metro-bike",city:"Los Angeles, CA",centerLat:34.0522,centerLon:-118.2437,loadRadiusKm:120,stationInformationUrl:"https://gbfs.bcycle.com/bcycle_lametro/station_information.json",stationStatusUrl:"https://gbfs.bcycle.com/bcycle_lametro/station_status.json",provider:"Metro Bike"},{id:"austin-capmetro",city:"Austin, TX",centerLat:30.2672,centerLon:-97.7431,loadRadiusKm:90,stationInformationUrl:"https://austin.publicbikesystem.net/customer/gbfs/v2/en/station_information.json",stationStatusUrl:"https://austin.publicbikesystem.net/customer/gbfs/v2/en/station_status.json",provider:"CapMetro"},{id:"honolulu-biki",city:"Honolulu, HI",centerLat:21.3069,centerLon:-157.8583,loadRadiusKm:90,stationInformationUrl:"https://hon.publicbikesystem.net/customer/gbfs/v2/en/station_information.json",stationStatusUrl:"https://hon.publicbikesystem.net/customer/gbfs/v2/en/station_status.json",provider:"Biki"},{id:"columbus-cogo",city:"Columbus, OH",centerLat:39.9612,centerLon:-82.9988,loadRadiusKm:90,stationInformationUrl:"https://gbfs.cogobikeshare.com/gbfs/2.3/en/station_information.json",stationStatusUrl:"https://gbfs.cogobikeshare.com/gbfs/2.3/en/station_status.json",provider:"CoGo"},{id:"chattanooga-bikechatt",city:"Chattanooga, TN",centerLat:35.0456,centerLon:-85.3097,loadRadiusKm:90,stationInformationUrl:"https://chat.publicbikesystem.net/customer/gbfs/v2/en/station_information.json",stationStatusUrl:"https://chat.publicbikesystem.net/customer/gbfs/v2/en/station_status.json",provider:"Bike Chattanooga"},pt({id:"boulder-bcycle",city:"Boulder, CO",centerLat:40.015,centerLon:-105.2705,systemId:"bcycle_boulder"}),pt({id:"milwaukee-bublr",city:"Milwaukee, WI",centerLat:43.0389,centerLon:-87.9065,systemId:"bcycle_bublr",provider:"Bublr"}),pt({id:"madison-bcycle",city:"Madison, WI",centerLat:43.0731,centerLon:-89.4012,systemId:"bcycle_madison"}),pt({id:"nashville-bcycle",city:"Nashville, TN",centerLat:36.1627,centerLon:-86.7816,systemId:"bcycle_nashville"}),pt({id:"salt-lake-greenbike",city:"Salt Lake City, UT",centerLat:40.7608,centerLon:-111.891,systemId:"bcycle_greenbikeslc",provider:"GREENbike"}),pt({id:"san-antonio-bcycle",city:"San Antonio, TX",centerLat:29.4241,centerLon:-98.4936,systemId:"bcycle_sanantonio"}),pt({id:"cincinnati-red-bike",city:"Cincinnati, OH",centerLat:39.1031,centerLon:-84.512,systemId:"bcycle_cincyredbike",provider:"Red Bike"}),pt({id:"el-paso-bcycle",city:"El Paso, TX",centerLat:31.7619,centerLon:-106.485,systemId:"bcycle_elpaso"}),pt({id:"indianapolis-pacers",city:"Indianapolis, IN",centerLat:39.7684,centerLon:-86.1581,systemId:"bcycle_pacersbikeshare",provider:"Pacers Bikeshare"}),pt({id:"fort-lauderdale-broward",city:"Fort Lauderdale, FL",centerLat:26.1224,centerLon:-80.1373,systemId:"bcycle_broward",provider:"Broward B-cycle"}),pt({id:"memphis-bcycle",city:"Memphis, TN",centerLat:35.1495,centerLon:-90.049,systemId:"bcycle_memphis"}),pt({id:"des-moines-bcycle",city:"Des Moines, IA",centerLat:41.5868,centerLon:-93.625,systemId:"bcycle_desmoines"}),pt({id:"tucson-tugo",city:"Tucson, AZ",centerLat:32.2226,centerLon:-110.9747,systemId:"bcycle_tugo",provider:"Tugo"}),pt({id:"fort-worth-trinity",city:"Fort Worth, TX",centerLat:32.7555,centerLon:-97.3308,systemId:"bcycle_fortworth",provider:"Trinity Metro"}),pt({id:"omaha-heartland",city:"Omaha, NE",centerLat:41.2565,centerLon:-95.9345,systemId:"bcycle_heartland",provider:"Heartland B-cycle"}),pt({id:"lincoln-bikelnk",city:"Lincoln, NE",centerLat:40.8136,centerLon:-96.7026,systemId:"bcycle_bikelnk",provider:"BikeLNK"}),pt({id:"greenville-sc-bcycle",city:"Greenville, SC",centerLat:34.8526,centerLon:-82.394,systemId:"bcycle_greenville"}),pt({id:"buffalo-reddy",city:"Buffalo, NY",centerLat:42.8864,centerLon:-78.8784,systemId:"bcycle_reddy",provider:"Reddy Bikeshare"}),pt({id:"las-vegas-rtc-bike-share",city:"Las Vegas, NV",centerLat:36.1699,centerLon:-115.1398,systemId:"bcycle_rtcbikeshare",provider:"RTC Bike Share"}),pt({id:"santa-barbara-bcycle",city:"Santa Barbara, CA",centerLat:34.4208,centerLon:-119.6982,systemId:"bcycle_santabarbara"})];function T2(e){const t=String((e==null?void 0:e.id)||"").trim().toLowerCase(),n=String((e==null?void 0:e.city)||"").trim(),i=Number(e==null?void 0:e.centerLat),o=Number(e==null?void 0:e.centerLon),r=Number(e==null?void 0:e.loadRadiusKm),s=new URL(String((e==null?void 0:e.stationInformationUrl)||"").trim()),a=new URL(String((e==null?void 0:e.stationStatusUrl)||"").trim());if(!t)throw new Error("GBFS entry id is required");if(!n)throw new Error(`GBFS entry "${t}" city is required`);if(!Number.isFinite(i)||!Number.isFinite(o))throw new Error(`GBFS entry "${t}" has invalid center coordinates`);if(s.protocol!=="https:"||a.protocol!=="https:")throw new Error(`GBFS entry "${t}" must use https URLs`);if(!/\/station_information\.json$/i.test(s.pathname))throw new Error(`GBFS entry "${t}" station_information URL is invalid`);if(!/\/station_status\.json$/i.test(a.pathname))throw new Error(`GBFS entry "${t}" station_status URL is invalid`);const c=Array.from(new Set([s.hostname.toLowerCase(),a.hostname.toLowerCase()]));return{id:t,city:n,centerLat:i,centerLon:o,loadRadiusKm:Number.isFinite(r)&&r>0?r:CITY_RANGE_BASE_KM,stationInformationUrl:s.toString(),stationStatusUrl:a.toString(),provider:String((e==null?void 0:e.provider)||"GBFS").trim()||"GBFS",hosts:c}}const Am=(()=>{const e=new Set;return E2.map(t=>{const n=T2(t);if(e.has(n.id))throw new Error(`Duplicate GBFS city id: ${n.id}`);return e.add(n.id),n})})(),I_=new Map(Am.map(e=>[e.id,e]));function k2({state:e,services:t,parts:n,source:i}){function o(f){return`/api/gbfs/${encodeURIComponent(f)}`}function r(){e._loadingOps++,e._loading=!0}function s(){e._loadingOps=Math.max(0,e._loadingOps-1),e._loading=e._loadingOps>0}async function a(f,p){return i.getStations(f,p)}function c(f,p){var _;const g=f.get(p);if(g){try{(_=g.controller)==null||_.abort()}catch{}f.delete(p)}}function l(){for(const f of e._inFlightInfo.keys())c(e._inFlightInfo,f);for(const f of e._inFlightStatus.keys())c(e._inFlightStatus,f)}async function u(f,p){if(e._stationInfoCache.has(f))return e._stationInfoCache.get(f);const g=e._inFlightInfo.get(f);if(g)return g.promise;const _=I_.get(f);if(!_)throw new Error(`Unknown GBFS city "${f}"`);const m=new AbortController,b=(async()=>{r();try{const C=await a(_.stationInformationUrl,{signal:m.signal}),y=n.model.parseStationInformation(C);if(y.size===0)throw new Error(`No station information for ${_.city}`);return e._stationInfoCache.set(f,y),y}finally{s()}})().finally(()=>{const C=e._inFlightInfo.get(f);C&&C.controller===m&&e._inFlightInfo.delete(f)});return e._inFlightInfo.set(f,{promise:b,controller:m,generation:p}),b}async function h(f,p){const g=e._inFlightStatus.get(f);if(g)return g.promise;const _=I_.get(f);if(!_)throw new Error(`Unknown GBFS city "${f}"`);const m=new AbortController,b=(async()=>{r();try{const C=await a(_.stationStatusUrl,{signal:m.signal}),y=n.model.parseStationStatus(C);return e._statusCache.set(f,{statusMap:y,timestamp:Date.now()}),y}finally{s()}})().finally(()=>{const C=e._inFlightStatus.get(f);C&&C.controller===m&&e._inFlightStatus.delete(f)});return e._inFlightStatus.set(f,{promise:b,controller:m,generation:p}),b}return{toProxyUrl:o,beginLoading:r,endLoading:s,fetchGbfsJson:a,abortInFlight:c,abortAllInFlight:l,loadCityStationInfo:u,loadCityStationStatus:h,methods:{async update(){if(!e._enabled||e._activeCityIds.size===0)return;const f=e._proximityGeneration,p=Array.from(e._activeCityIds);await Promise.all(p.map(async g=>{try{const _=await h(g,f);if(!e._enabled||!e._activeCityIds.has(g)||f!==e._proximityGeneration)return;n.rendering.applyStatusToPoints(g,_)}catch(_){if((_==null?void 0:_.name)==="AbortError")return;console.warn(`[Data:Bikeshare] ${g} status update error:`,_),e._error="GBFS status update failed"}})),e._count=e._stationRenderMap.size,e._count>0&&(e._lastUpdate=Date.now())}}}}function A2({state:e,services:t,parts:n,source:i}){function o(h,d=!0){if(h==null)return d;if(typeof h=="boolean")return h;const f=Number(h);if(Number.isFinite(f))return f!==0;const p=String(h).trim().toLowerCase();return p==="true"||p==="yes"?!0:p==="false"||p==="no"?!1:d}function r(h,d=null){const f=Number(h);return!Number.isFinite(f)||f<0?d:Math.round(f)}function s(h,d){return`${h}:${d}`}function a(h,d,f,p){const g=v=>v*Math.PI/180,_=g(f-h),m=g(p-d),b=g(h),C=g(f),y=Math.sin(_/2)**2+Math.cos(b)*Math.cos(C)*Math.sin(m/2)**2;return 6371*2*Math.atan2(Math.sqrt(y),Math.sqrt(1-y))}function c(h){const d=h==null?void 0:h.data;if(Array.isArray(d==null?void 0:d.stations))return d.stations;if(Array.isArray(d))return d;if(d&&typeof d=="object"){for(const f of Object.values(d))if(Array.isArray(f==null?void 0:f.stations))return f.stations}return[]}function l(h){const d=c(h),f=new Map;for(const p of d){const g=String((p==null?void 0:p.station_id)??(p==null?void 0:p.id)??"").trim(),_=Number((p==null?void 0:p.lat)??(p==null?void 0:p.latitude)),m=Number((p==null?void 0:p.lon)??(p==null?void 0:p.longitude));!g||!Number.isFinite(_)||!Number.isFinite(m)||f.set(g,{stationId:g,name:String((p==null?void 0:p.name)||(p==null?void 0:p.short_name)||"").trim(),lat:_,lon:m,capacity:r(p==null?void 0:p.capacity),isInstalled:o(p==null?void 0:p.is_installed,!0),isRenting:o(p==null?void 0:p.is_renting,!0),isReturning:o(p==null?void 0:p.is_returning,!0)})}return f}function u(h){const d=c(h),f=new Map;for(const p of d){const g=String((p==null?void 0:p.station_id)??(p==null?void 0:p.id)??"").trim();if(!g)continue;const _=r(p==null?void 0:p.num_bikes_available),m=r(p==null?void 0:p.num_docks_available);f.set(g,{stationId:g,bikesAvailable:_,docksAvailable:m,isInstalled:o(p==null?void 0:p.is_installed,!0),isRenting:o(p==null?void 0:p.is_renting,!0),isReturning:o(p==null?void 0:p.is_returning,!0),lastReported:r(p==null?void 0:p.last_reported)})}return f}return{normalizeGbfsBool:o,toNonNegativeInteger:r,stationKey:s,haversineKm:a,extractStationsArray:c,parseStationInformation:l,parseStationStatus:u}}const hr="bikeshare-selected",I2=Object.freeze({cohortLimit:1,collisionCapacity:0,moving:!1}),pw=5e4,R2=pw-2e3,L2=pw+2e3,P2=340,x2=100,F2=6e4,ju=4,R_=12,qu=15,L_=2,P_=8e3,S2=Cesium.Color.fromCssColorString("#00ff88").withAlpha(.95),N2=Cesium.Color.fromCssColorString("#ffaa00").withAlpha(.94),D2=Cesium.Color.fromCssColorString("#ff4444").withAlpha(.94),Wu=Cesium.Color.fromCssColorString("#91a4b4").withAlpha(.62),O2=Cesium.Color.fromCssColorString("#687581").withAlpha(.48),B2=Cesium.Color.BLACK.withAlpha(.25);function V2({state:e,services:t,parts:n,source:i}){const{governorRequestRender:o}=t.render;function r(g){var m;const _=(m=g==null?void 0:g.camera)==null?void 0:m.positionCartographic;return _&&Number.isFinite(_.height)?_.height:1/0}function s(g){var b,C,y,v;const _=(y=(b=g==null?void 0:g.camera)==null?void 0:b.computeViewRectangle)==null?void 0:y.call(b,(C=g.scene.globe)==null?void 0:C.ellipsoid);if(_){const M=Cesium.Rectangle.center(_);return{lat:Cesium.Math.toDegrees(M.latitude),lon:Cesium.Math.toDegrees(M.longitude)}}const m=(v=g==null?void 0:g.camera)==null?void 0:v.positionCartographic;return m?{lat:Cesium.Math.toDegrees(m.latitude),lon:Cesium.Math.toDegrees(m.longitude)}:null}function a(g){return Number.isFinite(g)?(e._altitudeGateEnabled?g>=L2&&(e._altitudeGateEnabled=!1):g<=R2&&(e._altitudeGateEnabled=!0),e._altitudeGateEnabled):(e._altitudeGateEnabled=!1,!1)}function c(g){const _=new Set;if(!g)return _;for(const m of Am){const b=n.model.haversineKm(g.lat,g.lon,m.centerLat,m.centerLon),C=Math.max(x2,m.loadRadiusKm);b<=C&&_.add(m.id)}return _}function l(g){o("bikeshare-deactivate"),n.ingestion.abortInFlight(e._inFlightInfo,g),n.ingestion.abortInFlight(e._inFlightStatus,g),n.rendering.removeCityPoints(g)}function u(){const g=Array.from(e._activeCityIds);for(const _ of g)l(_);e._activeCityIds.clear()}async function h(g,_){var m;if(!(!e._enabled||!e._activeCityIds.has(g)))try{const b=await n.ingestion.loadCityStationInfo(g,_);if(!e._enabled||!e._activeCityIds.has(g)||_!==e._proximityGeneration)return;n.rendering.ensureCityPoints(g,b);const C=(m=e._statusCache.get(g))==null?void 0:m.statusMap;C&&n.rendering.applyStatusToPoints(g,C);const y=await n.ingestion.loadCityStationStatus(g,_);if(!e._enabled||!e._activeCityIds.has(g)||_!==e._proximityGeneration)return;n.rendering.applyStatusToPoints(g,y),e._lastUpdate=Date.now(),e._error=null}catch(b){if((b==null?void 0:b.name)==="AbortError")return;console.warn(`[Data:Bikeshare] ${g} activate error:`,b),e._error="GBFS fetch error",l(g),e._activeCityIds.delete(g)}finally{e._count=e._stationRenderMap.size}}async function d(){if(!e._enabled||!e._viewer)return;const g=++e._proximityGeneration,_=r(e._viewer);if(!a(_)){u();return}const m=s(e._viewer);if(!m)return;const b=c(m);for(const y of e._activeCityIds)b.has(y)||l(y);if(e._activeCityIds=b,e._activeCityIds.size===0){e._count=0;return}const C=[];for(const y of e._activeCityIds)e._cityRuntime.has(y)||C.push(y);C.length!==0&&await Promise.all(C.map(y=>h(y,g)))}function f(){clearTimeout(e._cameraDebounceTimer),e._cameraDebounceTimer=setTimeout(()=>{d()},P2)}function p(){e._enabled&&f()}return{getCameraAltitude:r,getCameraCenterLatLon:s,shouldActivateAtAltitude:a,computeInRangeCities:c,deactivateCity:l,deactivateAllCities:u,activateCity:h,runProximityCheck:d,scheduleProximityCheck:f,onCameraChanged:p}}function H2({state:e,services:t,parts:n,source:i}){const{governorRequestRender:o}=t.render;function r(f,p){const g=n.model.toNonNegativeInteger(f);if(g&&g>0)return g;const _=n.model.toNonNegativeInteger(p==null?void 0:p.bikesAvailable,0),m=n.model.toNonNegativeInteger(p==null?void 0:p.docksAvailable,0),b=_+m;return b>0?b:qu}function s(f){const p=Math.max(1,Math.min(80,Number(f)||qu)),g=Math.sqrt(p)/Math.sqrt(80),_=ju+g*(R_-ju);return Math.max(ju,Math.min(R_,_))}function a(f,p){if(!f)return Wu;if(!f.isInstalled||!f.isRenting||!f.isReturning)return O2;const g=n.model.toNonNegativeInteger(f.bikesAvailable);if(!Number.isFinite(g))return Wu;const _=Math.max(1,Number(p)||qu),m=g/_;return m>.6?S2:m>=.3?N2:D2}function c(f){var m,b;const p=Number(f==null?void 0:f.lon),g=Number(f==null?void 0:f.lat);if(!Number.isFinite(g)||!Number.isFinite(p))return null;let _=L_;if((b=(m=e._viewer)==null?void 0:m.scene)!=null&&b.sampleHeightSupported){const C=Cesium.Cartographic.fromDegrees(p,g),y=e._viewer.scene.sampleHeight(C);Number.isFinite(y)&&(_=y+L_)}return Cesium.Cartesian3.fromDegrees(p,g,_)}function l(f){if(e._cityRuntime.has(f))return e._cityRuntime.get(f);const p={stationKeys:new Set};return e._cityRuntime.set(f,p),p}function u(f,p){o("bikeshare-points");const g=l(f);for(const _ of p.values()){const m=n.model.stationKey(f,_.stationId);if(e._stationRenderMap.has(m)){g.stationKeys.add(m);continue}if(e._stationRenderMap.size>=P_){e._limitWarned||(e._limitWarned=!0,console.warn(`[Data:Bikeshare] Point cap reached (${P_}).`));break}const b=c(_);if(!b)continue;const C=e._pointCollection.add({position:b,pixelSize:s(_.capacity),color:Wu,outlineColor:B2,outlineWidth:1,scaleByDistance:new Cesium.NearFarScalar(200,1.35,13e4,.4),translucencyByDistance:new Cesium.NearFarScalar(200,1,18e4,.15),disableDepthTestDistance:2500,id:m});e._stationRenderMap.set(m,{key:m,cityId:f,stationId:_.stationId,stationName:_.name,point:C,capacity:n.model.toNonNegativeInteger(_.capacity),bikesAvailable:null,docksAvailable:null,isInstalled:_.isInstalled,isRenting:_.isRenting,isReturning:_.isReturning}),g.stationKeys.add(m)}e._count=e._stationRenderMap.size}function h(f){const p=e._cityRuntime.get(f);if(p){e._selectedKey&&p.stationKeys.has(e._selectedKey)&&n.selection._clearSelection();for(const g of p.stationKeys){const _=e._stationRenderMap.get(g);_&&(e._pointCollection.remove(_.point),e._stationRenderMap.delete(g))}e._cityRuntime.delete(f),e._count=e._stationRenderMap.size}}function d(f,p){o("bikeshare-status");const g=e._cityRuntime.get(f);if(g)for(const _ of g.stationKeys){const m=e._stationRenderMap.get(_);if(!m)continue;const b=p.get(m.stationId)||null,C=r(m.capacity,b);m.capacity=C,m.bikesAvailable=n.model.toNonNegativeInteger(b==null?void 0:b.bikesAvailable),m.docksAvailable=n.model.toNonNegativeInteger(b==null?void 0:b.docksAvailable),m.isInstalled=n.model.normalizeGbfsBool(b==null?void 0:b.isInstalled,!0),m.isRenting=n.model.normalizeGbfsBool(b==null?void 0:b.isRenting,!0),m.isReturning=n.model.normalizeGbfsBool(b==null?void 0:b.isReturning,!0),m.point.pixelSize=s(C),m.point.color=a(b,C)}}return{resolveCapacity:r,capacityToPixelSize:s,statusToColor:a,createStationPosition:c,ensureCityRuntime:l,ensureCityPoints:u,removeCityPoints:h,applyStatusToPoints:d}}function $2({state:e,services:t,parts:n,source:i}){function o(u){const d=String((u==null?void 0:u.stationName)||"").trim()||(u!=null&&u.stationId?`Station ${u.stationId}`:"Station"),f=Number.isFinite(u==null?void 0:u.bikesAvailable)?u.bikesAvailable:"?",p=Number.isFinite(u==null?void 0:u.docksAvailable)?u.docksAvailable:"?",g=Number.isFinite(u==null?void 0:u.capacity)?u.capacity:"?",_=[d,`🚲 ${f} avail · ${p} docks · ${g} cap`],m=[];return(u==null?void 0:u.isInstalled)===!1&&m.push("⚠️ Not installed"),(u==null?void 0:u.isRenting)===!1&&m.push("⚠️ Not renting"),(u==null?void 0:u.isReturning)===!1&&m.push("⚠️ Not returning"),m.length>0&&_.push(m.join(" · ")),_.join(` +`)}function r(u,h){var g;const d=(g=h==null?void 0:h.point)==null?void 0:g.position;if(!u||!d)return null;const[f,...p]=o(h).split(` +`);return{id:String(u),position:d,variant:"selected",selected:!0,protected:!0,paintLane:"selected",collisionGroup:"ambient-card",priority:Number.MAX_SAFE_INTEGER,title:f,details:p,accent:"#00ffff",interactive:!1,anchorRadiusPx:9,minAnchorGapPx:11,verticalOnly:!0,placement:"above",edgeFade:"keyhole",horizonCull:!0,terrainOcclusion:!1}}function s(){if(e._selectedKey){const u=e._stationRenderMap.get(e._selectedKey);u!=null&&u.point&&(u.point.show=!0)}e._selectedEntity&&e._viewer&&e._viewer.entities.remove(e._selectedEntity),e._selectedKey=null,e._selectedEntity=null,e._overlayHost.clearSource(hr)}function a(u){var f;s();const h=e._stationRenderMap.get(u);if(!h||!((f=h.point)!=null&&f.position)||!e._viewer)return;e._selectedKey=u,h.point.show=!1,e._selectedEntity=e._viewer.entities.add({position:h.point.position,point:{pixelSize:14,color:Cesium.Color.CYAN,outlineColor:Cesium.Color.BLACK,outlineWidth:2,disableDepthTestDistance:Number.POSITIVE_INFINITY}});const d=r(u,h);d&&e._overlayHost.setEntries(hr,[d],I2)}function c(u){e._clickHandler||(e._clickHandler=new Cesium.ScreenSpaceEventHandler(u.scene.canvas),e._clickHandler.setInputAction(h=>{if(!Bt())return;const d=u.scene.pick(h.position);if(d){if(d.id===e._selectedEntity)return;const f=d.primitive;if(f&&typeof f.id=="string"&&e._stationRenderMap.has(f.id)){a(f.id);return}if(typeof d.id=="string"&&e._stationRenderMap.has(d.id)){a(d.id);return}}e._selectedKey&&s()},Cesium.ScreenSpaceEventType.LEFT_CLICK),document.addEventListener("keydown",l))}function l(u){u.key==="Escape"&&e._selectedKey&&s()}return{buildSelectionLabel:o,createBikeshareSelectedOverlayEntry:r,_clearSelection:s,_selectStation:a,_installClickHandler:c,_onKeyDown:l}}function G2({state:e,services:t,parts:n,source:i}){function o(s){const a=Number.isFinite(s.bikesAvailable)?s.bikesAvailable:"?",c=Number.isFinite(s.capacity)?s.capacity:"?",l=s.stationName||`Dock ${s.stationId}`;return`🚲 ${l.length>24?l.slice(0,22)+"…":l} [${a}/${c}]`}function r(s={}){var f,p;if(!e._enabled||!e._pointCollection||!e._pointCollection.show||e._stationRenderMap.size===0)return[];const a=[];for(const g of e._stationRenderMap.values()){const _=g.key===e._selectedKey;!((f=g.point)!=null&&f.show)&&!_||!((p=g.point)!=null&&p.position)||a.push(g)}if(a.length===0)return[];const c=Number.isFinite(s.maxCount)?Math.max(1,Math.floor(s.maxCount)):a.length,l=Number.isFinite(s.seed)?Math.floor(s.seed):0,u=Math.max(1,Math.ceil(a.length/c)),h=(l%u+u)%u,d=[];for(let g=h;g=c)break}return d}return{buildDetectionId:o,collectDetectableStations:r}}function U2({state:e,services:t,parts:n,source:i}){function o({viewer:a,key:c,record:l,overlayHost:u}){e._viewer=a,e._stationRenderMap=new Map([[c,l]]),e._selectedKey=null,e._selectedEntity=null,e._overlayHost=u||e.DEFAULT_OVERLAY_HOST}function r(a){n.selection._selectStation(a)}function s(){n.selection._clearSelection(),e._overlayHost=e.DEFAULT_OVERLAY_HOST}return{_setBikeshareSelectionStateForTest:o,_selectBikeshareStationForTest:r,_clearBikeshareSelectionForTest:s}}function z2({state:e,services:t,parts:n,source:i}){return{methods:{id:"bikeshare",name:"Bikeshare",icon:"🚲",source:"GBFS",updateInterval:F2,getDetectableObjects(r={}){return n.queries.collectDetectableStations(r)},getStats(){const r={count:e._count,lastUpdate:e._lastUpdate,loading:e._loading};return e._loading&&(r.loadingLabel=e._activeCityIds.size>0?`syncing ${e._activeCityIds.size} city feeds...`:"scanning nearby systems..."),e._error&&(r.error=e._error),r}}}}function j2({state:e,services:t,parts:n,source:i}){const{registerSpriteCollection:o,restoreSpriteOrder:r}=t.sprites,{registerPickOwner:s,unregisterPickOwner:a}=t.picking;return{methods:{init(l){e._viewer=l,e._pointCollection=new Cesium.PointPrimitiveCollection({blendOption:Cesium.BlendOption.TRANSLUCENT}),l.scene.primitives.add(e._pointCollection),o("bikeshare",e._pointCollection),e._pointCollection.show=!1,e._enabled=!1,e._cameraDebounceTimer=null,e._cameraChangedAttached=!1,e._altitudeGateEnabled=!1,e._proximityGeneration=0,e._activeCityIds=new Set,e._cityRuntime=new Map,e._stationInfoCache=new Map,e._statusCache=new Map,e._inFlightInfo=new Map,e._inFlightStatus=new Map,e._stationRenderMap=new Map,e._clickHandler=null,e._selectedKey=null,e._selectedEntity=null,e._count=0,e._lastUpdate=null,e._loading=!1,e._loadingOps=0,e._error=null,e._limitWarned=!1,e._overlayHost.setVisible(hr,!1),n.selection._installClickHandler(l),r(l),console.log(`[Data:Bikeshare] Initialized with ${Am.length} cities`)},enable(l){e._enabled=!0,e._error=null,e._pointCollection.show=!0,e._overlayHost.setVisible(hr,!0),n.selection._installClickHandler(l),s("bikeshare",u=>e._stationRenderMap.has(u)),e._cameraChangedAttached||(l.camera.changed.addEventListener(n.viewport.onCameraChanged),km(l.camera,"bikeshare",.05),e._cameraChangedAttached=!0),n.viewport.runProximityCheck(),r(l)},disable(l){e._enabled=!1,e._proximityGeneration++,e._altitudeGateEnabled=!1,clearTimeout(e._cameraDebounceTimer),e._cameraDebounceTimer=null,n.selection._clearSelection(),e._overlayHost.setVisible(hr,!1),e._clickHandler&&(e._clickHandler.destroy(),e._clickHandler=null),document.removeEventListener("keydown",n.selection._onKeyDown),a("bikeshare"),e._cameraChangedAttached&&(l.camera.changed.removeEventListener(n.viewport.onCameraChanged),hc(l.camera,"bikeshare"),e._cameraChangedAttached=!1),n.ingestion.abortAllInFlight(),n.viewport.deactivateAllCities(),e._cityRuntime.clear(),e._pointCollection.show=!1,e._count=0,e._loading=!1,e._loadingOps=0},destroy(l){e._enabled?this.disable(l):(n.selection._clearSelection(),e._overlayHost.setVisible(hr,!1),e._clickHandler&&(e._clickHandler.destroy(),e._clickHandler=null),document.removeEventListener("keydown",n.selection._onKeyDown),a("bikeshare")),e._cameraChangedAttached&&(l.camera.changed.removeEventListener(n.viewport.onCameraChanged),hc(l.camera,"bikeshare"),e._cameraChangedAttached=!1),n.ingestion.abortAllInFlight(),e._pointCollection&&(l.scene.primitives.remove(e._pointCollection),e._pointCollection=null),e._viewer=null}}}}function q2({services:e}){const{setOverlayEntries:t,setOverlaySourceVisible:n,clearOverlaySource:i}=e.overlays,o={};return o.DEFAULT_OVERLAY_HOST=Object.freeze({setEntries:t,setVisible:n,clearSource:i}),o._overlayHost=o.DEFAULT_OVERLAY_HOST,o._viewer=null,o._pointCollection=null,o._enabled=!1,o._cameraDebounceTimer=null,o._cameraChangedAttached=!1,o._altitudeGateEnabled=!1,o._proximityGeneration=0,o._activeCityIds=new Set,o._cityRuntime=new Map,o._stationInfoCache=new Map,o._statusCache=new Map,o._inFlightInfo=new Map,o._inFlightStatus=new Map,o._stationRenderMap=new Map,o._clickHandler=null,o._selectedKey=null,o._selectedEntity=null,o._count=0,o._lastUpdate=null,o._loading=!1,o._loadingOps=0,o._error=null,o._limitWarned=!1,o}function W2({fetchImpl:e=(...t)=>globalThis.fetch(...t)}={}){return{async getStations(t,{signal:n}={}){const i=new URL(t);if(i.protocol!=="https:"||i.username||i.password||i.hash)throw new TypeError("A public HTTPS GBFS URL is required");n==null||n.throwIfAborted();const o=await e("/api/gbfs/"+encodeURIComponent(i.href),{method:"GET",headers:{Accept:"application/json"},signal:n});if(!o.ok)throw new Error("GBFS HTTP "+o.status);const r=await o.json();if(n==null||n.throwIfAborted(),!r||typeof r!="object")throw new Error("Malformed GBFS payload");return r}}}function K2({services:e,source:t}){var r;if(typeof(t==null?void 0:t.getStations)!="function")throw new TypeError("A bikeshare source is required");const n=q2({services:e}),i={},o={state:n,services:e,parts:i,source:t};return i.ingestion=k2(o),i.model=A2(o),i.viewport=V2(o),i.rendering=H2(o),i.selection=$2(o),i.queries=G2(o),i.testing=U2(o),i.controls=z2(o),i.lifecycle=j2(o),Object.assign({},i.controls.methods,i.lifecycle.methods,(r=i.ingestion)==null?void 0:r.methods,{createBikeshareSelectedOverlayEntry:i.selection.createBikeshareSelectedOverlayEntry,_setBikeshareSelectionStateForTest:i.testing._setBikeshareSelectionStateForTest,_selectBikeshareStationForTest:i.testing._selectBikeshareStationForTest,_clearBikeshareSelectionForTest:i.testing._clearBikeshareSelectionForTest})}function Y2({source:e}){return K2({source:e,services:{render:Pt,sprites:Ki,picking:rn,overlays:ui}})}const $a={primary:"#8be9ff",amber:"#ffb547",cyan:"#39d0ff",green:"#5dff9f",red:"#ff6b6b"},Yi=Cesium.ClassificationType.BOTH,x_=Cesium.HeightReference.CLAMP_TO_GROUND;function gw(e){const t=new Cesium.CustomDataSource("gev-annotations");e.dataSources.add(t),_w();function n(h){return Cesium.Color.fromCssColorString($a[h.color]||$a.primary)}function i(){var d;const h=((d=e.camera.positionCartographic)==null?void 0:d.height)??1e3;return Math.max(14,Math.min(170,h*.03))}function o(h,d,{alpha:f=.9,pulse:p=!1}={}){return new Cesium.CallbackProperty(()=>{const g=(h.alpha??1)*f*(p?X2():1);return d.withAlpha(Math.max(0,Math.min(1,g)))},!1)}function r(h){const d=n(h),f=[];if(h._entities=f,h.ring&&h.ring.length>=3&&h.footprintKind==="building"){const p=e3(h.ring,3),g=Cesium.Cartesian3.fromDegreesArray(p.flat()),_=J2(e.scene,h.ring)??(Number.isFinite(h.anchor.height)?h.anchor.height-(h.buildingHeight||25):0),m=_-3,b=_+Math.max(18,h.buildingHeight||25)+24;f.push(t.entities.add({polygon:{hierarchy:new Cesium.PolygonHierarchy(g),height:m,extrudedHeight:b,perPositionHeight:!1,classificationType:Yi,material:new Cesium.ColorMaterialProperty(o(h,d,{alpha:.45,pulse:!0}))}}));const C=Cesium.Cartesian3.fromDegreesArray(Z2(p,14).flat());f.push(t.entities.add({polygon:{hierarchy:new Cesium.PolygonHierarchy(C),height:m,extrudedHeight:b,perPositionHeight:!1,fill:!1,outline:!0,outlineColor:o(h,d,{alpha:.32,pulse:!0})}})),f.push(t.entities.add({polyline:{positions:g,width:3,material:new Cesium.PolylineGlowMaterialProperty({glowPower:.25,color:o(h,d,{alpha:.7})}),clampToGround:!0,classificationType:Yi}})),h.label&&f.push(s(h,d,{point:!1}))}else if(h.ring&&h.ring.length>=3){const p=Cesium.Cartesian3.fromDegreesArray(h.ring.flat());f.push(t.entities.add({polygon:{hierarchy:new Cesium.PolygonHierarchy(p),material:new Cesium.ColorMaterialProperty(o(h,d,{alpha:h.synthesized?.1:.2,pulse:!0})),classificationType:Yi}})),f.push(t.entities.add({polyline:{positions:p,width:6,material:h.synthesized?new Cesium.PolylineDashMaterialProperty({color:o(h,d,{alpha:.95}),dashLength:24}):new Cesium.PolylineGlowMaterialProperty({glowPower:.35,color:o(h,d,{alpha:1})}),clampToGround:!0,classificationType:Yi}})),h.label&&f.push(s(h,d,{point:!1}))}else if(h.type==="route"&&Array.isArray(h.path)&&h.path.length>=2){const p=Cesium.Cartesian3.fromDegreesArray(h.path.flatMap(g=>[g.lon,g.lat]));f.push(t.entities.add({polyline:{positions:p,width:9,material:new is($a[h.color]||$a.primary),clampToGround:!0,classificationType:Yi}})),h.label&&f.push(s(h,d,{point:!1}))}else if(h.type==="arrow"&&h.to){const p=[Cesium.Cartesian3.fromDegrees(h.anchor.lon,h.anchor.lat),Cesium.Cartesian3.fromDegrees(h.to.lon,h.to.lat)];if(f.push(t.entities.add({polyline:{positions:p,width:16,material:new Cesium.PolylineArrowMaterialProperty(o(h,d,{alpha:.95})),clampToGround:!0,classificationType:Yi}})),h.label){const g={lon:(h.anchor.lon+h.to.lon)/2,lat:(h.anchor.lat+h.to.lat)/2};f.push(t.entities.add({position:Cesium.Cartesian3.fromDegrees(g.lon,g.lat),label:a(h)}))}}else h.type!=="label"&&f.push(t.entities.add({position:Cesium.Cartesian3.fromDegrees(h.anchor.lon,h.anchor.lat),ellipse:{semiMajorAxis:new Cesium.CallbackProperty(i,!1),semiMinorAxis:new Cesium.CallbackProperty(i,!1),material:new Cesium.ColorMaterialProperty(o(h,d,{alpha:.38,pulse:!0})),outline:!1,classificationType:Yi}})),f.push(s(h,d,{point:!0}))}function s(h,d,{point:f}){return t.entities.add({position:Cesium.Cartesian3.fromDegrees(h.anchor.lon,h.anchor.lat),point:f?{pixelSize:h.type==="label"?8:14,color:o(h,d,{alpha:1}),outlineColor:o(h,Cesium.Color.WHITE,{alpha:.95}),outlineWidth:3,heightReference:x_,disableDepthTestDistance:Number.POSITIVE_INFINITY}:void 0,label:h.label?a(h):void 0})}function a(h,d){return{text:h.label,font:'600 14px "Inter", system-ui, sans-serif',fillColor:o(h,Cesium.Color.WHITE,{alpha:1}),outlineColor:o(h,Cesium.Color.BLACK,{alpha:.85}),outlineWidth:3,style:Cesium.LabelStyle.FILL_AND_OUTLINE,verticalOrigin:Cesium.VerticalOrigin.BOTTOM,pixelOffset:new Cesium.Cartesian2(0,-16),showBackground:!0,backgroundColor:new Cesium.CallbackProperty(()=>Cesium.Color.fromCssColorString("#0b1622").withAlpha(.72*(h.alpha??1)),!1),backgroundPadding:new Cesium.Cartesian2(8,5),heightReference:x_,disableDepthTestDistance:Number.POSITIVE_INFINITY,scaleByDistance:new Cesium.NearFarScalar(500,1.05,14e3,.55)}}function c(h){if(h!=null&&h._entities){for(const d of h._entities)try{t.entities.remove(d)}catch{}h._entities=null}}function l(){}function u(){try{e.dataSources.remove(t,!0)}catch{}}return{add:r,remove:c,sync:l,destroy:u}}function X2(){return .8+.2*Math.sin(performance.now()*.005)}function Q2(e){return new Cesium.Material({fabric:{type:"GevRouteFlow",uniforms:{color:Cesium.Color.fromCssColorString(e).withAlpha(.95),time:0,repeat:64,duty:.46,speed:.55},source:` + czm_material czm_getMaterial(czm_materialInput materialInput) { + czm_material m = czm_getDefaultMaterial(materialInput); + float s = materialInput.st.s; // 0 origin -> 1 dest + float flow = fract(s * repeat - time * speed); // scroll toward dest + float on = smoothstep(duty + 0.08, duty - 0.08, flow); + // keep a faint baseline so the whole route stays readable between dashes + float a = max(on, 0.18); + m.diffuse = color.rgb; + m.emission = color.rgb * on * 0.9; // glow on the lit cells + m.alpha = color.a * a; + return m; + }`}})}let F_=!1;function _w(){F_||(Q2("#ffffff"),F_=!0)}function is(e){this._color=Cesium.Color.fromCssColorString(e).withAlpha(.95),this._definitionChanged=new Cesium.Event}Object.defineProperties(is.prototype,{isConstant:{get(){return!1}},definitionChanged:{get(){return this._definitionChanged}}});is.prototype.getType=function(){return"GevRouteFlow"};is.prototype.getValue=function(t,n){return Cesium.defined(n)||(n={}),n.color=this._color,n.time=performance.now()/1e3,n.repeat=64,n.duty=.46,n.speed=.55,n};is.prototype.equals=function(t){return this===t};function Z2(e,t){if(e.length<=t)return e;const n=[];for(let i=0;i-430&&g<9e3&&l.push(g)}}catch{}}return l.length?(l.sort((u,h)=>u-h),l[Math.floor(l.length*.3)]):null}function e3(e,t){let n=0,i=0;for(const[s,a]of e)n+=s,i+=a;n/=e.length,i/=e.length;const o=111320,r=o*Math.cos(Cesium.Math.toRadians(i));return e.map(([s,a])=>{const c=(s-n)*r,l=(a-i)*o,u=Math.hypot(c,l)||1,h=(u+t)/u;return[n+c*h/r,i+l*h/o]})}const t3=Object.freeze(Object.defineProperty({__proto__:null,FlowMaterialProperty:is,createWorldAnnotationRenderer:gw,ensureFlowFabricRegistered:_w},Symbol.toStringTag,{value:"Module"})),bw={slow:2,normal:6,fast:15},n3={slow:4,normal:10,fast:20},i3={slow:.08,normal:.2,fast:.45},vh={slow:20,normal:40,fast:90},us={orbitDeg:30,tiltDeg:15,rotateDeg:15,panViewFraction:.25,durationS:.9},Cw=Cesium.Math.toRadians(-89),yw=Cesium.Math.toRadians(-5),Im=260,vw=-32,o3=6.5,r3=120,s3=600,Mw=2.4,a3=.35,fc=10,S_=4,l3=.44,c3=2.2,u3=1.6,ww=20,d3=2200,Ew=26,h3=.5,f3=.9,Rm=90,m3=.9,N_=1e-6,Tw=4e3,p3=3e3,g3=96,kw=2,_3=55,b3=5e3,C3=8,y3=1.2,v3=10;function Aw(){try{return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches===!0}catch{return!1}}function fr(e,t,n,i){if(!Number.isFinite(e))return t;if(!Number.isFinite(t))return e;const o=1-Math.exp(-Math.max(0,n)*Math.max(0,i));return e+(t-e)*o}function Iw(e){return e>0?Math.min(a3,Mw/e):0}function Rw(e,t){const n=Math.min(1,Math.max(0,Number.isFinite(e)?e:0));if(!(t>0))return{distance:n,speed:1};const i=1-t,o=s=>t*(s*s*s-s*s*s*s/2),r=s=>s*s*(3-2*s);if(n<=t){const s=n/t;return{distance:o(s)/i,speed:r(s)}}if(n>=1-t){const s=(1-n)/t;return{distance:(i-o(s))/i,speed:r(s)}}return{distance:(t/2+(n-t))/i,speed:1}}function Lw(e,t=!1){if(t||!Number.isFinite(e))return 0;const n=e*l3;return Math.max(-fc,Math.min(fc,n))}function Pw(e,t,n=!1){if(n)return 0;const i=Number.isFinite(t)?Math.max(-1,Math.min(1,t)):0,o=1-Math.abs(i),r=Number.isFinite(e)?e:0;return Math.sin(2*Math.PI*r/d3)*ww*o+Math.abs(i)*Ew}function xw(e,t){const n=Number.isFinite(e)?e:0,i=n+Im+(Number.isFinite(t)?t:0);return Math.max(n+Rm,i)}function Mh(e,t,n){return Number.isFinite(t)?Number.isFinite(e)?fr(e,t,m3,n):t:e}const M3=Object.freeze({meanHeightM:Im,pitchDeg:vw,maxBankDeg:fc,minClearanceM:Rm,breathM:ww,turnLiftM:Ew,rampS:Mw}),w3=new Cesium.Cartesian3,E3=new Cesium.Cartesian3,Fw=new Cesium.Cartesian3,T3=new Cesium.Cartesian3,k3=new Cesium.Cartesian3,A3=new Cesium.Cartesian3,I3=new Cesium.Cartesian3,R3=new Cesium.Cartesian3,L3=new Cesium.Cartesian3,D_=new Cesium.Cartesian3,O_=new Cesium.Cartesian3,Ku=new Cesium.Cartesian3,Ga=new Cesium.Cartesian3,P3=new Cesium.Cartesian3,x3=new Cesium.Cartesian3,F3=new Cesium.Cartographic,S3=new Cesium.Cartographic,N3=new Cesium.Quaternion,D3=new Cesium.Matrix3,O3=new Cesium.Quaternion,B3=new Cesium.Matrix3,V3=new Cesium.Cartesian3,Sw=new Cesium.Cartographic,H3=new Cesium.Cartographic;function aa(e,t,n){const{pts:i,cumM:o}=e,r=Math.min(e.totalM,Math.max(0,t));let s=0,a=o.length-2;for(;s>1;o[u]<=r?s=u:a=u-1}const c=o[s+1]-o[s],l=c>1e-6?Math.min(1,Math.max(0,(r-o[s])/c)):0;return Cesium.Cartesian3.lerp(i[s],i[s+1],l,n)}function Yu(e,t,n,i,o){const r=aa(e,t,w3),s=aa(e,n,E3);Cesium.Cartesian3.subtract(s,r,o);const a=Cesium.Cartesian3.multiplyByScalar(i,Cesium.Cartesian3.dot(o,i),Fw);Cesium.Cartesian3.subtract(o,a,o);const c=Cesium.Cartesian3.magnitude(o);return c>.001?Cesium.Cartesian3.divideByScalar(o,c,o):null}function wh(e,t,n){const i=Cesium.Cartesian3.cross(e,t,T3),o=Cesium.Cartesian3.dot(i,n),r=Cesium.Cartesian3.dot(e,t);return r<=-1+N_&&Math.abs(o)0)||!(n>0)||!(i>0))return o;const r=Math.max(0,Math.min(e.totalM,t)),s=Math.max(0,Math.min(e.totalM,t+n)),a=new Set;for(let c=r;c<=s+1e-6&&o.length=o.length)}catch{}}if(Number.isFinite(e.meshProbeFloorM)&&i.push(e.meshProbeFloorM),!i.length)return!1;const r=Math.max(...i);return e.floorM=r,o.length&&!e.meshProbeCoveredCold?!1:(e.floorKnown=!0,!0)}function Bw(e,t){const n=Array.isArray(t)?t.length:0,i={heightM:Number.NaN,sampled:0,requested:n};if(!e||typeof e.sampleHeight!="function"||!n)return i;let o=Number.NaN,r=0;for(const s of t)try{const a=Cesium.Cartographic.fromDegrees(s.lon,s.lat,0,H3),c=e.sampleHeight(a);if(!Number.isFinite(c))continue;r+=1,o=Number.isFinite(o)?Math.max(o,c):c}catch{}return{heightM:o,sampled:r,requested:n}}function Vw({pts:e,cumM:t,speed:n="normal",floorFn:i=null,warmFn:o=null,probeFn:r=null,cameraHeightM:s=Number.NaN,reducedMotion:a=!1}){const c=t[t.length-1],l=vh[n]||vh.normal,u=Math.max(.5,c/l),h=Cesium.Cartographic.fromCartesian(e[0],Cesium.Ellipsoid.WGS84,Sw).height,d={kind:"route",mode:"continuous",direction:"forward",speed:n,pts:e,cumM:t,totalM:c,durationS:u,ramp:Iw(u),u:0,traveled:0,floorFn:i,warmFn:o,probeFn:r,reducedMotion:a,floorM:Number.NaN,floorKnown:!1,coldSeedFloorM:Dw(h,s),safeHoldHeightM:Number.isFinite(s)?s:Number.NaN,coldFrames:0,floorFromMeshProbe:!1,meshProbeSpent:!1,meshProbeFloorM:Number.NaN,meshProbeCoveredCold:!1,armS:0,armed:!1,departed:!1,appliedHeightM:Number.NaN,warmedCells:0,warmDueS:kw,offsetM:Number.NaN,bankLeadDeg:0,bankDeg:0,appliedBankDeg:0,liftBankDeg:0,headingDir:null,groundSpeedMps:0};return Nw(d,0,Tw),Ow(d),d}function Hw(e,t){const n=Math.min(.25,Math.max(0,Number.isFinite(t)?t:0));if((typeof e.floorFn=="function"||typeof e.probeFn=="function")&&!e.floorKnown&&!e.departed&&e.armS1e-6&&Cesium.Cartesian3.normalize(F,e.headingDir)}if(!e.headingDir){const S=Cesium.Cartesian3.fromElements(-a.y,a.x,0,D_);e.headingDir=Cesium.Cartesian3.magnitude(S)>1e-6?Cesium.Cartesian3.normalize(S,new Cesium.Cartesian3):Cesium.Cartesian3.fromElements(1,0,0,new Cesium.Cartesian3)}const b=e.headingDir,C=Cesium.Math.toRadians(vw),y=Cesium.Cartesian3.normalize(Cesium.Cartesian3.add(Cesium.Cartesian3.multiplyByScalar(b,Math.cos(C),Ga),Cesium.Cartesian3.multiplyByScalar(l,Math.sin(C),Ku),Ga),Ga),v=Cesium.Cartesian3.normalize(Cesium.Cartesian3.cross(y,l,O_),O_),M=Cesium.Cartesian3.normalize(Cesium.Cartesian3.cross(v,y,Ku),Ku),w=Cesium.Math.toRadians(g);let E=M;if(Math.abs(w)>1e-6){const S=Cesium.Quaternion.fromAxisAngle(y,w,N3),A=Cesium.Matrix3.fromQuaternion(S,D3);E=Cesium.Matrix3.multiplyByVector(A,M,x3)}e.warmDueS-=n,e.warmDueS<=0&&(e.warmDueS=kw,Nw(e,r,p3));let k=Number.NaN;if(typeof e.floorFn=="function"){const S=aa(e,r+_/2,A3),A=Cesium.Cartographic.fromCartesian(S,Cesium.Ellipsoid.WGS84,S3);try{const L=e.floorFn(Cesium.Math.toDegrees(c.latitude),Cesium.Math.toDegrees(c.longitude)),F=e.floorFn(Cesium.Math.toDegrees(A.latitude),Cesium.Math.toDegrees(A.longitude)),P=[L,F].filter(O=>Number.isFinite(O));P.length&&(k=Math.max(...P))}catch{k=Number.NaN}}Number.isFinite(k)?e.floorKnown?e.floorM=Mh(e.floorM,k,n):(e.floorM=Mh(e.floorM,k,n),e.floorKnown=!0):(e.floorM=Number.isFinite(e.floorM)?e.floorM:e.coldSeedFloorM,e.coldFrames+=1),e.liftBankDeg=fr(e.liftBankDeg,g,h3,n);const T=e.liftBankDeg/fc;e.offsetM=fr(e.offsetM,Pw(r,T,e.reducedMotion),f3,n);let I=Math.max(xw(e.floorM,e.offsetM),(Number.isFinite(k)?k:e.floorM)+Rm);!e.floorKnown&&Number.isFinite(e.safeHoldHeightM)&&(I=Math.max(I,e.safeHoldHeightM)),Number.isFinite(e.appliedHeightM)&&(I=Math.max(I,e.appliedHeightM-v3*n)),e.appliedHeightM=I;const R=Cesium.Cartesian3.fromRadians(c.longitude,c.latitude,I,Cesium.Ellipsoid.WGS84,P3);return e.appliedBankDeg=g,{finished:e.u>=1,eye:R,direction:y,up:E,bankDeg:g,heightM:I,aglM:I-e.floorM,groundSpeedMps:e.groundSpeedMps,progress:e.u}}let We=null,Li=null,Ge=null,Xu=null,Qu=[],B_=0;function fl(e){return e&&(B_+=1,e.motionId=B_),Ge=e,e}function $3(){return(Ge==null?void 0:Ge.motionId)||0}function G3(e,t="owner-cancel"){return!e||(Ge==null?void 0:Ge.motionId)!==e?{wasActive:!1,reason:t,leveled:!1}:St(t)}function U3(){try{We.camera.lookAtTransform(Cesium.Matrix4.IDENTITY)}catch{}}function z3(){try{const e=We==null?void 0:We.camera;if(!e||typeof e.setView!="function")return!1;const t=Cesium.Math.negativePiToPi(e.roll||0);return Math.abs(t)<1e-5?!1:(e.setView({orientation:{heading:e.heading,pitch:e.pitch,roll:0}}),!0)}catch{return!1}}function St(e="interrupt"){const t=!!Ge,n=!!(We!=null&&We.trackedEntity),i=t&&Ge.kind==="route";t&&!n&&(Ge.kind==="orbit"||Ge.kind==="route")&&U3();const o=i&&!n?z3():!1;return Ge=null,Vi("camera-verb"),{wasActive:t,reason:e,leveled:o}}function j3(){if(!Ge)return null;const e={kind:Ge.kind,mode:Ge.mode,speed:Ge.speed,motionId:Ge.motionId||0};return Ge.kind==="route"&&(e.progress=Ge.u,e.bankDeg=Ge.bankDeg,e.groundSpeedMps=Ge.groundSpeedMps,e.traveledM=Ge.traveled,e.totalM=Ge.totalM,e.reducedMotion=Ge.reducedMotion,e.arming=!Ge.departed,e.floorKnown=Ge.floorKnown,e.floorFromMeshProbe=Ge.floorFromMeshProbe,e.meshProbeSpent=Ge.meshProbeSpent),e}function q3(){if(!Ge||!We)return;const e=performance.now(),t=Math.min(.25,Math.max(.001,(e-(Ge.lastMs??e))/1e3));Ge.lastMs=e;const n=We.camera,i=Ge;let o=1;if(i.mode==="once"){i.elapsed=(i.elapsed||0)+t;const r=Math.min(1,i.elapsed/us.durationS);o=1-(1-r)*(1-r),r>=1&&St("once-complete")}try{if(i.kind==="orbit"&&i.pending){if(i.pendingS=(i.pendingS||0)+t,i.pendingS>30){St("orbit-arm-timeout");return}if(We.scene.tweens.length>0){i.settledS=0;return}if(i.settledS=(i.settledS||0)+t,i.settledS<.8)return;const r=Li==null?void 0:Li(We);if(!r)return;const s=We.camera,a=Cesium.Cartesian3.distance(s.positionWC,r),c=Cesium.Cartographic.fromCartesian(s.positionWC),l=Cesium.Cartographic.fromCartesian(r),u=c.height-l.height;i.target=r,i.hpr=new Cesium.HeadingPitchRange(s.heading,-Math.asin(Math.min(1,Math.max(-1,u/Math.max(1,a)))),a),i.hprStartHeading=s.heading,i.pending=!1,i.elapsed=0;return}if(i.kind==="orbit"){const r=Cesium.Math.toRadians(bw[i.speed])*(i.direction==="left"?-1:1);if(i.mode==="once"){const s=Cesium.Math.toRadians(us.orbitDeg)*(i.direction==="left"?-1:1);i.hpr.heading=i.hprStartHeading+s*o}else i.hpr.heading+=r*t;n.lookAt(i.target,i.hpr)}else if(i.kind==="pan"){const r=Math.max(50,n.positionCartographic.height),s=i.mode==="once"?r*us.panViewFraction*(o-(i.lastScale||0)):r*i3[i.speed]*t;i.lastScale=o,i.direction==="left"?n.moveLeft(s):i.direction==="right"?n.moveRight(s):i.direction==="up"?n.moveUp(s):n.moveDown(s)}else if(i.kind==="tilt"||i.kind==="rotate"){const r=n3[i.speed],s=i.mode==="once"?Cesium.Math.toRadians(i.kind==="tilt"?us.tiltDeg:us.rotateDeg)*(o-(i.lastScale||0)):Cesium.Math.toRadians(r)*t;if(i.lastScale=o,i.kind==="tilt"){const a=i.direction==="up",c=n.pitch+(a?s:-s);if(c>yw||cSt("manual-input");i.addEventListener(o,r,{passive:!0}),Qu.push(()=>i.removeEventListener(o,r))}}function Gw(e={},t=null){var c,l;const n=String(e.motion||"").toLowerCase(),i=e.direction?String(e.direction).toLowerCase():null,o=bw[String(e.speed||"normal").toLowerCase()]?String(e.speed||"normal").toLowerCase():"normal",r=e.mode==="continuous"?"continuous":"once";if(n==="stop"){const u=!!Ge,h=()=>{const{wasActive:d}=St("voice-stop");return{ok:!0,action:"move_camera",motion:"stop",stopped:u||d}};return typeof t=="function"?t(h):h()}if(!["orbit","pan","tilt","rotate"].includes(n))return{ok:!1,action:"move_camera",error:`Unknown motion "${e.motion}" — use orbit, pan, tilt, rotate, or stop.`};if(n!=="orbit"&&!["left","right","up","down"].includes(i))return{ok:!1,action:"move_camera",error:`${n} needs a direction (left/right${n!=="rotate"?"/up/down":""}).`};if(n==="rotate"&&!["left","right"].includes(i))return{ok:!1,action:"move_camera",error:"rotate needs left or right."};if(n==="tilt"){const u=We.camera.pitch;if(i==="up"&&u>=yw-Cesium.Math.toRadians(.5))return{ok:!1,action:"move_camera",error:"Already at the upper tilt limit (near the horizon) — tilt down, or zoom/pan instead."};if(i==="down"&&u<=Cw+Cesium.Math.toRadians(.5))return{ok:!1,action:"move_camera",error:"Already looking straight down — tilt up to raise the horizon."}}if(n==="orbit"&&(We!=null&&We.trackedEntity)&&typeof t!="function")return{ok:!1,action:"move_camera",error:`Already following ${((c=We.trackedEntity)==null?void 0:c.name)||((l=We.trackedEntity)==null?void 0:l.id)||"the tracked target"} — the follow camera owns the view while tracking. Say "stop tracking" first if you want a free orbit.`};const s=()=>{St("replaced");const u={kind:n,direction:i||"right",speed:o,mode:r};if(n==="orbit"){if(We.scene.tweens.length>0)return fl({kind:"orbit",direction:i||"right",speed:o,mode:r,pending:!0}),ii("camera-verb"),{ok:!0,action:"move_camera",motion:n,direction:i||"right",speed:o,mode:r,armed:"waiting-for-arrival"};const h=Li==null?void 0:Li(We);if(!h)return fl({kind:"orbit",direction:i||"right",speed:o,mode:r,pending:!0}),ii("camera-verb"),{ok:!0,action:"move_camera",motion:n,direction:i||"right",speed:o,mode:r,armed:"waiting-for-arrival"};const d=We.camera,f=Cesium.Cartesian3.distance(d.positionWC,h),p=Cesium.Cartographic.fromCartesian(d.positionWC),g=Cesium.Cartographic.fromCartesian(h),_=p.height-g.height,m=-Math.asin(Math.min(1,Math.max(-1,_/Math.max(1,f))));u.target=h,u.hpr=new Cesium.HeadingPitchRange(d.heading,m,f),u.hprStartHeading=d.heading}return fl(u),ii("camera-verb"),{ok:!0,action:"move_camera",motion:n,direction:u.direction,speed:o,mode:r}},a=n==="orbit"&&We.scene.tweens.length>0&&!We.trackedEntity;return typeof t=="function"?t(s,{preserveCameraFlight:a}):s()}function Uw(e){return!Ge||Ge.kind!=="orbit"||!Ge.hpr?!1:(Ge.hpr.range=Math.max(80,Math.min(5e6,Ge.hpr.range*e)),!0)}function zw(e,t={},n=null,i=null,o=null){const r=vh[String(t.speed||"normal").toLowerCase()]?String(t.speed||"normal").toLowerCase():"normal",s=(e||[]).filter(h=>h.type==="route"&&Array.isArray(h.path)&&h.path.length>=2);if(!s.length)return{ok:!1,action:"fly_route",error:'No route is drawn — draw a route first (e.g. "route from A to B"), then fly it.'};let a=s[s.length-1];if(t.label){const h=String(t.label).toLowerCase(),d=s.filter(f=>String(f.label||"").toLowerCase().includes(h));if(!d.length)return{ok:!1,action:"fly_route",error:`No route matches "${t.label}" — say fly the route without a name for the newest one.`};a=d[d.length-1]}if(a.path.some(h=>!Number.isFinite(h==null?void 0:h.lat)||h.lat<-90||h.lat>90||!Number.isFinite(h==null?void 0:h.lon)||h.lon<-180||h.lon>180||h.height!==void 0&&!Number.isFinite(h.height)))return{ok:!1,action:"fly_route",error:"The selected route has an invalid waypoint."};const c=a.path.map(h=>Cesium.Cartesian3.fromDegrees(h.lon,h.lat,h.height||0)),l=[0];for(let h=1;h{var h,d;return St("replaced"),fl(Vw({pts:c,cumM:l,speed:r,floorFn:n,warmFn:o,probeFn:f=>Bw(We==null?void 0:We.scene,f),cameraHeightM:(d=(h=We==null?void 0:We.camera)==null?void 0:h.positionCartographic)==null?void 0:d.height,reducedMotion:Aw()})),ii("camera-verb"),{ok:!0,action:"fly_route",label:a.label||null,speed:r,distanceM:Math.round(Ge.totalM),durationS:Math.round(Ge.durationS),waypoints:c.length,motionId:Ge.motionId}};return typeof i=="function"?i(u):u()}const W3=Object.freeze(Object.defineProperty({__proto__:null,ROUTE_CINEMA:M3,activeCameraMotionId:$3,adjustOrbitRange:Uw,advanceRouteFlight:Hw,approachValue:fr,createRouteFlight:Vw,flyRoute:zw,getActiveCameraMotion:j3,initCameraVerbs:$w,interruptCameraMotion:St,interruptCameraMotionIfActive:G3,moveCamera:Gw,prefersReducedMotion:Aw,probeMeshFloorM:Bw,routeAltitudeOffsetM:Pw,routeBankTargetDeg:Lw,routeColdSeedFloorM:Dw,routeCorridorCells:Lm,routeEyeHeightM:xw,routeFloorHoldM:Mh,routeRampFraction:Iw,routeSpeedProfile:Rw,signedTurnRad:wh},Symbol.toStringTag,{value:"Module"})),K3=GC({source:ts.terrain}),{cachedEllipsoidalGround:Y3,cachedRealEllipsoidalGround:X3,resolveEllipsoidalGround:Q3}=K3,Z3=Object.freeze(Object.defineProperty({__proto__:null,cachedEllipsoidalGround:Y3,cachedRealEllipsoidalGround:X3,resolveEllipsoidalGround:Q3},Symbol.toStringTag,{value:"Module"})),J3=UC({terrain:Z3}),{GROUND_FLOOR_LIFT_M:eB,MESH_FLOOR_BELOW_PRIOR_M:tB,MESH_FLOOR_ABOVE_PRIOR_M:nB,coarseFloorCoord:iB,floorAltitudeM:oB,displayFloorHeightM:rB,FLOOR_CELL_DEG:sB,NEIGHBOR_FLOOR_MIN_SAMPLES:aB,neighborFloorM:lB,CORRIDOR_MAX_CELLS:cB,CORRIDOR_WALK_STEP_DEG:uB,CELL_HYSTERESIS_DEG:dB,stickyFloorCell:hB,corridorFloorCells:fB,allocateCorridorCells:mB,setMeshFloorPreferred:pB,meshFloorPreferred:gB,reportMeshFloorCell:_B,meshFloorSampleWithinPrior:bB,reportValidatedMeshFloorCell:CB,cachedMeshFloor:yB,_clearMeshFloorCellsForTest:vB,cachedGroundFloor:MB,FLOOR_RESOLVE_DEADLINE_MS:wB,resolveGroundFloorCellsBounded:EB,resolveGroundFloorCells:TB,warmGroundFloor:kB}=J3,jw=Object.freeze(Object.defineProperty({__proto__:null,CELL_HYSTERESIS_DEG:dB,CORRIDOR_MAX_CELLS:cB,CORRIDOR_WALK_STEP_DEG:uB,FLOOR_CELL_DEG:sB,FLOOR_RESOLVE_DEADLINE_MS:wB,GROUND_FLOOR_LIFT_M:eB,MESH_FLOOR_ABOVE_PRIOR_M:nB,MESH_FLOOR_BELOW_PRIOR_M:tB,NEIGHBOR_FLOOR_MIN_SAMPLES:aB,_clearMeshFloorCellsForTest:vB,allocateCorridorCells:mB,cachedGroundFloor:MB,cachedMeshFloor:yB,coarseFloorCoord:iB,corridorFloorCells:fB,displayFloorHeightM:rB,floorAltitudeM:oB,meshFloorPreferred:gB,meshFloorSampleWithinPrior:bB,neighborFloorM:lB,reportMeshFloorCell:_B,reportValidatedMeshFloorCell:CB,resolveGroundFloorCells:TB,resolveGroundFloorCellsBounded:EB,setMeshFloorPreferred:pB,stickyFloorCell:hB,warmGroundFloor:kB},Symbol.toStringTag,{value:"Module"}));function Pm(e){if(!Number.isFinite(e)||e<0)return"";if(e<100)return`${Math.round(e)} m`;if(e<1e3)return`${Math.round(e/10)*10} m`;const t=e/1e3;return`${t<10?t.toFixed(1):Math.round(t)} km`}function qw(e){if(!Number.isFinite(e)||e<0)return"";if(e<60)return`${Math.round(e)} s`;const t=Math.round(e/60);if(t<60)return`${t} min`;const n=Math.floor(t/60),i=t%60;return i?`${n} h ${i} min`:`${n} h`}const Xo="directions-step",AB=Object.freeze({cohortLimit:1,collisionCapacity:0,moving:!1}),xm=Object.freeze({car:Object.freeze({chip:"DRIVE",word:"Drive",icon:"🚗"}),foot:Object.freeze({chip:"WALK",word:"Walk",icon:"🚶"}),bike:Object.freeze({chip:"BIKE",word:"Bike",icon:"🚲"})}),V_="car",Fm="#39d0ff",IB=Cesium.Color.fromCssColorString("#5dff9f"),RB=Cesium.Color.fromCssColorString("#ff6b6b"),LB=Cesium.Color.WHITE.withAlpha(.95),PB=Cesium.Color.fromCssColorString(Fm),H_=8,xB=13,FB=15e3,Ww="directions",$_=9e4,SB=400,NB=2e3,DB=5,OB=250;function BB(e={}){const t={};if(e.mode!==void 0){const n=String(e.mode).toLowerCase();if(!xm[n])return null;t.mode=n}return e.arm!==void 0&&(t.arm=e.arm==="a"||e.arm==="b"?e.arm:null),e.swap===!0&&(t.swap=!0),e.fly===!0&&(t.fly=!0),e.clear===!0&&(t.clear=!0),e.step!==void 0&&(t.step=Number.isInteger(e.step)&&e.step>=0?e.step:null),t}function VB(e){const{mode:t,armed:n,a:i,b:o,status:r,route:s,selectedStep:a,flightStep:c}=e,l=r==="routing",u=Object.entries(xm).map(([d,f])=>({id:`mode-${d}`,label:f.chip,active:t===d,state:t===d?"active":"idle",title:`${f.word} — reroute for ${f.word.toLowerCase()}`,params:{mode:d}}));u.push({id:"set-a",label:n==="a"?"CLICK MAP":i?"A ✓":"SET A",active:n==="a",state:n==="a"?"active":"idle",title:n==="a"?"Click a spot on the globe to place A (click again to cancel)":"Then click the globe to place the start",params:{arm:n==="a"?null:"a"}}),u.push({id:"set-b",label:n==="b"?"CLICK MAP":o?"B ✓":"SET B",active:n==="b",state:n==="b"?"active":"idle",title:n==="b"?"Click a spot on the globe to place B (click again to cancel)":"Then click the globe to place the destination",params:{arm:n==="b"?null:"b"}}),u.push({id:"swap",label:"⇄",disabled:!(i&&o)||l,state:"idle",title:"Swap A and B",params:{swap:!0}});const h=Number.isInteger(c);return u.push({id:"fly",label:l?"FLY ···":h?"FLYING":"FLY",disabled:!s||l,busy:l||h,active:h,state:l||h?"loading":"idle",title:s?"Fly the camera along the route":"Place A and B first",params:{fly:!0}}),u.push({id:"clear",label:"CLEAR",disabled:!i&&!o&&!s,state:"idle",title:"Remove the route and both markers",params:{clear:!0}}),{chips:u,legend:[],list:UB({route:s,selectedStep:a??null,flightStep:c??null})}}const HB=Object.freeze({draw:Object.freeze({name:"Draw",leave:"press Escape twice to leave Draw"})});function $B(e,t){const n=typeof e=="string"?e.trim():"";if(!n||n===Ww)return null;const i=t==="b"?"B":"A",o=HB[n],r=(o==null?void 0:o.name)||n,s=(o==null?void 0:o.leave)||`turn ${r} off`;return`${r} is active — ${s}, then set ${i}`}function G_(e){const t=Array.isArray(e)?e:[],n=[];for(let i=1;i=$_)return null;const n=e({id:`step-${a}`,ordinal:a+1,lead:Pm(s.distanceM)||"—",text:s.instruction,active:a===o,current:Number.isInteger(n)&&a===n,params:{step:a}}));return e.stepsTruncated&&r.push({id:"step-truncated",ordinal:r.length+1,lead:"",text:`Only the first ${i.length} turns of this route are shown`,active:!1,current:!1,disabled:!0}),{ariaLabel:"Turn-by-turn directions",items:r}}function zB(e,t){var i;if(!Array.isArray(e)||!e.length)return null;if(!Number.isFinite(t)||t<0)return 0;let n=0;for(let o=0;o0&&o.push(Pm(n.distanceM)),n.durationS>0&&o.push(qw(n.durationS)),i.push(`Step ${t+1} of ${e.length}${o.length?` · then ${o.join(" · ")}`:""}`);const r=e[t+1];return r&&i.push(`Then: ${r.instruction}`),{title:n.instruction,details:i}}function WB(e,t,n){return!Number.isInteger(e)||!t?null:{id:`directions-step-${e}`,position:t,variant:"selected",selected:!0,protected:!0,paintLane:"selected",collisionGroup:"ambient-card",priority:Number.MAX_SAFE_INTEGER,title:n.title,details:n.details,accent:Fm,interactive:!1,anchorRadiusPx:9,minAnchorGapPx:11,verticalOnly:!0,placement:"above",edgeFade:"keyhole",horizonCull:!0,terrainOcclusion:!1}}function KB(e,t,n){const i=`${t.lon.toFixed(6)},${t.lat.toFixed(6)};${n.lon.toFixed(6)},${n.lat.toFixed(6)}`;return`/api/route?profile=${encodeURIComponent(e)}&coords=${encodeURIComponent(i)}&steps=1`}function YB(e,t){if(!e||e.ok!==!0||!Array.isArray(e.geometry)||e.geometry.length<2)return null;const n=e.geometry.map(o=>[Number(o==null?void 0:o[0]),Number(o==null?void 0:o[1])]).filter(([o,r])=>Number.isFinite(o)&&Number.isFinite(r)&&Math.abs(r)<=90&&Math.abs(o)<=180);if(n.length<2)return null;const i=(Array.isArray(e.steps)?e.steps:[]).filter(o=>o&&typeof o.instruction=="string"&&Number.isFinite(o.lat)&&Number.isFinite(o.lon)).map((o,r)=>({...o,index:r}));return{distanceM:Math.max(0,Number(e.distanceM)||0),durationS:Math.max(0,Number(e.durationS)||0),geometry:n,steps:i,stepsTruncated:e.stepsTruncated===!0,mode:t}}function XB({services:e}){const t=Object.freeze({setEntries:(...te)=>e.overlays.setOverlayEntries(...te),setVisible:(...te)=>e.overlays.setOverlaySourceVisible(...te),clearSource:(...te)=>e.overlays.clearOverlaySource(...te)});let n=t,i=null,o=!1,r=V_,s=null,a=null,c=null,l="idle",u=null,h=null,d=0,f=null,p=null,g=null,_=null,m=null,b=null,C=null,y=null,v=!1,M=null,w=null,E=!1,k=null,T=null,I=0,R=null,S=null,A=null,L=0,F=0,P=null;function O(){return{enabled:o,mode:r,armed:s,a,b:c,status:l,error:u,route:h,lastUpdate:p,selectedStep:C,flightStep:S,pointerBlocked:E}}function D(){var te;try{M==null||M()}catch{}(te=w==null?void 0:w.refreshLayerStats)==null||te.call(w)}function $(){const te=o&&!!m;te&&!v?(e.render.holdContinuousRender("directions"),v=!0):!te&&v&&(e.render.releaseContinuousRender("directions"),v=!1)}function x(te){var ke;const de=i==null?void 0:i.scene;let U=null;if(de!=null&&de.pickPositionSupported&&typeof de.pickPosition=="function")try{U=de.pickPosition(te)}catch{U=null}if(!e.scenePick.isPickedWorldPosition(U)&&typeof((ke=i==null?void 0:i.camera)==null?void 0:ke.pickEllipsoid)=="function")try{U=i.camera.pickEllipsoid(te,Cesium.Ellipsoid.WGS84)}catch{U=null}if(!e.scenePick.isPickedWorldPosition(U))return null;const Le=Cesium.Cartographic.fromCartesian(U);return Le?{lat:Cesium.Math.toDegrees(Le.latitude),lon:Cesium.Math.toDegrees(Le.longitude)}:null}function N(te,de,U){return i.entities.add({id:`directions:marker:${te}`,position:Cesium.Cartesian3.fromDegrees(de.lon,de.lat,0),point:{pixelSize:14,color:U,outlineColor:Cesium.Color.BLACK,outlineWidth:2,heightReference:Cesium.HeightReference.CLAMP_TO_GROUND,disableDepthTestDistance:Number.POSITIVE_INFINITY},label:{text:te,font:'bold 13px "JetBrains Mono", "SF Mono", monospace',fillColor:Cesium.Color.WHITE,outlineColor:Cesium.Color.BLACK,outlineWidth:3,style:Cesium.LabelStyle.FILL_AND_OUTLINE,pixelOffset:new Cesium.Cartesian2(0,-20),heightReference:Cesium.HeightReference.CLAMP_TO_GROUND,disableDepthTestDistance:Number.POSITIVE_INFINITY}})}function G(te){var de;te&&i&&!((de=i.isDestroyed)!=null&&de.call(i))&&i.entities.remove(te)}function W(te,de){i&&(te==="a"?(G(g),g=N("A",de,IB)):(G(_),_=N("B",de,RB)))}function V(){oe(),H(),G(m),m=null,b==null||b.removeAll(),$()}function H(){A&&clearTimeout(A),A=null,L=0,F=0}function B(){if(A=null,!b||!h||!o)return;const te=h.steps,de=[];let U=0;for(const ke of G_(te)){const Ne=te[ke],Se=le(ke);if(!Se)continue;const Ue=U_(e.ground.cachedGroundFloor(Ne.lat,Ne.lon),e.ground.GROUND_FLOOR_LIFT_M);if(Ue===null){U+=1,Se.show=!1,de.push({lat:Ne.lat,lon:Ne.lon});continue}Se.position=Cesium.Cartesian3.fromDegrees(Ne.lon,Ne.lat,Ue),Se.show=!0}if(C!==null&&K(C),e.render.governorRequestRender("directions-anchor"),!U){L=0,F=0;return}e.ground.warmGroundFloor(de);const Le=GB(L,Date.now()-F);L+=1,Le!==null&&(A=setTimeout(B,Le))}function q(te){if(V(),!i)return;e.annotations.ensureFlowFabricRegistered();const de=Cesium.Cartesian3.fromDegreesArray(te.geometry.flat());m=i.entities.add({id:"directions:route",polyline:{positions:de,width:9,material:new e.annotations.FlowMaterialProperty(Fm),clampToGround:!0,classificationType:Cesium.ClassificationType.BOTH}});const U=[];for(const Le of G_(te.steps)){const ke=te.steps[Le];U.push({lat:ke.lat,lon:ke.lon}),b.add({id:`directions:step:${Le}`,position:Cesium.Cartesian3.fromDegrees(ke.lon,ke.lat,0),color:LB,pixelSize:H_,outlineColor:PB,outlineWidth:2,show:!1,disableDepthTestDistance:Number.POSITIVE_INFINITY})}e.ground.warmGroundFloor(U),L=0,F=Date.now(),B(),$(),e.sprites.restoreSpriteOrder(i),e.render.governorRequestRender("directions-route")}async function z(){if(!a||!c||!o)return;be("directions-reroute"),f==null||f.abort();const te=new AbortController;f=te;const de=setTimeout(()=>te.abort(),FB);d+=1;const U=d,Le=r;l="routing",u=null,D();try{const ke=await fetch(KB(Le,a,c),{signal:te.signal,headers:{Accept:"application/json"}}),Ne=await ke.json();if(ke.status===429)throw new Error(typeof(Ne==null?void 0:Ne.error)=="string"&&Ne.error?`${Ne.error} — try again in a moment`:"Routing is rate limited — try again in a moment");if(U!==d||!o)return;const Se=YB(Ne,Le);if(!Se){h=null,V(),l="error",u=(Ne==null?void 0:Ne.error)==="no route found"?"No route found between A and B":Ne!=null&&Ne.error?`Routing failed: ${Ne.error}`:"No route found between A and B";return}h=Se,l="ready",p=Date.now(),q(Se)}catch(ke){if(U!==d||!o)return;h=null,V(),l="error",u=(ke==null?void 0:ke.name)==="AbortError"?"Routing timed out":(ke==null?void 0:ke.name)==="TypeError"?"Routing unavailable — no response from the routing service":(ke==null?void 0:ke.message)||"Routing unavailable"}finally{clearTimeout(de),f===te&&(f=null),U===d&&D(),e.render.governorRequestRender("directions-route")}}function j(){T&&clearTimeout(T),T=null,k!==null&&e.input.releasePointer(k),k=null}function ne(){k===null||T||(T=setTimeout(()=>{T=null,j()},0))}function ee({afterDispatch:te=!1}={}){s=null,E=!1,te?ne():j()}function re(te,de){return te!=="a"&&te!=="b"||!Number.isFinite(de==null?void 0:de.lat)||!Number.isFinite(de==null?void 0:de.lon)?!1:(ee({afterDispatch:!0}),te==="a"?a=de:c=de,W(te,de),a&&c?z():D(),e.render.governorRequestRender("directions-place"),!0)}function se(te){var de;if(!te)return ee(),!1;if(!e.input.isLeaseCurrent(k)){const U=e.input.claimPointer(Ww);if(!U){s=null,E=!0;const Le=$B(e.input.pointerOwner(),te);return Le&&((de=P==null?void 0:P.showToast)==null||de.call(P,Le)),!1}k=U}return T&&(clearTimeout(T),T=null),E=!1,s=te,oe(),!0}function me(){f==null||f.abort(),f=null,d+=1,be("directions-clear"),ee(),a=null,c=null,h=null,l="idle",u=null,G(g),G(_),g=null,_=null,V(),e.render.governorRequestRender("directions-clear")}function be(te){if(J(),!I)return!1;const{wasActive:de}=e.camera.interruptCameraMotionIfActive(I,te);return I=0,S=null,de}function J(){R&&clearInterval(R),R=null}function Z(){J(),I&&(R=setInterval(()=>{const te=e.camera.getActiveCameraMotion();if(!te||te.motionId!==I){I=0,S=null,J(),D();return}const de=zB(h==null?void 0:h.steps,te.traveledM);de!==S&&(S=de,D())},OB))}function ae(){if(!h||!i)return!1;be("directions-refly"),e.camera.initCameraVerbs(i);const te=P,de=e.camera.flyRoute([{type:"route",label:"Directions",path:h.geometry.map(([U,Le])=>({lon:U,lat:Le,height:0}))}],{speed:"normal"},typeof(te==null?void 0:te.floorFn)=="function"?te.floorFn:null,typeof(te==null?void 0:te.runNavigation)=="function"?te.runNavigation:null,typeof(te==null?void 0:te.warmFn)=="function"?te.warmFn:null);return(de==null?void 0:de.ok)!==!0?(console.warn("[Data:Directions] fly refused:",(de==null?void 0:de.error)||de),!1):(I=de.motionId||0,S=0,Z(),!0)}function oe(){if(C!==null&&b){const te=le(C);te&&(te.pixelSize=H_)}C=null,n.clearSource(Xo)}function le(te){if(!b)return null;const de=`directions:step:${te}`;for(let U=0;U{if(!o)return;if(s&&e.input.isLeaseCurrent(k)){const ke=x(de.position);if(!ke)return;re(s,ke);return}if(!e.input.isPointerFree())return;let U=null;try{U=te.scene.pick(de.position)}catch{U=null}const Le=he(U);if(Le!==null){_e(Le);return}C!==null&&oe()},Cesium.ScreenSpaceEventType.LEFT_CLICK),typeof document<"u"&&document.addEventListener("keydown",Ce))}function ve(){y&&(y.destroy(),y=null),typeof document<"u"&&document.removeEventListener("keydown",Ce)}return{id:"directions",name:"Directions",icon:"🧭",source:"OSM routing",updateInterval:0,init(te){i=te,b=new Cesium.PointPrimitiveCollection({blendOption:Cesium.BlendOption.TRANSLUCENT}),te.scene.primitives.add(b),e.sprites.registerSpriteCollection("directions",b),b.show=!1,o=!1,r=V_,ee(),a=null,c=null,h=null,l="idle",u=null,S=null,n.setVisible(Xo,!1),e.sprites.restoreSpriteOrder(te),console.log("[Data:Directions] Initialized")},enable(te){o=!0,E=!1,b.show=!0,n.setVisible(Xo,!0),ye(te),e.picking.registerPickOwner("directions",de=>typeof de=="string"&&de.startsWith("directions:")),$(),e.sprites.restoreSpriteOrder(te)},disable(te){o=!1,me(),n.setVisible(Xo,!1),ve(),e.picking.unregisterPickOwner("directions"),b&&(b.show=!1),$()},async update(){},setParams(te={}){const de=BB(te);return de?(de.clear&&me(),de.mode!==void 0&&de.mode!==r&&(r=de.mode,a&&c&&o&&z()),de.arm!==void 0&&se(de.arm),de.swap&&a&&c&&([a,c]=[c,a],W("a",a),W("b",c),o&&z()),de.step!==void 0&&(de.step===null?oe():_e(de.step)),de.fly&&ae(),D(),e.render.governorRequestRender("directions-params"),!0):!1},getParams(){return{mode:r}},getRowControls(){return VB(O())},setRowControlsListener(te){M=typeof te=="function"?te:null},getStats(){return jB(O())},attachDataManager(te){w=te},attachShellServices(te){P=te||null},destroy(te){o&&this.disable(te),be("directions-destroy"),H(),ee(),P=null,w=null,M=null,b&&(e.sprites.unregisterSpriteCollection("directions",b),te.scene.primitives.remove(b),b=null),n.clearSource(Xo),i=null},placeEndpoint:re,_setOverlayHostForTest(te){n=te||t}}}const QB=Object.freeze({render:Pt,sprites:Ki,picking:rn,scenePick:HN,overlays:ui,annotations:t3,camera:W3,ground:jw,input:DI});function ZB(){return XB({services:QB})}function JB(){return ZB()}const Kw=Object.freeze(["bus","tram","subway","rail","ferry","unknown"]),z_=Object.freeze({bus:"🚌",tram:"🚊",subway:"🚇",rail:"🚆",ferry:"⛴️",unknown:"🚏"});function e5(e){return e?/^(Red|Orange|Blue)\b/.test(e)?"subway":/^(Green|Mattapan)/.test(e)?"tram":/^CR-/.test(e)?"rail":/^Boat-/.test(e)?"ferry":(/^Shuttle/i.test(e),"bus"):"unknown"}function t5(e){if(!e)return"unknown";const t=e.split(":")[0];return t==="VYG"||t==="GJB"||t==="SJN"||t==="FLT"||t==="GOA"||t==="NSB"||t==="VYT"||t==="FLB"?"rail":"bus"}function n5(e){return e?/^31M/.test(e)?"subway":/^10(0[1-9]|10|15)/.test(e)?"tram":/^1019/.test(e)?"ferry":/^300[0-9A-Z]/.test(e)?"rail":"bus":"unknown"}function i5(e){return e?e==="901"||e==="902"?"tram":e==="888"?"rail":"bus":"unknown"}const Yw=Object.freeze([Object.freeze({id:"mbta",historyRetention:!0,name:"MBTA",operator:"Massachusetts Bay Transportation Authority",region:"Boston, MA",center:Object.freeze({lat:42.3601,lon:-71.0589}),loadRadiusKm:70,url:"https://cdn.mbta.com/realtime/VehiclePositions.pb",license:"MassDOT Developers License Agreement",licenseUrl:"https://cdn.mbta.com/sites/default/files/2023-08/mbta-massdot-develop-license-agreement.pdf",attribution:"MBTA / MassDOT",defaultEnabled:!0,terms:Object.freeze({quote:"MassDOT ... hereby grants You (Licensee) non-exclusive, limited, and revocable rights to use, reproduce, and redistribute the Data. ... Clearly acknowledge MassDOT as the provider of the Data.",note:"Credit is text only: the agreement forbids using MBTA/MassDOT logos or trademarks with the data."}),defaultMode:"bus",routeMode:e5}),Object.freeze({id:"capmetro-austin",name:"CapMetro",operator:"Capital Metropolitan Transportation Authority",region:"Austin, TX",center:Object.freeze({lat:30.2672,lon:-97.7431}),loadRadiusKm:60,url:"https://data.texas.gov/download/eiei-9rpf/application%2Foctet-stream",license:"CapMetro Developer Tools license",licenseUrl:"https://www.capmetro.org/developertools",attribution:"Capital Metropolitan Transportation Authority — data.texas.gov",defaultEnabled:!0,terms:Object.freeze({quote:"Capital Metropolitan Transportation Authority (CMTA) hereby grants you (Licensee) non-exclusive, limited and revocable rights to use, reproduce, and redistribute CMTA Data.",note:"CMTA trademarks may not be used in association with the data, so the credit is the operator name as text."}),defaultMode:"bus"}),Object.freeze({id:"metrotransit-msp",name:"Metro Transit",operator:"Metro Transit (Metropolitan Council)",region:"Minneapolis–St Paul, MN",center:Object.freeze({lat:44.9778,lon:-93.265}),loadRadiusKm:70,url:"https://svc.metrotransit.org/mtgtfs/vehiclepositions.pb",license:"Public Metro Transit vehicle position data",licenseUrl:"https://svc.metrotransit.org/",attribution:"Metro Transit — Metropolitan Council",defaultEnabled:!0,terms:Object.freeze({quote:"Metro Transit's GTFS-realtime feeds are refreshed every 5 seconds.",note:'The realtime feed is published from a developer page carrying operational guidance and no licence text of its own. The public-domain statement below belongs to the Metropolitan Council metadata for the COMPANION SCHEDULE dataset, not to this feed: "None. This dataset is public domain under the Minnesota Government Data Practices Act". Credited as a courtesy, the way the other public agency feeds are.'}),defaultMode:"bus",routeMode:i5}),Object.freeze({id:"hsl-helsinki",name:"HSL",operator:"Helsinki Region Transport (HSL)",region:"Helsinki, Finland",center:Object.freeze({lat:60.1699,lon:24.9384}),loadRadiusKm:70,url:"https://realtime.hsl.fi/realtime/vehicle-positions/v2/hsl",license:"CC BY 4.0",licenseUrl:"https://www.hsl.fi/en/hsl/open-data",attribution:"HSL (Helsinki Region Transport)",defaultEnabled:!0,terms:Object.freeze({quote:null,note:"The open-data page refuses automated readers (HTTP 403, bot protection), so this entry rests on the owner opening it and accepting it rather than on a passage quoted here. HSL publishes its open data under CC BY 4.0 and asks to be credited as the source; the feed needs no key."}),defaultMode:"bus",routeMode:n5}),Object.freeze({id:"ovapi-nl",name:"OVapi",operator:"Stichting OpenGeo (NDOV data)",region:"Netherlands",center:Object.freeze({lat:52.2,lon:5.3}),loadRadiusKm:220,url:"https://gtfs.ovapi.nl/nl/vehiclePositions.pb",license:"Free to use per the OVapi README (best effort, no SLA)",licenseUrl:"https://gtfs.ovapi.nl/README",attribution:"OVapi / Stichting OpenGeo — Dutch integrated real-time transit data",defaultEnabled:!0,terms:Object.freeze({quote:"You are free to use this data, but there is no service level agreement (best-effort) nor are you allowed to say you represent or impersonate any of the transit agencies listed here.",note:"The README asks consumers to identify themselves in the User-Agent, to send If-Modified-Since / If-None-Match when polling faster than once a minute, and to accept gzip. The proxy does all three."}),defaultMode:"bus"}),Object.freeze({id:"entur-norway",name:"Entur",operator:"Entur AS (Norwegian national transit data)",region:"Norway",center:Object.freeze({lat:64,lon:11.5}),loadRadiusKm:720,url:"https://api.entur.io/realtime/v1/gtfs-rt/vehicle-positions",headers:Object.freeze({"ET-Client-Name":"gods-eye-view-transit"}),license:"Norwegian Licence for Open Government Data (NLOD)",licenseUrl:"https://developer.entur.org/pages-intro-authentication",attribution:"Entur — data under NLOD",defaultEnabled:!0,terms:Object.freeze({quote:"This API is open under NLOD licence, however, it is required that all consumers identify themselves by using the header ET-Client-Name.",note:"The header is mandatory — unidentified consumers may be rate-limited or blocked — and the proxy sends it on every request."}),defaultMode:"bus",routeMode:t5}),Object.freeze({id:"translink-seq",name:"TransLink",operator:"TransLink (Queensland Government)",region:"South East Queensland, Australia",center:Object.freeze({lat:-27.4698,lon:153.0251}),loadRadiusKm:150,url:"https://gtfsrt.api.translink.com.au/api/realtime/seq/VehiclePositions",license:"CC BY 4.0",licenseUrl:"https://translink.com.au/about-translink/open-data",attribution:"TransLink — Queensland Government (CC BY 4.0)",defaultEnabled:!0,terms:Object.freeze({quote:"Our data is licensed under a Creative Commons Attribution 4.0 International License. ... You must not represent that the State in any way endorses your Application.",note:"No key, no stated rate limit, no caching rule. Logos and network imagery need separate approval, so the credit is text only."}),defaultMode:"bus"})]),ru=Object.freeze(Yw.filter(e=>e.defaultEnabled===!0));new Map(ru.map(e=>[e.id,e]));const o5=new Map(Yw.map(e=>[e.id,e])),r5=/^[a-z0-9][a-z0-9-]{1,63}$/;function su(e){return typeof e!="string"||!r5.test(e)?null:o5.get(e)||null}function s5(e,t,n,i){const o=c=>c*Math.PI/180,r=o(n-e),s=o(i-t),a=Math.sin(r/2)**2+Math.cos(o(e))*Math.cos(o(n))*Math.sin(s/2)**2;return 2*6371*Math.asin(Math.min(1,Math.sqrt(a)))}function j_(e,t,n=0){return!Number.isFinite(e)||!Number.isFinite(t)?[]:ru.map(i=>({feed:i,km:s5(e,t,i.center.lat,i.center.lon)})).filter(({feed:i,km:o})=>o<=i.loadRadiusKm+Math.max(0,n)).sort((i,o)=>i.km-o.km).map(({feed:i})=>i)}function a5(e,t){const n=typeof(e==null?void 0:e.routeMode)=="function"?e.routeMode(t):null,i=n&&n!=="unknown"?n:(e==null?void 0:e.defaultMode)||"unknown";return Kw.includes(i)?i:"unknown"}function l5(e,t){const n=typeof(e==null?void 0:e.routeMode)=="function"?e.routeMode(t):null;return!!n&&n!=="unknown"&&Kw.includes(n)}function c5(e){return typeof e=="string"&&e.length>0&&!/[\u0000-\u001f\u007f/\\]/u.test(e)&&e!=="."&&e!==".."&&new TextEncoder().encode(e).length<=256&&!/[\uD800-\uDFFF]/u.test(e)}async function u5(e,t,n,i=fetch){var u,h;if(!c5(t))throw new TypeError("Invalid transit vehicle identifier");const o=await i(`/api/transit/trail/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{signal:n,headers:{Accept:"application/json"}});if(!o.ok)throw new Error(`Transit history HTTP ${o.status}`);const r=(h=(u=o.body)==null?void 0:u.getReader)==null?void 0:h.call(u);let s="";if(r){const d=new TextDecoder;let f=0;try{for(;;){n==null||n.throwIfAborted();const p=await r.read();if(p.done)break;if(f+=p.value.byteLength,f>32768)throw new RangeError("Transit history exceeds response limit");s+=d.decode(p.value,{stream:!0})}s+=d.decode()}finally{await r.cancel().catch(()=>{})}}else if(s=await o.text(),new TextEncoder().encode(s).length>32768)throw new RangeError("Transit history exceeds response limit");n==null||n.throwIfAborted();const a=JSON.parse(s);if(a.version!==1||a.feedId!==e||a.vehicleId!==t||!Array.isArray(a.fixes)||a.fixes.length>128||!Array.isArray(a.epochs)||a.epochs.length>8)throw new TypeError("Invalid transit history response");let c=-1/0;const l=new Set;for(const d of a.epochs){if(!Number.isInteger(d.id)||d.id<1||d.id>4294967295||l.has(d.id)||!["trip","route","mode"].every(f=>typeof d[f]=="string"&&new TextEncoder().encode(d[f]).length<=256))throw new TypeError("Invalid transit history epoch");l.add(d.id)}for(const d of a.fixes){if(!Array.isArray(d)||d.length!==5||!d.every(Number.isFinite)||d[0]<0||d[0]<=c||Math.abs(d[1])>90||Math.abs(d[2])>180||!Number.isInteger(d[3])||!l.has(d[4]))throw new TypeError("Invalid transit history fix");c=d[0]}return a}const Cs=48,Mt=Object.freeze({VEHICLE_TIME:1,FEED_TIME:2,RECEIPT_TIME:4,FLOOR:8,BREAK:16,LIVE:32}),q_=e=>Math.max(25e3,Math.min(12e4,e));function Xw(e=256){return{values:new Float64Array(e),count:0,cursor:0}}function W_(e,t){!e||!Number.isFinite(t)||t<0||(e.values[e.cursor]=t,e.cursor=(e.cursor+1)%e.values.length,e.count=Math.min(e.count+1,e.values.length))}function K_(e,t){if(!(e!=null&&e.count))return 0;const n=e.values.slice(0,e.count).sort();return n[Math.ceil(n.length*t)-1]}function d5(e=32*1024*1024){return{maxBytes:e,allocatedBytes:0}}function oo(){return{t:NaN,lat:NaN,lon:NaN,heightM:NaN,h:NaN,receivedAt:NaN,bearingDeg:NaN,flags:0,epoch:0,seq:-1}}function h5({capacity:e=128,retentionMs:t=9e5,policy:n={},budget:i=null}={}){return e=Math.max(2,Math.min(128,Math.floor(e))),{capacity:e,retentionMs:t,policy:n,budget:i,metricsScratchA:oo(),metricsScratchB:oo(),storage:new DataView(new ArrayBuffer(0)),slots:0,head:0,count:0,baseSeq:0,revision:0,truncated:!1,epochs:new Map,lag:Xw(32),targetDelayMs:25e3,displayT:NaN,wallAnchor:NaN,monoAnchor:NaN,lastMono:NaN,offset:0,rate:1,phase:"buffering",resets:0,resetReason:null,acceptedAt:NaN,acceptedMono:NaN,resumePending:!1,bracket:0,metricsRevision:-1,metricsIndex:-1,from:oo(),to:oo(),metrics:{speed:NaN,course:NaN,nextMotionT:1/0},latest:oo(),pending:null,pendingCount:0}}function Ea(e,t){return(e.head+t)%e.slots*Cs}function gt(e,t,n={}){if(t<0||t>=e.count)return null;const i=e.storage,o=Ea(e,t);return n.t=i.getFloat64(o),n.lat=i.getFloat64(o+8),n.lon=i.getFloat64(o+16),n.heightM=i.getFloat32(o+24),n.h=n.heightM,n.receivedAt=i.getFloat64(o+28),n.bearingDeg=i.getFloat32(o+36),n.flags=i.getUint32(o+40),n.epoch=i.getUint32(o+44),n.seq=e.baseSeq+t,n}function Y_(e,t,n){const i=e.storage,o=Ea(e,t);i.setFloat64(o,n.t),i.setFloat64(o+8,n.lat),i.setFloat64(o+16,n.lon),i.setFloat32(o+24,n.heightM??n.h??NaN),i.setFloat64(o+28,n.receivedAt??NaN),i.setFloat32(o+36,n.bearingDeg??NaN),i.setUint32(o+40,n.flags||0),i.setUint32(o+44,n.epoch||0)}function Qw(e,t){const n=t*Cs,i=n-e.storage.byteLength;if(i>0&&e.budget&&e.budget.allocatedBytes+i>e.budget.maxBytes)return!1;const o=e.storage,r=e.head,s=e.slots,a=new Uint8Array(n),c=new Uint8Array(o.buffer);for(let l=0;l2&&(e.count>n||Pi(e,1)e.displayT);)Zw(e);n=0&&Number.isFinite(e.lat)&&Math.abs(e.lat)<=90&&Number.isFinite(e.lon)&&Math.abs(e.lon)<=180}function X_(e,t){const n=(t.lon-e.lon+540)%360-180;return Math.hypot((t.lat-e.lat)*111320,n*111320*Math.cos(e.lat*Math.PI/180))}function Eh(e,t){if(e.count===e.slots&&e.slotse.displayT){if(e.count<4)return!1;const n={};for(let i=2;in.wallNowMs+1e4)return{accepted:!1,reason:"malformed"};const i=gt(e,e.count-1,e.latest);if(i&&t.t===i.t)return{accepted:!1,reason:t.lat===i.lat&&t.lon===i.lon?"repeat":"conflict"};let o=i?"moved":"first";if(i&&(t.t>>0;Eh(e,{...a,epoch:l,flags:(a.flags||0)|Mt.BREAK}),t={...t,epoch:l},o==="out-of-order"&&(e.displayT=NaN),e.resetReason=o,e.resets++}const r=n.receivedAt??t.receivedAt??n.wallNowMs??t.t;Jw(e,r);const s=Eh(e,{...t,receivedAt:r,flags:(t.flags||0)|Mt.LIVE});return s&&(n.replayed||(i&&t.t>i.t&&o==="moved"?(W_(e.lag,r-i.t),W_(e.policy.feedLag,r-i.t),e.targetDelayMs=q_(Math.max(K_(e.lag,.95),K_(e.policy.feedLag,.9))+5e3)):i||(e.targetDelayMs=q_(Math.max(0,r-t.t)+2e4))),e.acceptedAt=r,e.acceptedMono=n.monoNowMs??NaN,e.resumePending=!0,e.pending=null,e.pendingCount=0),{accepted:s,reason:s?o:"capacity"}}function tE(e,t){const n=new Map;for(const d of t.slice(-128))eE(d)&&(!Number.isFinite(e.acceptedAt)||d.t>=e.acceptedAt-e.retentionMs)&&n.set(d.t,{...d,flags:(d.flags||0)&~Mt.LIVE});for(let d=0;dgt(e,f)),o=Number.isFinite(e.displayT)?i.findLastIndex(d=>d.t<=e.displayT):-1,r=i[o],s=i[o+1],a=new Set(i.map(d=>d.t)),c=[...n.values()].sort((d,f)=>d.t-f.t).filter(d=>a.has(d.t)||!r||!s||d.ts.t),l=[];function u(d,f,p=!1){let g=f,_=null;const m=(b,C)=>!e.policy.accept||(p?e.policy.accept(C,b):e.policy.accept(b,C));for(const b of d)a.has(b.t)||!g||m(g,b)?(l.push(b),g=b,_=null):_&&m(_,b)?(p?g.flags|=Mt.BREAK:_.flags|=Mt.BREAK,l.push(_,b),g=b,_=null):_=b}const h=i[0];for(h?(u(c.filter(d=>d.td.t>=h.t),null)):u(c,null),l.sort((d,f)=>d.t-f.t);l.length>e.capacity;){const d=l.findIndex(f=>f.t!==(r==null?void 0:r.t)&&f.t!==(s==null?void 0:s.t));d>0&&d+1=e.count||!Number.isFinite(n))return!1;const o=Ea(e,i),r=Math.fround(n);return e.storage.getFloat32(o+24)===r?!1:(e.storage.setFloat32(o+24,r),e.storage.setUint32(o+40,e.storage.getUint32(o+40)|Mt.FLOOR),e.revision++,!0)}function Sm(e,t){return Number.isFinite(e.wallAnchor)||(e.wallAnchor=t.wallNowMs,e.monoAnchor=t.monoNowMs),e.wallAnchor+Math.max(0,t.monoNowMs-e.monoAnchor)}function m5(){return{displayT:NaN,revision:0,nextWakeMonoMs:1/0,phase:"buffering",motion:"unknown",fromSeq:-1,toSeq:-1,lat:NaN,lon:NaN,heightM:NaN,segmentCourseDeg:NaN,segmentSpeedMps:NaN,fraction:NaN,fromT:NaN,toT:NaN,nextMotionT:1/0,latestReportAgeMs:NaN,actualDelayMs:NaN}}function p5(e,t,n){return n.displayT=t,iE(e,n)}function iE(e,t){const n=t.displayT;if(t.revision=e.revision,t.nextWakeMonoMs=1/0,t.phase=e.phase,t.motion="unknown",t.fromSeq=-1,t.toSeq=-1,t.lat=NaN,t.lon=NaN,t.heightM=NaN,t.segmentCourseDeg=NaN,t.segmentSpeedMps=0,!e.count)return t;let i=Math.min(e.bracket,e.count-1);for(Pi(e,i)>n&&(i=0);i+1=(e.policy.courseMinTravelM??12))u.course=(Math.atan2(((s.lon-o.lon+540)%360-180)*Math.cos(o.lat*Math.PI/180),s.lat-o.lat)*180/Math.PI+360)%360;else{const f=e.metricsScratchA,p=e.metricsScratchB;for(let g=i;g>=0&&(gt(e,g,p),p.epoch===o.epoch);g--)if(Number.isFinite(p.bearingDeg)&&(u.course=p.bearingDeg),!(g===0||p.flags&Mt.BREAK)&&(gt(e,g-1,f),f.epoch===p.epoch&&X_(f,p)>=(e.policy.courseMinTravelM??12))){u.course=(Math.atan2(((p.lon-f.lon+540)%360-180)*Math.cos(f.lat*Math.PI/180),p.lat-f.lat)*180/Math.PI+360)%360;break}}u.nextMotionT=1/0;const h=e.metricsScratchA,d=e.metricsScratchB;for(let f=i;f+1180&&(t.lon-=360),t.lon<-180&&(t.lon+=360),t.heightM=a?o.heightM+(s.heightM-o.heightM)*c:o.heightM,t.segmentCourseDeg=e.metrics.course,t.segmentSpeedMps=e.metrics.speed,t.motion=a?e.metrics.speed>0?"moving":"stopped":"unknown",t.nextMotionT=e.metrics.nextMotionT,t.latestReportAgeMs=Number.isFinite(e.wallAnchor)?e.wallAnchor+e.lastMono-e.monoAnchor-Pi(e,e.count-1):NaN,t.actualDelayMs=Number.isFinite(e.wallAnchor)?e.wallAnchor+e.lastMono-e.monoAnchor-n:NaN,t}function g5(e,t,n){const i=Sm(e,t),o=e.lastMono,r=Number.isFinite(o)?Math.max(0,t.monoNowMs-o):0;if(e.lastMono=t.monoNowMs,!e.count)return p5(e,NaN,n);const s=Pi(e,e.count-1),a=Pi(e,0),c=Math.min(s,i-e.targetDelayMs+e.offset),l=e.offset===0&&e.phase!=="playing"&&c9e4||e.truncated&&e.displayT9e4?"backlog":"unavailable-bracket",e.displayT=c,e.resets++;else if(e.rate!==0){const u=e.offset<0||e.phase==="playing"?s:c;let h=e.displayT+r*e.rate;if(e.phase==="held"&&e.resumePending){const d=Number.isFinite(e.acceptedMono)?Math.max(0,t.monoNowMs-e.acceptedMono):0;h=e.displayT+Math.min(r,d)*e.rate}e.displayT=Math.max(e.displayT,Math.min(h,u))}if(e.phase=e.rate===0?"paused":e.displayT=s?"held":"playing",e.resumePending=!1,n.displayT=e.displayT,iE(e,n),n.motion!=="moving"||e.phase!=="playing"){const u=Math.max(a,n.nextMotionT);Number.isFinite(u)&&u>e.displayT&&e.rate>0&&(n.nextWakeMonoMs=t.monoNowMs+(u-e.displayT)/e.rate)}return l&&e.rate>0&&(n.nextWakeMonoMs=t.monoNowMs+Math.max(1,e.displayT-c)),n.latestReportAgeMs>(e.policy.staleMs??9e4)&&(n.motion="stale"),n}function Q_(e,t,n){if(!Number.isFinite(t))throw new TypeError("A seek needs a finite time");Sm(e,n),e.displayT=t,e.offset=-1,e.rate=0,e.phase="paused",e.lastMono=n.monoNowMs,e.bracket=0,e.resets++,e.resetReason="seek"}function _5(e,t,n){if(!Number.isFinite(t)||t>0)throw new RangeError("Offset must be zero or negative");Number.isFinite(e.displayT)&&(e.resets++,e.resetReason="time-offset"),e.offset=t,e.rate=1,e.displayT=Sm(e,n)-e.targetDelayMs+t,e.lastMono=n.monoNowMs,e.phase="buffering",e.bracket=0}function Z_(e,t,n){if(!Number.isFinite(t)||t<0||t>16)throw new RangeError("Rate must be in [0, 16]");e.offset,e.rate=t,e.lastMono=n.monoNowMs,e.phase="buffering"}const b5=[[0,.8],[12e4,.45],[6e5,.2],[9e5,.08]];function C5(e){const t=b5;for(let n=1;n>>1;r[A].toT<=v.displayT?E=A+1:k=A}const T=E-1,I=r[E],R=I&&I.fromT<=v.displayT&&I.fromSeq===v.fromSeq&&I.toSeq===v.toSeq?I:null;if(o!=null&&o.ready&&T!==u){for(let A=Math.min(T,u)+1;A<=Math.max(T,u);A++)for(let L=0;L<2;L++){const F=o.getGeometryInstanceAttributes(f[A][L]);F&&(F.show[0]=A<=T?1:0,F.show=F.show)}u=T}if(o!=null&&o.ready&&w!==l){for(let A=0;A0))return!0;const o=v5(e,i);return n>=1?t/n<=o:t<=o}function A5(e,t,n){e.track=h5({budget:t,policy:{feedLag:n,courseMinTravelM:M5,staleMs:oE,accept:(i,o)=>k5(o.admissionMode??e.mode,ml(i,o),(o.t-i.t)/1e3,o.admissionModeInferred??e.modeInferred)}}),e.sample=m5(),e.segment={from:oo(),to:oo(),fraction:NaN},e.clocks={wallNowMs:NaN,monoNowMs:NaN},Object.defineProperty(e,"playT",{configurable:!0,get:()=>e.sample.displayT}),Object.defineProperty(e,"lagTarget",{configurable:!0,get:()=>e.track.targetDelayMs}),Object.defineProperty(e,"fixes",{configurable:!0,get(){return Array.from({length:e.track.count},(i,o)=>gt(e.track,o))}})}function Th(e,t,n={}){const i=n.context;let o=e.currentEpoch||1;if(i){const s=e.track.epochs.get(o);s&&(s.trip!==i.trip||s.route!==i.route||s.mode!==i.mode)&&(o=Math.max(0,...e.track.epochs.keys())+1)}const r=f5(e.track,{...t,epoch:o,admissionMode:i==null?void 0:i.mode,admissionModeInferred:n.modeInferred},n);if(r.accepted){const s=gt(e.track,e.track.count-1,e.track.latest);e.currentEpoch=s.epoch,i&&e.track.epochs.set(s.epoch,i)}return r}function En(e,t,n){e.clocks.wallNowMs=t,e.clocks.monoNowMs=n,g5(e.track,e.clocks,e.sample),e.resets=e.track.resets;const i=e.segment;return gt(e.track,e.sample.fromSeq-e.track.baseSeq,i.from),gt(e.track,e.sample.toSeq-e.track.baseSeq,i.to),i.fraction=e.sample.fraction,e.sample}function kh(e,t,n=performance.now()){e.clocks.wallNowMs=t,e.clocks.monoNowMs=n;const i=e.track.resets,o=e.track.resetReason;_5(e.track,0,e.clocks),e.hasRendered?e.track.resetReason="re-entry":(e.track.resets=i,e.track.resetReason=o),En(e,t,n)}function Ah(e,t,n){if(!e.track||!Number.isFinite(n))return;const i={};for(let o=0;ooE?{moving:!1,word:"NO FIX"}:n.phase!=="playing"?{moving:!1,word:"WAITING"}:n.motion==="stopped"?{moving:!1,word:"STOPPED"}:{moving:n.motion==="moving",word:n.motion==="moving"?"EN ROUTE":"WAITING"}:{moving:!1,word:"WAITING"}}const L5=Object.freeze({surveillance:"mono",thermal:"mono",noir:"mono",nvg:"mono",retro:"crt"}),Os=Object.freeze({mono:Object.freeze({rgba:Object.freeze([255,255,255,1]),scale:1.5,outlinePx:3}),crt:Object.freeze({scale:1.3,outlinePx:1.25,rgbaByMode:Object.freeze({bus:Object.freeze([0,255,102,1]),tram:Object.freeze([255,179,0,1]),subway:Object.freeze([255,59,48,1]),rail:Object.freeze([215,139,255,1]),ferry:Object.freeze([58,208,255,1]),unknown:Object.freeze([255,255,255,1])})})}),sE=Object.freeze(["bus","tram","subway","rail","ferry","unknown"]);function Do(e){return L5[e]||"normal"}function P5(e,t){const n=Do(e);return n==="mono"?Os.mono.rgba:n==="crt"?Os.crt.rgbaByMode[t]||Os.crt.rgbaByMode.unknown:null}function aE(e,t=!1){var n;return Do(e)==="mono"?t?36/30:30/20:((n=Os[Do(e)])==null?void 0:n.scale)??1}function lE(e,t=!1){var n;return((n=Os[Do(e)])==null?void 0:n.outlinePx)??(t?1.5:1)}function x5(e){return`transit_${sE.includes(e)?e:"unknown"}`}Object.freeze(sE.map(e=>`transit_${e}`));const eb={bus:"#5EF08A",tram:"#FFC24A",subway:"#FF4538",rail:"#D9A6FF",ferry:"#5FD6FF",unknown:"#D8DDE5"},tb=2048,nb=25;function F5({state:e,services:t,parts:n}){let i=null,o=0,r=0,s=null,a=null,c=null,l=0;function u(){return!s&&e._viewer&&(s=y5(e._viewer.scene)),s}function h(){s==null||s.setStyle(Do(e._stylePreset)==="mono"?"#FFFFFF":eb[a==null?void 0:a.mode]||eb.unknown)}function d(C){C.trailSegments=[],C.trailVertices=0,C.trailTruncated=!1,C.pathRevision=-1,C.markerPathSeq=NaN,f(C,C.sample)}function f(C,y){var v;if(!(C===a||C.markerPathSeq===y.fromSeq)){C.markerPathSeq=y.fromSeq;for(const M of((v=C.displayPaths)==null?void 0:v.keys())||[])M{const O=n.height.requestHeight(P.lat,P.lon,C);return y&&y(P,O),O.height};if(y&&C.key===e._selectedKey){gt(C.track,Math.max(0,C.sample.fromSeq-C.track.baseSeq),w),gt(C.track,Math.max(0,C.sample.toSeq-C.track.baseSeq),E);const P=Math.min(tb-1,Math.max(1,Math.ceil(ml(w,E)/nb)));for(let O=0;O<=P;O++)I({lat:w.lat+(E.lat-w.lat)*O/P,lon:w.lon+(E.lon-w.lon)*O/P})}for(let P=0;P=0;P--)R.push(P);C.trailTruncated=!1;for(const P of R){if(gt(C.track,P,w),gt(C.track,P+1,E),w.epoch!==E.epoch||E.flags&Mt.BREAK||C!==a&&E.ttb){C.trailTruncated=!0;continue}const D=[],$=[];let x=!0;for(let N=0;N<=O;N++){const G=N/O,W={lat:w.lat+(E.lat-w.lat)*G,lon:w.lon+((E.lon-w.lon+540)%360-180)*G},V=I(W);$.push(V),V===null?(x=!1,D.push(null)):D.push(Cesium.Cartesian3.fromDegrees(W.lon,W.lat,V))}if(T+=`${w.seq}/${E.seq}:${$.join(",")};`,k+=O+1,!!x&&(v.set(w.seq,{positions:D,toSeq:E.seq}),C===a&&ml(w,E)>0))for(let N=0;NP.fromT-O.fromT),(F=u())==null||F.replaceHistory({segments:M,revision:++l}),C.trailVertices=k,C.trailSegments=M,t.render.governorRequestRender("transit-trail-history"))),A}function g(C,y,v,M=n.height.nearGround()){var S;if(f(C,y),!M){const A=C.fromCart,L=C.toCart,F=y.fraction;return v.x=A.x+(L.x-A.x)*F,v.y=A.y+(L.y-A.y)*F,v.z=A.z+(L.z-A.z)*F,v}if(y.fromSeq===y.toSeq)return Number.isFinite(C.segment.from.h)?(Cesium.Cartesian3.clone(C.fromCart,v),v):null;const w=(S=C.displayPaths)==null?void 0:S.get(y.fromSeq);if(!w||w.toSeq!==y.toSeq)return null;const E=y.fraction*(w.positions.length-1),k=Math.min(w.positions.length-2,Math.floor(E)),T=w.positions[k],I=w.positions[k+1],R=E-k;return v.x=T.x+(I.x-T.x)*R,v.y=T.y+(I.y-T.y)*R,v.z=T.z+(I.z-T.z)*R,v}function _(){var C,y;!a||!s||(s.setVisible(e._enabled&&((C=a.marker)==null?void 0:C.show)!==!1),s.setDisplaySample(a.sample,(y=a.marker)==null?void 0:y.position))}function m(C){b(),a=C,u(),h(),C.pathRevision=-1,p(C),_();const y=su(C.feedId);if(y!=null&&y.historyRetention){const v=new AbortController;i=v,o++,u5(C.feedId,C.record.id,v.signal).then(M=>{var E;if(v.signal.aborted||!e._enabled||a!==C||i!==v)return;const w=new Map;for(const k of M.epochs){let T=null;for(const[I,R]of C.track.epochs)if(R.trip===k.trip&&R.route===k.route&&R.mode===k.mode){T=I;break}T===null&&(T=Math.max(0,...C.track.epochs.keys())+1,C.track.epochs.set(T,{trip:k.trip,route:k.route,mode:k.mode})),w.set(k.id,T)}tE(C.track,M.fixes.map(([k,T,I,R,S])=>({t:k,lat:T,lon:I,flags:R,epoch:w.get(S)}))),(E=C.track).truncated||(E.truncated=M.truncated),C.pathRevision=-1,n.height.anchorFloors(),p(C),_(),t.render.governorRequestRender("transit-trail-backfill")}).catch(()=>{}).finally(()=>{i===v&&(i=null)})}c=setInterval(()=>{!e._enabled||a!==C||(n.rendering.sampleIdle(C),_(),t.render.governorRequestRender("transit-trail-age"))},1e3)}function b(){i&&(i.abort(),r++,i=null),c!=null&&clearInterval(c),c=null;const C=a;a=null,C&&d(C),s==null||s.destroy(),s=null}return{prepareEntry:p,samplePosition:g,select:m,clear:b,update:_,style:h,destroy:b,requestDiagnostics:()=>({requestCount:o,abortCount:r,pending:i!==null}),diagnostics:()=>(s==null?void 0:s.diagnostics())||null}}function S5({services:e}){const{setOverlayEntries:t,setOverlaySourceVisible:n,clearOverlaySource:i}=e.overlays,o={};return o._historyBudget=d5(),o.DEFAULT_OVERLAY_HOST=Object.freeze({setEntries:t,setVisible:n,clearSource:i}),o._overlayHost=o.DEFAULT_OVERLAY_HOST,o._viewer=null,o._markers=null,o._animatedMarkers=null,o._visible=new Set,o._visibilityTimer=null,o._maintenanceTimer=null,o._detectBuiltAt=-1/0,o._cameraRevision=0,o._rotationRevision=-1,o._enabled=!1,o._generation=0,o._cameraChangedAttached=!1,o._cameraDebounceTimer=null,o._altitudeGateOpen=!1,o._priorPercentageChanged=null,o._appliedPercentageChanged=null,o._preRenderRemove=null,o._renderHeld=!1,o._clickHandler=null,o._moving=new Set,o._heightDirty=new Set,o._viewBounds=null,o._shownCount=0,o._visibilityDirty=!0,o._visibilityAt=0,o._rotationAt=0,o._rotationPose=null,o._rotationDirty=!1,o._activeFeeds=new Map,o._feedStatus=new Map,o._inFlight=new Map,o._vehicles=new Map,o._floorTimer=null,o._floorAttempts=0,o._floorCursor=0,o._selectedKey=null,o._selectedCardAt=0,o._selectedCardText=null,o._detectRevision=0,o._detectCache=null,o._stylePreset="normal",o._cockpitVision=!1,o._styleListeners=[],o._dataManager=null,o._lastUpdate=null,o._error=null,o._limitWarned=!1,o._scratchCartesian=new Cesium.Cartesian3,o}const mr="transit-selected",N5=Object.freeze({cohortLimit:1,collisionCapacity:0,moving:!0}),cE=15e3,Nm=3e6,D5=Nm-15e4,O5=Nm+15e4,B5=340,V5=.05,H5=40,ib=15e3,$5=2,G5=10*6e4,Dm=9e4,ob=5*6e4,U5=6e4,rb=300,z5=900,j5=6,Ju=20,q5=30,W5=200,sb=250,K5=.6;function Ih(e,t){return!e||!t?!0:t.late.north?!1:e.west<=e.east?t.lon>=e.west&&t.lon<=e.east:t.lon>=e.west||t.lon<=e.east}function Y5(e,t){return!e||!t||Ih(e,t.to)?!0:t.from?Ih(e,t.from):!1}function X5(e,t=K5){if(!e)return null;const{south:n,north:i,west:o,east:r}=e;if(![n,i,o,r].every(Number.isFinite))return null;const s=Math.max(0,(i-n)*t),a=o<=r?r-o:360-o+r,c=Math.max(0,a*t),l={south:Math.max(-90,n-s),north:Math.min(90,i+s),west:-180,east:180};return a+c*2>=360||(l.west=o-c<-180?o-c+360:o-c,l.east=r+c>180?r+c-360:r+c),l}const Q5=250,Rh=Object.freeze({bus:"#5EF08A",tram:"#FFC24A",subway:"#FF4538",rail:"#D9A6FF",ferry:"#5FD6FF",unknown:"#D8DDE5"});function Z5(e,t){return`${e}:${t}`}function J5(e,t=null){const n=Number(e==null?void 0:e.timestamp);return Number.isFinite(n)&&n>0?n*1e3:Number.isFinite(t)?t:Date.now()}function uE(e,t,n=null){const i=Number(e==null?void 0:e.timestamp);return Number.isFinite(i)&&i>0?Math.max(0,t-i*1e3):Number.isFinite(n)?Math.max(0,t-n):0}function ab(e,t,n=null){return uE(e,t,n)>G5}function eV(e,t){const n=Array.isArray(e)?e:[];if(n.length===0)return{stale:!1,degraded:!1,error:null,retryInSec:null,loading:!1,staleFeeds:0};const i=a=>a.stale===!0||Number.isFinite(a.upstreamAt)&&t-a.upstreamAt>Dm,o=n.filter(i).length,r=n.find(a=>a.error)||null,s=(r==null?void 0:r.error)||null;return{stale:o===n.length,degraded:o>0&&oa.loading),staleFeeds:o}}function tV(e,t,n,i,o=null,r=null){var y,v,M;const s=z_[n]||z_.unknown,a=t.routeId?`Route ${t.routeId}`:t.label?`Vehicle ${t.label}`:`Vehicle ${t.id}`,c=`${s} ${a}`,u=[`${lb[n]||lb.unknown} · ${e.name} · ${e.region}`],h=[],d=r?rE(r):null;(d==null?void 0:d.word)==="STOPPED"?h.push("Stopped"):(d==null?void 0:d.word)==="NO FIX"?h.push("No recent fix"):(d==null?void 0:d.word)==="WAITING"?h.push("Waiting for update"):d&&h.push("Moving"),h.length&&u.push(h.join(" · "));const f=[];Number.isFinite(t.speedMps)&&f.push(`reported ${Math.round(t.speedMps*3.6)} km/h`),Number.isFinite(t.bearing)&&f.push(`reported hdg ${Math.round(t.bearing)}°`);const p=[];t.status==="STOPPED_AT"&&t.stopId?p.push(`Last report: stopped at stop ${t.stopId}`):t.status==="INCOMING_AT"&&t.stopId?p.push(`Last report: arriving at stop ${t.stopId}`):t.status==="IN_TRANSIT_TO"&&t.stopId&&p.push(`Last report: next stop ${t.stopId}`),t.occupancy&&t.occupancy!=="NO_DATA_AVAILABLE"&&p.push(t.occupancy.toLowerCase().replaceAll("_"," ")),f.length&&u.push(f.join(" · ")),p.length&&u.push(p.join(" · ")),iV.has(n)&&u.push("Shown at street level · depth not in the feed"),u.push(`Vehicle ${t.id}${t.label&&t.label!==t.id?` · ${t.label}`:""}`);const g=Math.round((Number.isFinite((y=r==null?void 0:r.sample)==null?void 0:y.latestReportAgeMs)?r.sample.latestReportAgeMs:uE(t,i,o))/1e3),_=g<90?`Reported ${g} s ago`:`Reported ${Math.round(g/60)} min ago`,m=Number.isFinite(t.timestamp)&&t.timestamp>0&&(!t.timestampSource||t.timestampSource==="vehicle"),b=Number.isFinite((v=r==null?void 0:r.sample)==null?void 0:v.actualDelayMs)?Math.max(0,Math.round(r.sample.actualDelayMs/1e3)):null,C=b===null?"":` · shown ${b} s behind`;if(u.splice(h.length?2:1,0,(m?_:`${_} (feed time)`)+C),(M=r==null?void 0:r.track)!=null&&M.count){const w=Math.max(0,Math.min(r.playT,r.fixes.at(-1).t)-r.fixes[0].t);u.push(`Available trail: ${Math.round(w/6e4)} min${r.track.truncated||r.trailTruncated?" (limited)":""}`)}return{title:c,details:u}}function nV(e,t,n,i){return!e||!t?null:{id:String(e),position:t,variant:"selected",selected:!0,protected:!0,paintLane:"selected",collisionGroup:"ambient-card",priority:Number.MAX_SAFE_INTEGER,title:n.title,details:n.details,accent:Rh[i]||Rh.unknown,interactive:!1,anchorRadiusPx:9,minAnchorGapPx:11,verticalOnly:!0,placement:"above",edgeFade:"keyhole",horizonCull:!0,terrainOcclusion:!1}}const iV=new Set(["subway"]),lb=Object.freeze({bus:"Bus",tram:"Tram",subway:"Subway",rail:"Train",ferry:"Ferry",unknown:"Transit vehicle"}),pc=Object.freeze({bus:"BUS",tram:"TRAM",subway:"METRO",rail:"RAIL",ferry:"FERRY",unknown:"TRANSIT"});function oV(e){const t=typeof(e==null?void 0:e.routeId)=="string"?e.routeId.trim():"";if(t)return ed(t);const n=typeof(e==null?void 0:e.label)=="string"?e.label.trim():"";return ed(n||String((e==null?void 0:e.id)||"TRANSIT"))}const cb=14;function ed(e){const t=String(e||"").toUpperCase();return t.length<=cb?t:`${t.slice(0,cb-1)}…`}function rV(e,t){const n=pc[e]||pc.unknown,i=typeof(t==null?void 0:t.name)=="string"?t.name.toUpperCase():"";return i?`${n} ${i}`.slice(0,20):n}function ub(e,t,n=Date.now()){const i=pc[t]||pc.unknown,o=sV(e,n);return o?`${i} ${o}`:i}function sV(e,t=Date.now()){return rE(e).word}function aV({state:e,services:t,parts:n}){var w;const{governorRequestRender:i}=t.render,{cachedGroundFloor:o,neighborFloorM:r,warmGroundFloor:s,coarseFloorCoord:a,GROUND_FLOOR_LIFT_M:c}=t.ground,l=((w=t.mesh)==null?void 0:w.sampleMeshFloorCells)||null;function u(){var k,T;const E=(T=(k=e._viewer)==null?void 0:k.camera)==null?void 0:T.positionCartographic;return E?{viewerLat:E.latitude*180/Math.PI,viewerLon:E.longitude*180/Math.PI}:{viewerLat:void 0,viewerLon:void 0}}function h(){var k,T;const E=(T=(k=e._viewer)==null?void 0:k.camera)==null?void 0:T.positionCartographic;return E&&Number.isFinite(E.height)?E.height:1/0}function d(){return h()<=U5}const f=new Cesium.Cartographic;function p(E,k,T=null){var P,O,D,$,x;const I=a(E,k),R=`${I.lat},${I.lon}`,S=(T==null?void 0:T.qaFloorM)??((P=e._qaFixtureFloors)==null?void 0:P.get(T==null?void 0:T.key));if(Number.isFinite(S))return{cell:R,height:S,prior:null};const A=(D=(O=e._viewer)==null?void 0:O.scene)==null?void 0:D.globe;if((A==null?void 0:A.show)===!0){Cesium.Cartographic.fromDegrees(k,E,0,f);const N=($=A.getHeight)==null?void 0:$.call(A,f),G=((x=e._viewer)==null?void 0:x.terrainProvider)instanceof Cesium.EllipsoidTerrainProvider;if(Number.isFinite(N)||G)return{cell:R,height:(G?0:N)+c,prior:null}}const L=o(E,k);if(Number.isFinite(L))return{cell:R,height:L+c,prior:null};if(!d())return{cell:R,height:null,prior:0};const F=r(I);return{cell:R,height:null,prior:Number.isFinite(F)?F+c:null}}function g(){}let _=new WeakMap,m=-1/0,b=new Set,C=0;function y(){var D,$;if(e._floorTimer=null,!e._enabled)return;const E=d(),k=[],T=[...e._vehicles.values()].filter(x=>{var N;return x.key===e._selectedKey||e._visible.has(x)||Ih(e._viewBounds,((N=x.segment)==null?void 0:N.from)||x.to)});T.sort((x,N)=>+(N.key===e._selectedKey)-+(x.key===e._selectedKey));for(const x of T){const N=new Map,G=(H,B)=>{E&&(N.has(B.cell)||N.set(B.cell,{lat:H.lat,lon:H.lon,cell:B.cell,warm:B.height!==null}))};n.trails.prepareEntry(x,G);const W=x.fixes.at(-1),V=p(W.lat,W.lon,x);x.heightCell=V.cell,V.height!==null&&(x.heightM=V.height,x.heightResolved=!0,x.heightPending&&(x.heightPending=!1,e._visibilityDirty=!0)),k.push({entry:x,cells:[...N.values()],cursor:0,start:_.get(x)||0})}const I=((D=k[0])==null?void 0:D.entry.key)===e._selectedKey?k[0].cells.slice(0,12):[],R=[...I],S=new Set(I.map(x=>x.cell)),A=k.length?e._floorCursor%k.length:0;let L=!0;for(;L;){L=!1;for(let x=0;x=N.cells.length)continue;const G=(N.start+N.cursor++)%N.cells.length,W=N.cells[G];L=!0,S.has(W.cell)||(S.add(W.cell),R.push({...W,entry:N.entry,next:(G+1)%N.cells.length}))}}e._floorCursor+=rb;const F=[],P=[];for(const x of R){let N=!1;!x.warm&&(b.has(x.cell)||b.sizex.marker).filter(Boolean);for(let x=0;x=cE&&(b=new Set,C=0,m=E),y()}function M(){m=-1/0,_=new WeakMap,b.clear(),C=0,e._floorTimer&&(clearTimeout(e._floorTimer),e._floorTimer=null),e._floorAttempts=0,e._heightDirty.clear()}return{nearGround:d,requestHeight:p,releaseVehicle:g,anchorFloors:v,rereadFloors:y,clear:M}}const Bs=96,db=Bs/2,Qo='stroke="rgba(0,0,0,0.34)" stroke-width="1.5" stroke-linejoin="round"',sn='stroke="rgba(0,0,0,0.30)" stroke-width="1.5" stroke-linecap="round" fill="none"',Lh={bus:` + + + `,tram:` + + + + `,subway:` + + + + `,rail:` + + + `,ferry:` + + `,unknown:` + `};Object.freeze(Object.keys(Lh));const Ph=new Map,lV=e=>typeof btoa=="function"?btoa(e):Buffer.from(e,"utf8").toString("base64"),td=48,dE=96,cV=20;function hE(e,t=cV){const n=Number.isFinite(e)?Math.max(0,e):0;if(n===0)return{units:0,pad:0,ratio:1};const i=2*n*Bs/Math.max(1,t),o=Math.ceil(i/2)+1;return{units:i,pad:o,ratio:(Bs+2*o)/Bs}}function uV(){return Ph.size}function hb(e,t=td,n={}){const i=Lh[e]?e:"unknown",o=t>td;t=o?dE:td;const r=Do(n.style||(n.haloScreenPx>=2?"thermal":n.haloScreenPx===1.25?"retro":"normal")),s=r==="mono"?"thermal":r==="crt"?"retro":"normal",a=(o?30:20)*aE(s,o),c=hE(lE(s,o),a),l=`${i}:${o?1:0}:${r}`;let u=Ph.get(l);if(!u){const h=Bs+2*c.pad,d=i==="bus"||i==="ferry"||i==="unknown"?48:47,f=48,p=i==="subway"?8:i==="rail"?12:14,g=``,_=r==="mono"?g:Lh[i],m=c.units>0?_.replace(//,(C,y)=>``):"",b=`${m}${_}`;u="data:image/svg+xml;base64,"+lV(b),Ph.set(l,u)}return u}const nd=Object.fromEntries(Object.entries(Rh).map(([e,t])=>[e,Cesium.Color.fromCssColorString(t)]));function dV({state:e,services:t,parts:n}){const{governorRequestRender:i,holdContinuousRender:o,releaseContinuousRender:r}=t.render;function s(P,O,D,$){return Cesium.Cartesian3.fromDegrees(O,P,D||0,void 0,$)}function a(P){!P.sample||P.sample.fromSeq<0||(P.from=P.segment.from,P.to=P.segment.to,P.fromCart=s(P.from.lat,P.from.lon,P.from.h,P.fromCart||new Cesium.Cartesian3),P.toCart=s(P.to.lat,P.to.lon,P.to.h,P.toCart||new Cesium.Cartesian3),P.endpointRevision=P.sample.revision,P.endpointFromSeq=P.sample.fromSeq,P.endpointToSeq=P.sample.toSeq)}function c(P,O=n.height.nearGround()){(P.endpointRevision!==P.sample.revision||P.endpointFromSeq!==P.sample.fromSeq||P.endpointToSeq!==P.sample.toSeq)&&a(P);const D=n.trails.samplePosition(P,P.sample,e._scratchCartesian,O);P.surfaceReady=!!D,P.marker.show=!!D&&f(P),D&&(P.marker.position=e._scratchCartesian,P.hasRendered=!0)}function l(P){e._moving.has(P)||(En(P,Date.now(),performance.now()),c(P))}function u(P){P.wakeTimer!=null&&clearTimeout(P.wakeTimer),P.wakeTimer=null}function h(P,O){const D=O?e._animatedMarkers:e._markers;if(!P.marker||P.markerCollection===D)return;const $=P.marker,x=D.add({id:P.key,position:$.position,image:$.image,width:$.width,height:$.height,color:$.color,scaleByDistance:$.scaleByDistance,rotation:$.rotation,alignedAxis:$.alignedAxis,show:$.show,disableDepthTestDistance:$.disableDepthTestDistance});P.markerCollection.remove($),P.marker=x,P.markerCollection=D,P.markerRevision=(P.markerRevision||0)+1,P.detectContact&&(P.detectContact.position=x.position)}function d(P){if(u(P),!P.marker||!f(P)){e._moving.delete(P),h(P,!1);return}const O=P.sample;if(!O||P.heightPending||P.surfaceReady===!1){e._moving.delete(P),h(P,!1);return}const D=O.phase==="playing"&&O.segmentSpeedMps>0,$=Number.isFinite(O.segmentCourseDeg)&&Number.isFinite(P.courseDeg)&&Math.abs((O.segmentCourseDeg-P.courseDeg+540)%360-180)>.01;D||$?(e._moving.add(P),h(P,!0)):(e._moving.delete(P),h(P,!1),Number.isFinite(O.nextWakeMonoMs)&&(P.wakeTimer=setTimeout(()=>{P.wakeTimer=null,!(!e._enabled||!e._vehicles.has(P.key))&&(En(P,Date.now(),performance.now()),c(P),d(P),M(),i("transit-motion-boundary"))},Math.max(1,O.nextWakeMonoMs-performance.now()))))}function f(P){return e._visible.has(P)}const p=new Map;function g(P,O){const D=P5(P,O);if(!D)return null;const $=`${Do(P)}:${O}`;let x=p.get($);return x||(x=new Cesium.Color(D[0]/255,D[1]/255,D[2]/255,D[3]),p.set($,x)),x}function _(P){const O=P.marker;if(!O)return;const D=e._stylePreset,$=e._selectedKey===P.key,x=$?q5:Ju,N=lE(D,$),G=x*aE(D,$),W=hE(N,G),V=G*W.ratio;O.image=hb(P.mode,$?dE:void 0,{style:D}),O.width=V,O.height=V,P.detectContact&&(P.detectContact.bracketHalfWidth=Math.ceil(V/2)+2,P.detectContact.bracketHalfHeight=Math.ceil(V/2)+2);const H=g(D,P.mode);H?O.color=H:O.color=nd[P.mode]||nd.unknown}function m(P,O){const D=e._markers.add({id:P,position:O.toCart,image:hb(O.mode),width:Ju,height:Ju,color:nd[O.mode],rotation:0,alignedAxis:Cesium.Cartesian3.ZERO,disableDepthTestDistance:Number.POSITIVE_INFINITY});return O.marker=D,O.markerCollection=e._markers,D.show=!1,_(O),D}function b(P,O){P.mode=O,P.key===e._selectedKey&&(n.trails.style(),n.selection.refreshSelectedCard(!0)),e._detectRevision+=1,_(P)}function C(P){const O=P||"normal";if(O!==e._stylePreset){e._stylePreset=O;for(const D of e._vehicles.values())_(D);n.trails.style(),i("transit-style")}}function y(P){var $;const O=($=e._viewer)==null?void 0:$.scene;if(!(O!=null&&O.camera)||P-e._rotationAt0;P&&!e._renderHeld?(o("transit"),e._renderHeld=!0):!P&&e._renderHeld&&(r("transit"),e._renderHeld=!1,i("transit-settled"))}function w(){if(typeof document<"u"&&document.visibilityState==="hidden"||!e._enabled)return;const P=Date.now();if(e._vehicles.size===0){e._moving.clear(),M();return}const O=performance.now(),D=n.height.nearGround();let $=0;for(const N of e._heightDirty){if($++>=64)break;e._heightDirty.delete(N),N.marker&&(En(N,P,O),c(N,D),d(N))}for(const N of e._moving){if(!N.marker||!f(N)){e._moving.delete(N);continue}En(N,P,O),c(N,D),R5(N,O)&&(e._rotationDirty=!0),(!N.surfaceReady||N.sample.phase!=="playing"||N.sample.segmentSpeedMps===0)&&d(N),e._moving.has(N)||v(N)}n.trails.update(),y(P);const x=e._vehicles.get(e._selectedKey);x&&e._visible.has(x)&&x.courseDeg!==null&&(x.marker.rotation=Vp(e._viewer.scene,x.marker.position,x.courseDeg,x.marker.rotation)),e._heightDirty.size&&i("transit-height-batch"),M()}const E=new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84),k=new Cesium.BoundingSphere(void 0,5),T=new Cesium.Cartesian3,I=new Cesium.Cartesian3;function R(){e._visibilityDirty=!0,!(!e._enabled||e._visibilityTimer!==null)&&(e._visibilityTimer=setTimeout(()=>{e._visibilityTimer=null,S()},Math.max(0,sb-(Date.now()-e._visibilityAt))))}function S(){var W,V,H;if(!e._enabled)return 0;const P=Date.now();if(P-e._visibilityAt{const d=h.marker,f=(d==null?void 0:d.show)!==!1?d==null?void 0:d.position:null;return f&&Number.isFinite(f.x)&&Number.isFinite(f.y)&&Number.isFinite(f.z)?f:null}}function r(h){const d=e._selectedKey?e._vehicles.get(e._selectedKey):null;if(!d)return;const f=Date.now();if(!h&&f-e._selectedCardAt{var b,C,y,v,M,w;if(!Bt())return;const f=h.scene,p=Cesium.Cartesian2.clone(d.position),g=e._stylePreset,_=(C=(b=f.postProcessStages)==null?void 0:b.getStageByName)==null?void 0:C.call(b,`godsEyeView_${g}`);if(_!=null&&_.enabled&&(g==="thermal"||g==="surveillance")){const E=_.uniforms.intensity,k=f.canvas,T=k.clientWidth,I=k.clientHeight;let R=p.x/T,S=1-p.y/I;if(g==="surveillance"){const L=R*2-1,F=S*2-1,P=L*L+F*F,O=1+P*E*.25+P*P*E*.075;R=(L*O+1)/2,S=(F*O+1)/2}const A=1+(_.uniforms.pixelation-1)*E;R+=(Math.floor(R*k.width/A)*A/k.width-R)*E,S+=(Math.floor(S*k.height/A)*A/k.height-S)*E,p.x=R*T,p.y=(1-S)*I}const m=f.pick(p);if(e._lastPickForTest={id:typeof(m==null?void 0:m.id)=="string"?m.id:null,primitiveId:typeof((y=m==null?void 0:m.primitive)==null?void 0:y.id)=="string"?m.primitive.id:null,x:p.x,y:p.y,collection:((v=m==null?void 0:m.primitive)==null?void 0:v._billboardCollection)===e._animatedMarkers?"animated":((M=m==null?void 0:m.primitive)==null?void 0:M._billboardCollection)===e._markers?"stationary":null},m){const E=(w=m.primitive)==null?void 0:w.id;if(typeof E=="string"&&e._vehicles.has(E)){a(E);return}if(typeof m.id=="string"&&e._vehicles.has(m.id)){a(m.id);return}}e._selectedKey&&s()},Cesium.ScreenSpaceEventType.LEFT_CLICK),document.addEventListener("keydown",c))}function u(){e._clickHandler&&(e._clickHandler.destroy(),e._clickHandler=null),document.removeEventListener("keydown",c)}return{refreshSelectedCard:r,clearSelection:s,selectVehicle:a,onKeyDown:c,installClickHandler:l,removeClickHandler:u}}const fV=1e4;function mV({state:e,services:t,parts:n}){const{governorRequestRender:i}=t.render,{registerDynamicCredit:o,transitFeedCredit:r}=t.credits;function s(f){let p=e._feedStatus.get(f);return p||(p={count:0,lastUpdate:null,upstreamAt:null,receivedAt:null,error:null,retryInSec:null,stale:!1,pollSeq:0,loading:!1},e._feedStatus.set(f,p)),p}function a(f){var g;const p=e._vehicles.get(f);p&&(e._selectedKey===f&&n.selection.clearSelection(),p.marker&&((g=p.markerCollection)==null||g.remove(p.marker)),p.marker=null,p.detectContact=null,e._visible.delete(p),n.height.releaseVehicle(f,p.heightCell),e._moving.delete(p),e._heightDirty.delete(p),n.rendering.cancelWake(p),mc(p.track),e._vehicles.delete(f),e._detectRevision+=1)}function c(f){let p=0;for(const[g,_]of e._vehicles)_.feedId===f&&(a(g),p+=1);return p>0&&n.rendering.syncRenderHold(),p}function l(f){var _,m;let p=0;const g=new Set;for(const[b,C]of e._feedStatus)Number.isFinite(C.upstreamAt)&&f-C.upstreamAt>ob&&g.add(b);for(const[b,C]of e._vehicles)(g.has(C.feedId)||ab(C.record,f,C.fetchedAt))&&(a(b),p+=1);if(p>0){for(const b of g){const C=e._feedStatus.get(b);C&&(C.count=0,C.stale=!0)}n.rendering.syncRenderHold(),i("transit-evict"),(m=(_=e._dataManager)==null?void 0:_.refreshLayerStats)==null||m.call(_)}return p}function u(f,p,{stale:g,contactedAt:_=null}){var R,S,A,L,F,P;const m=Date.now(),b=Math.min(Number.isFinite(p==null?void 0:p.fetchedAt)?p.fetchedAt:m,m),C=Math.min(Number.isFinite(_)?_:b,m),y=s(f.id),v=m-Math.max(C,b);if(y.upstreamAt=Math.max(C,b),y.receivedAt=m,y.loading=!1,y.error=null,y.retryInSec=null,y.stale=g===!0||v>Dm,v>ob){c(f.id),y.count=0,n.rendering.syncRenderHold(),i("transit-stale-refused"),(S=(R=e._dataManager)==null?void 0:R.refreshLayerStats)==null||S.call(R);return}y.pollSeq+=1;const M=y.pollSeq;let w=0,E=0;const k=p.vehicles||[];y.lag||(y.lag=Xw());const T=y.snapshotAt===b||g===!0;y.snapshotAt=b;const I=performance.now();if(e._historyBudget.allocatedBytes>e._historyBudget.maxBytes*.9)for(const O of e._vehicles.values())!((A=O.marker)!=null&&A.show)&&O.key!==e._selectedKey&&Jw(O.track,m,2);for(const O of k){if(ab(O,m,b))continue;const D=Z5(f.id,O.id),$=a5(f,O.routeId),x=!l5(f,O.routeId),N=J5(O,b),G=N>b+fV?b:N,W={t:G,lat:O.lat,lon:O.lon,bearingDeg:Number.isFinite(O.bearing)?O.bearing:NaN,flags:N!==G?Mt.RECEIPT_TIME:O.timestampSource==="vehicle"?Mt.VEHICLE_TIME:O.timestampSource==="header"?Mt.FEED_TIME:Mt.RECEIPT_TIME};let V=e._vehicles.get(D);if(V){const H=Th(V,W,{receivedAt:m,monoNowMs:I,wallNowMs:m,replayed:T,modeInferred:x,context:{trip:O.tripId||"",route:O.routeId||"",mode:$}});if(!H.accepted){V.pollSeq=M,w+=1,H.reason!=="repeat"&&(E+=1);continue}V.mode!==$&&n.rendering.paintMode(V,$),V.modeInferred=x,En(V,m,I),n.rendering.schedulePlayback(V);const B=V.heightM,q=n.height.requestHeight(O.lat,O.lon);q.height!==null?(V.heightCell=q.cell,V.heightM=q.height,V.heightResolved=!0,V.heightPending=!1):(q.cell!==V.heightCell||!V.heightResolved)&&(V.heightCell=q.cell,V.heightResolved=!1,q.prior!==null&&(V.heightM=q.prior,V.heightPending=!1));const z=V.fixes[V.fixes.length-1],j=z.h;q.height!==null&&Ah(V,z,q.height),(V.heightM!==B||z.h!==j)&&e._heightDirty.add(V)}else{if(e._vehicles.size>=ib){e._limitWarned||(e._limitWarned=!0,console.warn(`[Data:Transit] vehicle cap ${ib} reached — extra vehicles are not rendered`));continue}const H=n.height.requestHeight(O.lat,O.lon),B=H.height===null?H.prior:H.height;if(V={key:D,feedId:f.id,marker:null,mode:$,modeInferred:x,heightM:B===null?0:B,heightCell:H.cell,heightResolved:H.height!==null,heightPending:H.height===null&&B===null,from:null,to:null,fromCart:null,toCart:null,playT:NaN,resets:0,courseDeg:Number.isFinite(O.bearing)?O.bearing:null,courseAt:m,courseEvalAt:I,record:O,fetchedAt:b,pollSeq:M},A5(V,e._historyBudget,y.lag),!Th(V,W,{receivedAt:m,monoNowMs:I,wallNowMs:m,replayed:T,modeInferred:x,context:{trip:O.tripId||"",route:O.routeId||"",mode:$}}).accepted){mc(V.track);continue}H.height!==null&&Ah(V,W,H.height),kh(V,m,I),V.from=V.segment.from,V.to=V.segment.to,n.rendering.refreshEndpoints(V),V.marker=n.rendering.addMarker(D,V),e._vehicles.set(D,V),n.rendering.schedulePlayback(V),V.courseDeg!==null&&(e._rotationDirty=!0)}V.record=O,V.fetchedAt=b,V.pollSeq=M,w+=1}for(const[O,D]of e._vehicles)D.feedId===f.id&&M-D.pollSeq>=$5&&a(O);l(m),y.count=w,y.lastUpdate=b,y.receivedAt=m,e._lastUpdate=Math.max(e._lastUpdate||0,b)||b,e._error=null,E>0&&!e._jumpWarned&&(e._jumpWarned=!0,console.warn(`[Data:Transit] ${f.id}: ${E} fix(es) implied impossible travel and were not animated`)),e._viewer&&o(e._viewer,r(f)),e._selectedKey&&((L=e._vehicles.get(e._selectedKey))==null?void 0:L.feedId)===f.id&&n.selection.refreshSelectedCard(!0),n.height.anchorFloors(),e._detectRevision++,n.rendering.requestVisibility(),n.rendering.syncRenderHold(),i("transit-poll"),(P=(F=e._dataManager)==null?void 0:F.refreshLayerStats)==null||P.call(F)}function h(f,p){if(!e._enabled||p!==e._generation)return Promise.resolve();const g=e._inFlight.get(f.id);if(g)return g.promise;const _=new AbortController,m=s(f.id);m.loading=m.count===0;const b=(async()=>{var C,y,v;try{const M=await fetch(`/api/transit/vehicles/${encodeURIComponent(f.id)}`,{signal:_.signal,headers:{Accept:"application/json"}});if(!M.ok){const k=await M.json().catch(()=>null),T=new Error(`transit proxy HTTP ${M.status}`);throw Number.isFinite(k==null?void 0:k.retryInSec)&&(T.retryInSec=k.retryInSec),T}const w=await M.json();if(!e._enabled||p!==e._generation||!e._activeFeeds.has(f.id))return;const E=Number.parseInt(M.headers.get("x-transit-contact")||"",10);u(f,w,{stale:M.headers.get("x-gev-cache")==="STALE-ERROR",contactedAt:Number.isFinite(E)?E:null})}catch(M){if((M==null?void 0:M.name)==="AbortError"||p!==e._generation)return;console.warn(`[Data:Transit] ${f.id} poll failed:`,(M==null?void 0:M.message)||M),m.error=`${f.name} feed unavailable`,m.retryInSec=Number.isFinite(M==null?void 0:M.retryInSec)?M.retryInSec:null,m.loading=!1,e._error=m.error,l(Date.now()),(y=(C=e._dataManager)==null?void 0:C.refreshLayerStats)==null||y.call(C)}finally{((v=e._inFlight.get(f.id))==null?void 0:v.controller)===_&&e._inFlight.delete(f.id)}})();return e._inFlight.set(f.id,{controller:_,promise:b}),b}function d(){for(const{controller:f}of e._inFlight.values())f.abort();e._inFlight.clear()}return{feedStatus:s,removeVehicle:a,removeFeedVehicles:c,sweepAgedVehicles:l,applySnapshot:u,pollFeed:h,abortAllInFlight:d}}function pV({state:e,services:t,parts:n}){const{governorRequestRender:i}=t.render;function o(u=e._viewer){var d;const h=(d=u==null?void 0:u.camera)==null?void 0:d.positionCartographic;return h&&Number.isFinite(h.height)?h.height:1/0}function r(u=e._viewer){var f,p,g,_;const h=(g=(f=u==null?void 0:u.camera)==null?void 0:f.computeViewRectangle)==null?void 0:g.call(f,(p=u.scene.globe)==null?void 0:p.ellipsoid);if(h){const m=Cesium.Rectangle.center(h);return{lat:Cesium.Math.toDegrees(m.latitude),lon:Cesium.Math.toDegrees(m.longitude)}}const d=(_=u==null?void 0:u.camera)==null?void 0:_.positionCartographic;return d?{lat:Cesium.Math.toDegrees(d.latitude),lon:Cesium.Math.toDegrees(d.longitude)}:null}function s(u){return e._altitudeGateOpen?u<=O5:u<=D5}function a(){var d,f,p;const u=e._viewer,h=(p=(d=u==null?void 0:u.camera)==null?void 0:d.computeViewRectangle)==null?void 0:p.call(d,(f=u.scene.globe)==null?void 0:f.ellipsoid);e._viewBounds=h?X5({south:Cesium.Math.toDegrees(h.south),north:Cesium.Math.toDegrees(h.north),west:Cesium.Math.toDegrees(h.west),east:Cesium.Math.toDegrees(h.east)}):null,e._visibilityDirty=!0,e._cameraRevision++,n.rendering.requestVisibility()}function c(){var f;if(!e._enabled||!e._viewer)return;a();const u=o();e._altitudeGateOpen=s(u);const h=e._altitudeGateOpen?r():null,d=new Map;if(h){for(const p of j_(h.lat,h.lon))d.set(p.id,p);for(const p of j_(h.lat,h.lon,H5))e._activeFeeds.has(p.id)&&d.set(p.id,p)}for(const p of[...e._activeFeeds.keys()])d.has(p)||((f=e._inFlight.get(p))==null||f.controller.abort(),e._inFlight.delete(p),e._activeFeeds.delete(p),e._feedStatus.delete(p),n.ingestion.removeFeedVehicles(p));for(const[p,g]of d)e._activeFeeds.has(p)||(e._activeFeeds.set(p,g),n.ingestion.pollFeed(g,e._generation));n.ingestion.sweepAgedVehicles(Date.now()),n.rendering.syncRenderHold(),i("transit-proximity")}function l(){a(),clearTimeout(e._cameraDebounceTimer),e._cameraDebounceTimer=setTimeout(()=>{e._cameraDebounceTimer=null,c()},B5)}return{refreshViewBounds:a,getCameraAltitude:o,getCameraCenterLatLon:r,altitudeGateOpen:s,runProximityCheck:c,onCameraChanged:l}}function gV({state:e,parts:t}){const n=[],i={};let o=1/0,r=0;function s(u,h){let d=(2166136261^h)>>>0;for(let f=0;f>>0;return d>>>0}function a(u=i){var f,p;if(!e._enabled||!((f=e._markers)!=null&&f.show)||e._vehicles.size===0)return n;const h=Number.isFinite(u.maxCount)?Math.max(1,Math.floor(u.maxCount)):1/0,d=Number.isFinite(u.seed)?Math.floor(u.seed):0;return o=h,r=d,e._detectCache||c(),((p=e._detectCache)==null?void 0:p.contacts)||n}function c(){if(!e._enabled)return;const u=e._detectCache,h=Date.now(),d=o,f=r;if(h-e._detectBuiltAt<250)return;if(e._detectBuiltAt=h,u&&u.revision===e._detectRevision&&u.maxCount===d&&u.seed===f){for(const m of u.contacts)m.metric=ub(m._entry,m._entry.mode,h);return}if(u)for(const m of u.contacts)m._entry.detectContact=null;const p=[];for(const m of e._visible){const b=m.marker;!(b!=null&&b.position)||b.show===!1||p.push(m)}let g=p;p.length>d&&(g=p.map(m=>({entry:m,rank:s(m.key,f)})).sort((m,b)=>m.rank-b.rank||(m.entry.keym.entry));const _=[];for(const m of g){if((!m.labelId||m.labelRecord!==m.record)&&(m.labelId=oV(m.record),m.labelRecord=m.record),!m.labelClass||m.labelMode!==m.mode){const C=e._activeFeeds.get(m.feedId)||su(m.feedId);m.labelClass=rV(m.mode,C),m.labelMode=m.mode}const b={position:m.marker.position,bracketHalfWidth:Math.ceil(m.marker.width/2)+2,bracketHalfHeight:Math.ceil(m.marker.height/2)+2,sourceId:m.key,id:m.labelId,type:"VEH",klass:m.labelClass,metric:ub(m,m.mode,h),tier:x5(m.mode),skipLabel:m.key===e._selectedKey,_entry:m};m.detectContact=b,_.push(b)}return e._detectCache={revision:e._detectRevision,maxCount:d,seed:f,contacts:_},_}return{methods:{getDetectableObjects(u=i){return a(u)},getStats(){const u=[...e._activeFeeds.values()],h=u.map(_=>t.ingestion.feedStatus(_.id)),d=Date.now(),f=eV(h,d),p=e._vehicles.size;if(e._enabled&&u.length===0)return{count:0,lastUpdate:e._lastUpdate,error:null,source:"GTFS-RT",status:"zoom-in",coverage:e._altitudeGateOpen?`No feed here yet · ${ru.length} regions available`:`Fly below ${Math.round(Nm/1e3).toLocaleString()} km to a covered region`};const g=u.map(_=>{const m=t.ingestion.feedStatus(_.id),C=(m.stale===!0||Number.isFinite(m.upstreamAt)&&d-m.upstreamAt>Dm)&&Number.isFinite(m.upstreamAt)?` (${Math.round((d-m.upstreamAt)/1e3)}s old)`:"";return`${_.name} ${m.count}${C}`}).join(" · ");return{count:p,lastUpdate:e._lastUpdate,error:p===0?f.error:null,...p===0&&Number.isFinite(f.retryInSec)?{retryInSec:f.retryInSec}:{},degraded:p>0&&f.degraded,loading:f.loading&&p===0,loadingLabel:f.loading&&p===0?`Loading ${u.map(_=>_.name).join(", ")}`:void 0,stale:f.stale,source:"GTFS-RT",coverage:g,feeds:u.map(_=>_.id)}}},refreshDetectCache:c}}function _V({state:e}){return{methods:{attachDataManager(n){e._dataManager=n}}}}function bV({state:e,services:t,parts:n}){const{registerSpriteCollection:i,unregisterSpriteCollection:o,restoreSpriteOrder:r}=t.sprites,{registerPickOwner:s,unregisterPickOwner:a}=t.picking,{releaseContinuousRender:c}=t.render;function l(C){km(C==null?void 0:C.camera,"transit",V5)}function u(C){hc(C==null?void 0:C.camera,"transit")}function h(){var v,M;if(typeof window>"u"||e._styleListeners.length>0)return;n.rendering.setStylePreset(((M=(v=document==null?void 0:document.documentElement)==null?void 0:v.dataset)==null?void 0:M.gevStyle)||"normal");const C=w=>{var E;e._cockpitVision||n.rendering.setStylePreset((E=w==null?void 0:w.detail)==null?void 0:E.style)},y=w=>{var E,k;e._cockpitVision=((E=w==null?void 0:w.detail)==null?void 0:E.cockpit)===!0,n.rendering.setStylePreset((k=w==null?void 0:w.detail)==null?void 0:k.style)};window.addEventListener("gev:style-change",C),window.addEventListener("gev:vision-change",y),e._styleListeners.push(["gev:style-change",C],["gev:vision-change",y])}function d(){if(!(typeof window>"u")){for(const[C,y]of e._styleListeners)window.removeEventListener(C,y);e._styleListeners.length=0,e._cockpitVision=!1}}let f=null,p=!1;function g(){f.visibilityState==="hidden"?p=!0:p&&(p=!1,n.rendering.resumePlayback())}function _(){f||typeof document>"u"||(f=document,p=document.visibilityState==="hidden",f.addEventListener("visibilitychange",g))}function m(){f==null||f.removeEventListener("visibilitychange",g),f=null,p=!1}return{methods:{id:"transit",name:"Transit",icon:"🚌",source:"GTFS-RT",init(C){e._viewer=C,e._markers=new Cesium.BillboardCollection({blendOption:Cesium.BlendOption.TRANSLUCENT}),C.scene.primitives.add(e._markers),i("transit",e._markers),e._animatedMarkers=new Cesium.BillboardCollection({blendOption:Cesium.BlendOption.TRANSLUCENT}),C.scene.primitives.add(e._animatedMarkers),i("transit-motion",e._animatedMarkers),e._animatedMarkers.show=!1,e._markers.show=!1,e._enabled=!1,e._activeFeeds.clear(),e._feedStatus.clear(),e._inFlight.clear();for(const y of e._vehicles.values())y.detectContact=null,n.rendering.cancelWake(y),mc(y.track);e._vehicles.clear(),n.height.clear(),e._selectedKey=null,e._lastUpdate=null,e._error=null,e._limitWarned=!1,e._altitudeGateOpen=!1,e._moving.clear(),e._heightDirty.clear(),e._rotationPose=null,e._rotationDirty=!1,e._overlayHost.setVisible(mr,!1),r(C),h(),console.log(`[Data:Transit] Initialized with ${ru.length} GTFS-RT feeds`)},enable(C){e._enabled=!0,_(),e._generation+=1,e._error=null,e._markers.show=!0,e._animatedMarkers.show=!0,e._maintenanceTimer=setInterval(n.rendering.maintainPresentation,250),e._overlayHost.setVisible(mr,!0),n.selection.installClickHandler(C),s("transit",y=>e._vehicles.has(y)),e._cameraChangedAttached||(C.camera.changed.addEventListener(n.viewport.onCameraChanged),l(C),e._cameraChangedAttached=!0),e._preRenderRemove||(e._preRenderRemove=C.scene.preRender.addEventListener(n.rendering.onPreRender)),n.viewport.runProximityCheck(),r(C)},disable(C){var y,v,M;e._enabled=!1,m(),n.testing._stopTransitProbeForTest(),(y=e._qaFixtureFloors)==null||y.clear(),e._generation+=1,clearInterval(e._maintenanceTimer),e._maintenanceTimer=null,clearTimeout(e._visibilityTimer),e._visibilityTimer=null,e._detectCache=null,e._detectBuiltAt=-1/0,e._visible.clear(),clearTimeout(e._cameraDebounceTimer),e._cameraDebounceTimer=null,n.selection.clearSelection(),e._overlayHost.setVisible(mr,!1),n.selection.removeClickHandler(),a("transit"),e._cameraChangedAttached&&(C.camera.changed.removeEventListener(n.viewport.onCameraChanged),u(C),e._cameraChangedAttached=!1),e._preRenderRemove&&(e._preRenderRemove(),e._preRenderRemove=null),n.ingestion.abortAllInFlight(),e._activeFeeds.clear(),e._feedStatus.clear();for(const w of e._vehicles.values())w.detectContact=null,n.rendering.cancelWake(w),mc(w.track);e._vehicles.clear(),n.height.clear(),(v=e._markers)==null||v.removeAll(),(M=e._animatedMarkers)==null||M.removeAll(),e._animatedMarkers&&(e._animatedMarkers.show=!1),e._markers&&(e._markers.show=!1),e._altitudeGateOpen=!1,e._moving.clear(),e._heightDirty.clear(),e._rotationPose=null,e._rotationDirty=!1,e._renderHeld&&(c("transit"),e._renderHeld=!1)},async update(){if(!e._enabled||(n.ingestion.sweepAgedVehicles(Date.now()),e._activeFeeds.size===0))return;const C=e._generation;await Promise.all([...e._activeFeeds.values()].map(y=>n.ingestion.pollFeed(y,C)))},destroy(C){var y,v,M,w;this.disable(C),e._markers&&(o("transit",e._markers),(v=(y=C==null?void 0:C.scene)==null?void 0:y.primitives)==null||v.remove(e._markers),e._markers=null),e._animatedMarkers&&(o("transit-motion",e._animatedMarkers),(w=(M=C==null?void 0:C.scene)==null?void 0:M.primitives)==null||w.remove(e._animatedMarkers),e._animatedMarkers=null),e._overlayHost.clearSource(mr),n.height.clear(),d(),e._dataManager=null,e._viewer=null}}}}function CV({state:e,parts:t}){let n=null;return{_setTransitFixtureFloorsForTest(i,o){e._qaFixtureFloors=new Map(i.map(r=>[r,o]))},_stopTransitProbeForTest(){n==null||n()},_loadTransitFleetForTest(i,o,r=6,s=["741"]){t.selection.clearSelection(),t.ingestion.abortAllInFlight(),e._activeFeeds.clear();for(const f of e._vehicles.keys())t.ingestion.removeVehicle(f);clearTimeout(e._cameraDebounceTimer),e._cameraDebounceTimer=null;const a=su("mbta"),c=Date.now(),l=performance.now(),u=Math.ceil(Math.sqrt(i)),h=Array.from({length:i},(f,p)=>({id:`qa-${p}`,routeId:s[p%s.length],tripId:"qa",lat:o.lat+(Math.floor(p/u)-u/2)*r/111320,lon:o.lon+(p%u-u/2)*r/(111320*Math.cos(o.lat*Math.PI/180)),timestamp:(c-12e4)/1e3,timestampSource:"vehicle",bearing:0}));t.ingestion.applySnapshot(a,{fetchedAt:c,vehicles:h},{stale:!1});let d=0;for(const f of e._vehicles.values()){f.qaIndex=d++,f.qaFixture=!0,f.qaFloorM=20;for(let g=1;g<=8;g++){const _=c-12e4+g*15e3;Th(f,{t:_,lat:f.record.lat+g*15/111320,lon:f.record.lon,bearingDeg:0},{receivedAt:_+1e3,wallNowMs:_+1e3,monoNowMs:l-c+_+1e3})}tE(f.track,Array.from({length:119},(g,_)=>{const m=c-899e3+_*6474.576271186441;return{t:m,lat:f.record.lat+(m-c+12e4)/1e3/111320,lon:f.record.lon,bearingDeg:0,epoch:f.currentEpoch}}));for(const g of f.fixes)Ah(f,g,20);f.heightPending=!1,f.surfaceReady=!0,f.displayPaths=new Map;const p=f.fixes;for(let g=0;g+1{l[y]=v})}for(const y of[e._markers,e._animatedMarkers]){const v=y.update;y.update=function(M){u=!0;try{return v.call(this,M)}finally{u=!1}},g.push(()=>{y.update=v})}(C=e._preRenderRemove)==null||C.call(e);const _=o.preRender.addEventListener(()=>{h=0;const y=performance.now();t.rendering.onPreRender(),d=performance.now()-y});let m,b;return new Promise(y=>{const v=()=>{clearTimeout(b),_(),m==null||m();for(const w of g)w();e._enabled&&(e._preRenderRemove=o.preRender.addEventListener(t.rendering.onPreRender)),n=null;const M=[];for(let w=1;w{const M=performance.now();if(f>=r)return;const w=f++*s,E=e._vehicles.get("mbta:qa-0");a[w]=p?M-p:0,p=M,a[w+1]=d,a[w+2]=h;let k=0;for(const T of e._visible){const I=T.marker.position,R=T.qaIndex*3;f>1&&Math.hypot(I.x-c[R],I.y-c[R+1],I.z-c[R+2])>1e-5&&k++,c[R]=I.x,c[R+1]=I.y,c[R+2]=I.z}if(a[w+3]=k,E!=null&&E.marker){const T=E.marker.position;a[w+4]=T.x,a[w+5]=T.y,a[w+6]=T.z,a[w+7]=E.sample.displayT,a[w+8]=E.sample.segmentSpeedMps,a[w+9]=E.sample.fromSeq}}),b=setTimeout(v,i)})},_transitVisibilityForTest(){return[...e._vehicles.values()].map(i=>{var s,a;const o=i.visibility||{},r=[];return i.marker||r.push("no marker"),o.bounds===!1&&o.boundsApplied&&r.push("bounds"),o.occluder===!1&&r.push("occluder"),o.frustum===!1&&r.push("frustum"),i.heightPending&&r.push("heightPending"),i.surfaceReady===!1&&r.push("surfaceReady"),(!i.sample||!Number.isFinite(i.sample.lat))&&r.push("no sample"),e._enabled||r.push("disabled"),{key:i.key,shown:((s=i.marker)==null?void 0:s.show)===!0,why:r,...o,heightPending:!!i.heightPending,surfaceReady:i.surfaceReady??null,moving:e._moving.has(i),held:e._renderHeld,heightM:i.heightM,phase:(a=i.sample)==null?void 0:a.phase}})},_transitStylingForTest(){return{stylePreset:e._stylePreset,cockpitVision:e._cockpitVision,iconCacheSize:uV()}},_setTransitOverlayHostForTest(i){e._overlayHost=i||e.DEFAULT_OVERLAY_HOST},_transitStateForTest(){return e},_transitPartsForTest(){return t}}}function yV({services:e}){if(!(e!=null&&e.overlays)||!(e!=null&&e.render)||!(e!=null&&e.sprites))throw new TypeError("A transit layer needs overlay, render and sprite services");const t=S5({services:e}),n={},i={state:t,services:e,parts:n};return n.trails=F5(i),n.height=aV(i),n.selection=hV(i),n.rendering=dV(i),n.ingestion=mV(i),n.viewport=pV(i),n.queries=gV(i),n.controls=_V(i),n.lifecycle=bV(i),n.testing=CV(i),Object.assign({updateInterval:cE},n.lifecycle.methods,n.queries.methods,n.controls.methods,n.testing)}function vV({surface:e}){if(!(e!=null&&e.groundFloor)||!(e!=null&&e.meshFloor))throw new TypeError("Transit needs the application surface services");const{groundFloor:t,meshFloor:n}=e;return yV({services:{render:Pt,sprites:Ki,picking:rn,overlays:ui,credits:{registerDynamicCredit:gm,transitFeedCredit:VM},ground:{GROUND_FLOOR_LIFT_M:t.GROUND_FLOOR_LIFT_M,cachedGroundFloor:t.cachedGroundFloor,coarseFloorCoord:t.coarseFloorCoord,neighborFloorM:t.neighborFloorM,warmGroundFloor:t.warmGroundFloor,corridorFloorCells:t.corridorFloorCells,allocateCorridorCells:t.allocateCorridorCells},mesh:{sampleMeshFloorCells:n.sampleMeshFloorCells}}})}const ko="military-installations",MV=500,fb=10,wV=700,EV=new Set(["military_base"]),fE={airfield:"#5aa9ff",naval_base:"#48c7d5",range:"#d9a85d",military_land:"#9ca6b0",places_candidate:"#c58cff"},TV=63710088e-1,kV=5e3;function AV({state:e,services:t,parts:n,source:i}){function o(u,h,d,f){const p=Cesium.Math.toRadians(d),g=Cesium.Math.toRadians(f),_=p-u,m=Math.atan2(Math.sin(g-h),Math.cos(g-h)),b=Math.sin(_/2),C=Math.sin(m/2),y=b*b+Math.cos(u)*Math.cos(p)*C*C;return 2*TV*Math.asin(Math.min(1,Math.sqrt(y)))}function r(u){return Cesium.Color.fromCssColorString(fE[u.class]||"#9ca6b0")}function s(u){return[...new Set([u==null?void 0:u.primaryType,...Array.isArray(u==null?void 0:u.types)?u.types:[]].map(d=>String(d||"").trim().toLowerCase()).filter(Boolean))].some(d=>EV.has(d))?"military_land":"places_candidate"}function a(u){return[...new Set((Array.isArray(u==null?void 0:u.sources)?u.sources:[]).map(d=>String((d==null?void 0:d.name)||"").trim()).filter(Boolean))].join(" + ")||"Unknown mapped source"}function c(u,h){if(!u||!h)return!1;const{latitude:d,longitude:f,footprint:p}=u;if(d>=h.south&&d<=h.north&&f>=h.west&&f<=h.east)return!0;if(Array.isArray(p)&&p.length){let _=1/0,m=-1/0,b=1/0,C=-1/0;for(const[y,v]of p)v<_&&(_=v),v>m&&(m=v),yC&&(C=y);return m>=h.south&&_<=h.north&&C>=h.west&&b<=h.east}return u.osmType!=="node"}function l(u){if(typeof(u==null?void 0:u.saturated)=="boolean")return u.saturated;const h=Number(u==null?void 0:u.elementCap);return!Number.isFinite(h)||h<=0?!1:Array.isArray(u==null?void 0:u.elements)&&u.elements.length>=h}return{approximateSurfaceDistanceM:o,colorFor:r,classifyGoogleMilitaryPlace:s,installationSourceLabel:a,installationWithinViewport:c,installationResponseSaturated:l}}function IV({state:e,services:t,parts:n,source:i}){const{floorAltitudeM:o,cachedGroundFloor:r}=t.ground,{removeEntityContextsForLayer:s,getSelectedEntityContext:a,registerEntityContext:c,selectEntityContext:l}=t.context,{governorRequestRender:u}=t.render,{warmFireAnchorFloors:h}=t.anchors;function d(m){return o(null,r(m==null?void 0:m.latitude,m==null?void 0:m.longitude))??0}function f(){var m;(m=e.dataSource)!=null&&m.entities&&e.dataSource.entities.removeAll(),s(ko)}function p(){const m=e.records.slice(0,wV);if(!e.selectedId||m.some(C=>C.id===e.selectedId))return m;const b=e.recordById.get(e.selectedId);return b?[...m,b]:m}function g({claimSelection:m=!1}={}){const b=a();!m&&e.selectedId&&b&&b.id!==e.selectedId&&(e.selectedId=null),u("installations-render"),f();for(const y of p()){const v=n.model.colorFor(y),M=d(y),w=Cesium.Cartesian3.fromDegrees(y.longitude,y.latitude,M),E=e.dataSource.entities.add({id:y.id,position:w,point:{pixelSize:y.id===e.selectedId?13:9,color:y.id===e.selectedId?Cesium.Color.WHITE:v,outlineColor:Cesium.Color.BLACK.withAlpha(.8),outlineWidth:1,disableDepthTestDistance:Number.POSITIVE_INFINITY},polygon:y.footprint?{hierarchy:new Cesium.PolygonHierarchy(y.footprint.map(([k,T])=>Cesium.Cartesian3.fromDegrees(k,T))),material:v.withAlpha(.12),outline:!0,outlineColor:v.withAlpha(.65),height:M}:void 0});E.gevTrackedId=`installations:${y.id}`,E.gevDisplayPosition=()=>w,E.gevLabelModel={title:y.name||"MAPPED INSTALLATION",details:[String(y.class||"installation").replaceAll("_"," ").toUpperCase()],accent:fE[y.class]||"#9ca6b0"},c(E,{id:y.id,layerId:ko,layerName:y.kind==="place_candidate"?"Military Site Search Candidates":"Mapped Military Installations",source:n.model.installationSourceLabel(y),label:y.name,latitude:y.latitude,longitude:y.longitude,properties:{class:y.class,primaryType:y.primaryType||null,placeTypes:Array.isArray(y.placeTypes)?y.placeTypes:[],validation:y.validation,retrievedAt:y.retrievedAt}})}const C=e.selectedId?e.dataSource.entities.getById(e.selectedId):null;C?l(C):e.selectedId=null}function _(m){const b=m.filter(C=>r(C.latitude,C.longitude)==null).map(C=>({lat:C.latitude,lon:C.longitude}));b.length&&h(b).then(()=>{!e.enabled||!e.dataSource||b.some(C=>r(C.lat,C.lon)!=null)&&g()})}return{installationSurfaceHeightM:d,clearRendered:f,renderableRecords:p,renderRecords:g,warmInstallationFloors:_}}const RV={airfield:"airfield",naval_base:"naval_base",range:"range",barracks:"military_land",base:"military_land"},mb={airfield:"Military airfield",naval_base:"Naval base",range:"Firing range",military_land:"Military land"},LV=400;function PV(e){const t=String(e||"").trim().toLowerCase();if(mb[t])return mb[t];const n=t.replaceAll("_"," ").trim();return n?`${n[0].toUpperCase()}${n.slice(1)}`:"Mapped installation"}function pl(e){return Number.isFinite(e)&&e>=-90&&e<=90}function gl(e){return Number.isFinite(e)&&e>=-180&&e<=180}function xV(e){var c,l;const t=Number((e==null?void 0:e.lat)??((c=e==null?void 0:e.center)==null?void 0:c.lat)),n=Number((e==null?void 0:e.lon)??((l=e==null?void 0:e.center)==null?void 0:l.lon));if(pl(t)&&gl(n))return{latitude:t,longitude:n};const i=e==null?void 0:e.bounds;if(![i==null?void 0:i.minlat,i==null?void 0:i.minlon,i==null?void 0:i.maxlat,i==null?void 0:i.maxlon].every(u=>typeof u=="number"&&Number.isFinite(u)))return null;const o=Number(i==null?void 0:i.minlat),r=Number(i==null?void 0:i.minlon),s=Number(i==null?void 0:i.maxlat),a=Number(i==null?void 0:i.maxlon);return pl(o)&&pl(s)&&gl(r)&&gl(a)&&o<=s&&r<=a&&s-o<=10&&a-r<=10?{latitude:(o+s)/2,longitude:(r+a)/2}:null}function FV(e){if(!Array.isArray(e==null?void 0:e.geometry)||e.geometry.length<3||e.geometry.length>LV)return null;const t=[];for(const n of e.geometry){const i=Number(n==null?void 0:n.lat),o=Number(n==null?void 0:n.lon);if(!pl(i)||!gl(o))return null;t.push([o,i])}return t}function SV(e,t=new Date().toISOString()){const n=[],i=new Set;let o=0;for(const r of Array.isArray(e==null?void 0:e.elements)?e.elements:[]){const s=String((r==null?void 0:r.type)||""),a=Number(r==null?void 0:r.id);if(!["node","way","relation"].includes(s)||!Number.isSafeInteger(a)){o+=1;continue}const c=`osm:${s}:${a}`,l=(r==null?void 0:r.tags)||{},u=RV[String(l.military||"").toLowerCase()]||(l.landuse==="military"?"military_land":null),h=xV(r);if(!u||!h||i.has(c)){o+=1;continue}i.add(c),n.push({id:c,kind:"installation",osmType:s,class:u,name:String(l.name||l["name:en"]||"").trim()||PV(u),...h,footprint:FV(r),sources:[{name:"OpenStreetMap",id:`${s}/${a}`,retrievedAt:t}],validation:"unreviewed",retrievedAt:t})}return{records:n,droppedCount:o}}function NV({state:e,services:t,parts:n,source:i}){const{governorRequestRender:o}=t.render,{resolveGroundFloorCellsBounded:r}=t.ground;function s(l,u=null){e.status===l&&e.error===u||(e.status=l,e.error=u,o("installations-status"))}async function a(){var h,d;if(!e.enabled||!e.viewer)return;const l=n.viewport.viewportBox(e.viewer);if(!l){(h=e.abort)==null||h.abort(),e.abort=null,e.loading=!1,n.viewport.clearUnavailableRetry(),s("zoom-in");return}(d=e.abort)==null||d.abort();const u=new AbortController;e.abort=u,e.loading=!0,n.viewport.clearUnavailableRetry({resetBackoff:!1}),s("loading");try{const f=C=>i.getMappedSites(l,{exact:C,signal:u.signal});let p=await f(!1),g=n.model.installationResponseSaturated(p);g&&(p=await f(!0),g=n.model.installationResponseSaturated(p));const m=SV(p,p.retrievedAt||new Date().toISOString()).records.filter(C=>n.model.installationWithinViewport(C,l));let b=null;if(e.googleSearchRequested){e.googleSearchRequested=!1;const C=(l.south+l.north)/2,y=(l.west+l.east)/2,v=Math.min(5e4,Math.max(1e3,Math.round(Math.max(l.north-l.south,l.east-l.west)*55e3)));try{const M=await i.searchNearby({latitude:C,longitude:y,radiusM:v},{signal:u.signal}),w=new Set(m.map(E=>`${E.name.toLowerCase()}|${E.latitude.toFixed(3)}|${E.longitude.toFixed(3)}`));for(const E of Array.isArray(M==null?void 0:M.places)?M.places:[]){if(!(E!=null&&E.id)||!(E!=null&&E.name)||!Number.isFinite(E.latitude)||!Number.isFinite(E.longitude))continue;const k=n.model.classifyGoogleMilitaryPlace(E),T=`${String(E.name).toLowerCase()}|${E.latitude.toFixed(3)}|${E.longitude.toFixed(3)}`;if(w.has(T))continue;w.add(T);const I=new Date().toISOString();m.push({id:`google:${E.id}`,kind:k==="military_land"?"installation":"place_candidate",class:k,name:String(E.name).trim(),latitude:E.latitude,longitude:E.longitude,footprint:null,primaryType:E.primaryType||null,placeTypes:Array.isArray(E.types)?E.types:[],sources:[{name:"Google Maps Places",id:E.id,retrievedAt:I}],validation:"unreviewed",retrievedAt:I})}}catch(M){if(u.signal.aborted||e.abort!==u||!e.enabled||(M==null?void 0:M.name)==="AbortError")return;b="Google Places search unavailable; showing mapped sites"}}if(await r(m.map(C=>({lat:C.latitude,lon:C.longitude}))),u.signal.aborted||e.abort!==u||!e.enabled)return;e.records=m,e.recordById=new Map(e.records.map(C=>[C.id,C])),e.lastUpdate=Date.now(),e.stale=p.status==="stale",e.saturated=g,e.failureReason=null,n.viewport.clearUnavailableRetry(),s(e.records.length?e.stale?"stale":"ready":"empty",p.status==="stale"?"Serving cached mapped context":g?"Too many mapped sites in view to list them all":b),n.rendering.renderRecords(),n.rendering.warmInstallationFloors(e.records)}catch(f){if(u.signal.aborted||e.abort!==u||!e.enabled||(f==null?void 0:f.name)==="AbortError")return;e.failureReason=(f==null?void 0:f.failureReason)||"unavailable",s("unavailable",(f==null?void 0:f.message)||"Installation context unavailable"),n.viewport.scheduleUnavailableRetry()}finally{e.abort===u&&(e.abort=null,e.loading=!1)}}return{setInstallationStatus:s,loadInstallations:a,methods:{update(){return a()}}}}function DV({state:e,services:t,parts:n,source:i}){function o(l){var g;const u=(g=l==null?void 0:l.camera)==null?void 0:g.computeViewRectangle(l.scene.globe.ellipsoid);if(!u)return null;const h=Cesium.Math.toDegrees(u.south),d=Cesium.Math.toDegrees(u.north),f=Cesium.Math.toDegrees(u.west),p=Cesium.Math.toDegrees(u.east);return!Number.isFinite(h+d+f+p)||p<=f||d-h>fb||p-f>fb?null:{south:h,west:f,north:d,east:p}}function r(l){return!Number.isFinite(l)||l<=0?3e4:Math.min(l*2,24e4)}function s(){e.enabled&&(clearTimeout(e.retryTimer),e.retryDelayMs=r(e.retryDelayMs),e.retryAt=Date.now()+e.retryDelayMs,e.retryTimer=setTimeout(()=>{e.retryTimer=null,e.retryAt=0,e.enabled&&!e.loading&&n.ingestion.loadInstallations()},e.retryDelayMs))}function a({resetBackoff:l=!0}={}){clearTimeout(e.retryTimer),e.retryTimer=null,e.retryAt=0,l&&(e.retryDelayMs=0)}function c(){e.enabled&&(a({resetBackoff:!1}),clearTimeout(e.timer),e.timer=setTimeout(()=>{n.ingestion.loadInstallations()},MV))}return{viewportBox:o,installationRetryDelayMs:r,scheduleUnavailableRetry:s,clearUnavailableRetry:a,scheduleLoad:c}}function OV({state:e,services:t,parts:n,source:i}){const{clearSelectedEntityContextForLayer:o}=t.context;function r(a){return!e.recordById.get(a)||!e.dataSource?!1:(e.selectedId=a,n.rendering.renderRecords({claimSelection:!0}),e.selectedId===a)}function s(a){e.clickHandler||(e.clickHandler=new Cesium.ScreenSpaceEventHandler(a.scene.canvas),e.clickHandler.setInputAction(c=>{var h;if(!Bt()||!e.enabled)return;const l=a.scene.pick(c.position),u=typeof((h=l==null?void 0:l.id)==null?void 0:h.id)=="string"?l.id.id:null;u&&e.recordById.has(u)&&u!==e.selectedId?r(u):e.selectedId&&(e.selectedId=null,o(ko),n.rendering.renderRecords())},Cesium.ScreenSpaceEventType.LEFT_CLICK))}return{selectRecord:r,installInteraction:s}}function mE(e={},t=Date.now()){const i={rate_limited:"Overpass rate-limited",timeout:"Overpass timed out",query_failed:"Overpass could not complete the query"}[e.failureReason]||"Overpass temporarily unavailable";if(e.loading)return e.retrying?"Retrying mapped sites…":"Fetching mapped sites…";if(e.retryAt>0){const o=Math.max(0,Math.ceil((e.retryAt-t)/1e3));return`${i} — ${o?`retrying in ${o}s`:"retry pending"}`}return e.status==="unavailable"?i:e.status==="zoom-in"?"Zoom in to search mapped installations":e.stale?"Showing cached mapped sites":e.status==="idle"?"Mapped sites not loaded":"Mapped sites loaded"}function BV({state:e,services:t,parts:n,source:i}){return{methods:{id:ko,name:"Mapped Installations",icon:"⌖",source:"OpenStreetMap + optional Google Maps Places",updateInterval:0,statsRefreshInterval:1e3,searchNearby(){return e.googleSearchRequested=!0,n.ingestion.loadInstallations()},getNearby(r,s,a=50){if(!r)return[];const c=Number.isFinite(s)?s:1/0,l=Cesium.Cartographic.fromCartesian(r);if(!l)return[];const u=[],h=Number.isFinite(c)?c*1.03+kV:1/0;for(const d of e.records){if(d.kind!=="installation"||n.model.approximateSurfaceDistanceM(l.latitude,l.longitude,d.latitude,d.longitude)>h)continue;e.distanceEndpointScratch.longitude=Cesium.Math.toRadians(d.longitude),e.distanceEndpointScratch.latitude=Cesium.Math.toRadians(d.latitude),e.distanceEndpointScratch.height=0,e.distanceGeodesicScratch.setEndPoints(l,e.distanceEndpointScratch);const f=e.distanceGeodesicScratch.surfaceDistance;!Number.isFinite(f)||f>c||u.push({...d,position:Cesium.Cartesian3.fromDegrees(d.longitude,d.latitude,n.rendering.installationSurfaceHeightM(d)),distanceM:f})}return u.sort((d,f)=>d.distanceM-f.distanceM),u.slice(0,Number.isFinite(a)?Math.max(1,Math.floor(a)):50)},focusById(r){const s=e.recordById.get(String(r));return!s||!e.viewer||!n.selection.selectRecord(s.id)?!1:(e.viewer.camera.flyToBoundingSphere(new Cesium.BoundingSphere(Cesium.Cartesian3.fromDegrees(s.longitude,s.latitude,n.rendering.installationSurfaceHeightM(s)),18e3),{duration:1.4}),!0)},getStats(){return{count:e.records.length,lastUpdate:e.lastUpdate,stale:e.stale,saturated:e.saturated,error:e.error,status:e.status,loading:e.loading,retryAt:e.retryAt,retrying:e.loading&&!!e.failureReason,failureReason:e.failureReason,statusMessage:mE({...e,retrying:e.loading&&!!e.failureReason}),loadingLabel:e.loading?"loading mapped installation context":""}}}}}function VV({state:e,services:t,parts:n,source:i}){const{registerPickOwner:o,unregisterPickOwner:r}=t.picking,{clearSelectedEntityContextForLayer:s}=t.context;return{methods:{init(c){e.viewer=c,e.dataSource=new Cesium.CustomDataSource("military-installations"),c.dataSources.add(e.dataSource),e.moveEndRemove=c.camera.moveEnd.addEventListener(n.viewport.scheduleLoad),n.selection.installInteraction(c)},enable(){e.enabled=!0,o(ko,c=>e.recordById.has(c)),e.dataSource.show=!0},disable(){var c;e.enabled=!1,r(ko),n.viewport.clearUnavailableRetry(),clearTimeout(e.timer),(c=e.abort)==null||c.abort(),e.abort=null,e.loading=!1,e.dataSource&&(e.dataSource.show=!1),s(ko),e.selectedId=null,e.failureReason=null,n.ingestion.setInstallationStatus("idle")},destroy(c){var l,u;this.disable(),(l=e.moveEndRemove)==null||l.call(e),(u=e.clickHandler)==null||u.destroy(),e.clickHandler=null,n.rendering.clearRendered(),e.dataSource&&c&&c.dataSources.remove(e.dataSource,!0),e.dataSource=null}}}}function HV({services:e}){const t={};return t.distanceEndpointScratch=new Cesium.Cartographic,t.distanceGeodesicScratch=new Cesium.EllipsoidGeodesic,Object.assign(t,{viewer:null,dataSource:null,enabled:!1,records:[],recordById:new Map,selectedId:null,lastUpdate:null,error:null,status:"idle",stale:!1,saturated:!1,loading:!1,abort:null,retryTimer:null,retryDelayMs:0,retryAt:0,failureReason:null,moveEndRemove:null,clickHandler:null,timer:null,googleSearchRequested:!1}),t}function $V({fetchImpl:e=(...t)=>globalThis.fetch(...t)}={}){return{async getMappedSites(t,{exact:n=!1,signal:i}={}){const{south:o,west:r,north:s,east:a}=t||{};if(![o,r,s,a].every(Number.isFinite)||o<-90||s>90||r<-180||a>180||s<=o||a<=r||s-o>10||a-r>10)throw new TypeError("A bounded installation viewport is required");i==null||i.throwIfAborted();const c=new URLSearchParams(Object.entries({south:o,west:r,north:s,east:a}).map(([h,d])=>[h,d.toFixed(5)]));n&&c.set("exact","1");const l=await e(`/api/military-installations?${c}`,{signal:i}),u=await l.json();if(i==null||i.throwIfAborted(),!l.ok)throw Object.assign(new Error((u==null?void 0:u.error)||`Installation feed HTTP ${l.status}`),{failureReason:["rate_limited","timeout","query_failed"].includes(u==null?void 0:u.reason)?u.reason:"unavailable"});if(!Array.isArray(u==null?void 0:u.elements))throw new Error("Malformed installation snapshot");return u},async searchNearby({latitude:t,longitude:n,radiusM:i},{signal:o}={}){if(![t,n,i].every(Number.isFinite)||Math.abs(t)>90||Math.abs(n)>180||i<1e3||i>5e4)throw new TypeError("Invalid nearby installation search");o==null||o.throwIfAborted();const r=await e(`/api/google/text-search?${new URLSearchParams({q:"military installation",lat:t.toFixed(5),lon:n.toFixed(5),radiusM:String(i)})}`,{signal:o}),s=await r.json();if(o==null||o.throwIfAborted(),!r.ok)throw new Error((s==null?void 0:s.error)||`Google Places HTTP ${r.status}`);if(!Array.isArray(s==null?void 0:s.places))throw new Error("Malformed nearby-place snapshot");return s}}}function GV({services:e,source:t}){var r;if(typeof(t==null?void 0:t.getMappedSites)!="function"||typeof(t==null?void 0:t.searchNearby)!="function")throw new TypeError("An installation source is required");const n=HV({services:e}),i={},o={state:n,services:e,parts:i,source:t};return i.model=AV(o),i.rendering=IV(o),i.ingestion=NV(o),i.viewport=DV(o),i.selection=OV(o),i.controls=BV(o),i.lifecycle=VV(o),Object.assign({},i.controls.methods,i.lifecycle.methods,(r=i.ingestion)==null?void 0:r.methods,{approximateSurfaceDistanceM:i.model.approximateSurfaceDistanceM,classifyGoogleMilitaryPlace:i.model.classifyGoogleMilitaryPlace,installationSourceLabel:i.model.installationSourceLabel,installationSurfaceHeightM:i.rendering.installationSurfaceHeightM,installationWithinViewport:i.model.installationWithinViewport,installationResponseSaturated:i.model.installationResponseSaturated,installationRetryDelayMs:i.viewport.installationRetryDelayMs})}function UV({surface:e,source:t}){const{groundFloor:n,anchors:i}=e;return GV({source:t,services:{render:Pt,context:Go,ground:n,anchors:i,picking:rn}})}const Om=Object.freeze({station:Object.freeze({label:"STATION",color:"#fff6e5",blurb:"Crewed stations and their visiting vehicles"}),nav:Object.freeze({label:"NAV",color:"#4fd8ff",blurb:"GNSS navigation — GPS, GLONASS, Galileo"}),geo:Object.freeze({label:"GEO",color:"#c89bff",blurb:"Geostationary belt — comms and weather, fixed over the equator"}),visual:Object.freeze({label:"VISUAL",color:"#9fb3c4",blurb:"Brightest naked-eye objects — CelesTrak visual group"}),comms:Object.freeze({label:"COMMS",color:"#54697f",blurb:"Broadband constellation shell — shown only in DENSE mode"})}),zV=Object.freeze(["station","nav","geo","visual","comms"]),jV=Object.freeze({stations:Object.freeze({klass:"station",subtype:null}),visual:Object.freeze({klass:"visual",subtype:null}),"gps-ops":Object.freeze({klass:"nav",subtype:"GPS"}),glonass:Object.freeze({klass:"nav",subtype:"GLONASS"}),galileo:Object.freeze({klass:"nav",subtype:"GALILEO"}),geo:Object.freeze({klass:"geo",subtype:null}),dense:Object.freeze({klass:"comms",subtype:"STARLINK"})}),qV=Object.freeze({klass:"visual",subtype:null}),WV=Object.freeze({klass:"station",subtype:"ISS"});function Bm(e,{isIss:t=!1}={}){return t?WV:jV[e]||qV}function KV(e){return Om[Bm(e).klass].color}function xh(e,{isIss:t=!1}={}){const{klass:n,subtype:i}=Bm(e,{isIss:t}),o=Om[n].label;return i?`${o} · ${i}`:o}function YV(e){const t=Object.create(null);for(const n of e||[]){const i=n&&typeof n=="object"?n:{group:n},{klass:o}=Bm(i.group,{isIss:i.isIss});t[o]=(t[o]||0)+1}return t}function XV(e){const t=[];for(const n of zV){const i=e==null?void 0:e[n];if(!(i>0))continue;const o=Om[n];t.push({klass:n,label:o.label,color:o.color,blurb:o.blurb,count:i})}return t}const _t=25544,Rn="satellites-iss",QV=Object.freeze({cohortLimit:1,collisionCapacity:1,moving:!0,solveIntervalMs:125}),pb=180,ZV=1e3,JV=1e3,eH=[{tag:"stations",path:"stations"},{tag:"visual",path:"visual"},{tag:"gps-ops",path:"gps-ops"},{tag:"glonass",path:"glo-ops"},{tag:"galileo",path:"galileo"},{tag:"geo",path:"geo"}],Ua="starlink",tH=300,gb=1500,nH=new Cesium.Cartesian3(-45e4,-45e4,35e4),iH=2e6,oH=4,fi=Cesium.Color.WHITE.withAlpha(.3),Xi=e=>Cesium.Color.fromCssColorString(KV(e)),Vs={iss:{pixelSize:12,color:Cesium.Color.fromCssColorString("#ff4444"),outlineColor:fi,outlineWidth:2},stations:{pixelSize:8,color:Xi("stations"),outlineColor:fi,outlineWidth:0},visual:{pixelSize:6,color:Xi("visual"),outlineColor:fi,outlineWidth:0},"gps-ops":{pixelSize:6,color:Xi("gps-ops"),outlineColor:fi,outlineWidth:0},glonass:{pixelSize:6,color:Xi("glonass"),outlineColor:fi,outlineWidth:0},galileo:{pixelSize:6,color:Xi("galileo"),outlineColor:fi,outlineWidth:0},geo:{pixelSize:5,color:Xi("geo"),outlineColor:fi,outlineWidth:0},dense:{pixelSize:3,color:Xi("dense").withAlpha(.9),outlineColor:fi,outlineWidth:0}},_b=2e3,rH=1e3,sH=1e3;function aH({state:e,services:t,parts:n,source:i}){const{isExplicitLayerStateOrigin:o}=t.layerState;function r(h,d){return h===_t?Vs.iss:Vs[d]||Vs.visual}function s(){var h;try{(h=e._rowControlsListener)==null||h.call(e)}catch(d){console.warn("[Data:Satellites] row-controls listener failed:",d)}}function a(){if(e._classTallyCache.counts&&e._classTallyCache.revision===e._catalogRevision)return e._classTallyCache.counts;const h=[];for(const[f,p]of e._catalog)h.push({group:p.group,isIss:f===_t});const d=YV(h);return e._classTallyCache={revision:e._catalogRevision,counts:d},d}function c(h,d){return!!h&&!!d}function l(h,d){return(d==="core"||d==="dense")&&d!==h}const u={id:"satellites",name:"Satellites",icon:"🛰️",source:"CelesTrak",updateInterval:0,refreshInterval:300*1e3,getDetectableObjects(h={}){var C;if(!e._pointCollection||!e._pointCollection.show)return[];const d=Math.max(1,e._points.size-e._denseIds.length),f=Number.isFinite(h.maxCount)?Math.max(1,Math.floor(h.maxCount)):d,p=Number.isFinite(h.seed)?Math.floor(h.seed):0,g=Math.max(1,Math.ceil(d/f)),_=p%g,m=[];let b=0;for(const[y,v]of e._points){if(e._denseIds.length>0&&((C=e._catalog.get(y))==null?void 0:C.group)==="dense")continue;const M=(b-_)%g===0;if(b++,!M||!v.position)continue;const w=y===e._trackedNorad;if(!w&&e._dockedCompanions.has(y))continue;const E=e._catalog.get(y);let k=e._detectionObjects.get(y);if(k||(k={sourceId:y,id:(E==null?void 0:E.name)||`SAT-${y}`,type:"SAT",klass:xh(E==null?void 0:E.group,{isIss:y===_t})},e._detectionObjects.set(y,k)),k.position=v.position,k.skipLabel=w,m.push(k),m.length>=f)break}return m},findByQuery(h){if(h==null||!e._catalog||e._catalog.size===0)return null;const d=String(h).trim();if(!d)return null;let f=null;if(/^\d+$/.test(d)&&e._catalog.has(Number(d)))f=Number(d);else{const _=d.toLowerCase();for(const[m,b]of e._catalog)if(b.name.toLowerCase().includes(_)){f=m;break}}if(f===null)return null;const p=e._catalog.get(f),g=n.orbits.propagatePosition(p.satrec,new Date);return g?{noradId:f,name:p.name.trim(),position:Cesium.Cartesian3.fromDegrees(g.longitude,g.latitude,g.altitude),latitude:g.latitude,longitude:g.longitude,altitudeM:g.altitude}:null},getAllPositions(h=300){var p;const d=[];if(!e._points||e._points.size===0)return d;const f=Number.isFinite(h)&&h>0?Math.floor(h):300;for(const[g,_]of e._points){if(d.length>=f)break;if(!_.position||e._denseIds.length>0&&((p=e._catalog.get(g))==null?void 0:p.group)==="dense")continue;const m=Cesium.Cartographic.fromCartesian(_.position);if(!m)continue;const b=e._catalog.get(g);d.push({id:g,label:b?b.name.trim():String(g),position:_.position,latitude:Cesium.Math.toDegrees(m.latitude),longitude:Cesium.Math.toDegrees(m.longitude),altitudeM:m.height})}return d},trackById(h,{origin:d="programmatic"}={}){const f=Number(h);return!Number.isFinite(f)||!e._viewer||!e._catalog.has(f)||!e._points.has(f)?!1:(n.tracking._cancelPendingTrackingRestore(),n.tracking._trackSatellite(f,{origin:d}),e._trackedNorad===f)},async resolveTrackingRestoreTarget(h,{signal:d=null,origin:f="share-restore"}={}){if(d!=null&&d.aborted)return{status:"cancelled",reason:String(d.reason||"aborted")};const p=n.tracking._normalizeTrackedNorad(h);if(p===null)return{status:"missing",reason:"invalid-target"};const g=e._lastTrackingRefreshOutcome,_=()=>e._catalog.has(p)&&e._points.has(p),m=()=>d!=null&&d.aborted?{status:"cancelled",reason:String(d.reason||"aborted")}:this.trackById(p,{origin:f})?{status:"found",refreshEpoch:g.epoch}:{status:"source-unavailable",reason:"target-not-renderable",refreshEpoch:g.epoch};if(_())return m();if(g.status!=="accepted"&&g.status!=="partial")return{status:"source-unavailable",reason:"CelesTrak catalog unavailable",refreshEpoch:g.epoch};if(e._params.catalog==="dense"){const b=await(e._denseLoadPromise||Promise.resolve({status:"source-unavailable"}));if(d!=null&&d.aborted)return{status:"cancelled",reason:String(d.reason||"aborted")};if(e._lastTrackingRefreshOutcome.epoch!==g.epoch)return{status:"superseded",reason:"newer-catalog-refresh"};if(_())return m();if((b==null?void 0:b.status)!=="ready")return{status:"source-unavailable",reason:(b==null?void 0:b.reason)||"dense catalog unavailable",refreshEpoch:g.epoch}}return g.status==="partial"?{status:"source-unavailable",reason:"partial CelesTrak catalog cannot prove absence",refreshEpoch:g.epoch,failedGroups:[...g.failedGroups]}:{status:"missing",reason:"target-absent-from-catalog",refreshEpoch:g.epoch}},stopTracking({origin:h="programmatic"}={}){return n.tracking._cancelPendingTrackingRestore(),n.tracking._clearTracking(!1,{origin:h}),!0},cancelPendingTrackingRestore(){n.tracking._cancelPendingTrackingRestore()},getTrackedInfo(){if(e._trackedNorad===null||!e._catalog.has(e._trackedNorad))return null;const h=e._catalog.get(e._trackedNorad),d=n.tracking._getTrackedFramePosition();return d?{noradId:e._trackedNorad,name:h.name.trim(),latitude:d.latitude,longitude:d.longitude,altitudeM:d.altitude}:null},setParams(h={},{origin:d="programmatic"}={}){o(d)&&!Object.hasOwn(h,"selectedSatTrackingId")&&n.tracking._cancelPendingTrackingRestore();const f=h.catalog;if(f!==void 0&&f!=="core"&&f!=="dense")return!1;const p=l(e._params.catalog,f);if(p&&(e._params.catalog=f),h.showPoints!==void 0&&(e._params.showPoints=h.showPoints!==!1,e._pointCollection&&(e._pointCollection.show=c(e._enabled,e._params.showPoints))),h.showOrbits!==void 0){e._params.showOrbits=h.showOrbits!==!1;for(const g of e._orbitPaths.values())g.primitive.show=c(e._enabled,e._params.showOrbits);n.labels._syncIssOverlay()}if(p&&f==="dense"?e._denseLoadPromise=n.catalog._loadDenseCatalog():f==="core"&&(p&&n.catalog._removeDenseCatalog(),e._denseStatus="idle",e._denseError=null),p&&console.log(`[Data:Satellites] Catalog mode: ${f}`),Object.hasOwn(h,"selectedSatTrackingId")){const g=n.tracking._normalizeTrackedNorad(h.selectedSatTrackingId);if(g===e._trackedNorad)e._pendingTrackingRestore=null;else if(g===null)n.tracking._cancelPendingTrackingRestore(),e._trackedNorad!==null&&n.tracking._clearTracking(!1,{origin:d});else{const _=++e._trackingIntentGeneration;e._pendingTrackingRestore={id:g,generation:_,origin:d},e._trackedNorad!==null&&n.tracking._clearTracking(!1,{origin:d}),n.tracking._applyPendingTrackingRestore()}}return!0},getParams(){return{catalog:e._params.catalog,showPoints:e._params.showPoints,showOrbits:e._params.showOrbits,selectedSatTrackingId:e._trackedNorad}},getRowControls(){if(!e._params.showPoints)return{chips:[],legend:[]};const h=e._denseStatus==="loading",d=e._denseStatus==="failed",f=e._params.catalog==="dense"&&e._denseStatus==="ready";let p="Add the full Starlink broadband shell (thousands of extra points)";return h?p="Loading the Starlink shell…":d?p=`Starlink ${e._denseError||"load failed"} — click to retry`:f&&(p="Showing the full Starlink shell — click for the core catalog only"),{chips:[{id:"catalog",label:h?"DENSE ···":d?"DENSE ✕":"DENSE",active:f,busy:h,disabled:h,state:h?"loading":d?"error":f?"active":"idle",title:p,params:{catalog:f?"core":"dense"}}],legend:XV(a())}},setRowControlsListener(h){e._rowControlsListener=typeof h=="function"?h:null},getStats(){return{count:e._count,lastUpdate:e._lastUpdate,stale:!1,status:e._lastError==="CelesTrak unreachable"?"unavailable":e._lastError?"degraded":"nominal",error:e._lastError}}};return{_pointStyleFor:r,_notifyRowControls:s,_classTally:a,satelliteVisualsVisible:c,satelliteCatalogModeChanged:l,methods:u}}var Et=Math.PI,ct=Et*2,ys=Et/180,lH=180/Et,cH=1440,uH=398600.8,Gt=6378.135,ei=60/Math.sqrt(Gt*Gt*Gt/uH),id=Gt*ei/60,dH=1/ei,fo=.001082616,hH=-253881e-11,fH=-165597e-11,mo=hH/fo,la=2/3,mH=1440/(2*Et);function pH(e,t){for(var n=[31,e%4===0?29:28,31,30,31,30,31,31,30,31,30,31],i=Math.floor(t),o=1,r=0;i>r+n[o-1]&&o<12;)r+=n[o-1],o+=1;var s=o,a=i-r,c=(t-i)*24,l=Math.floor(c);c=(c-l)*60;var u=Math.floor(c),h=(c-u)*60;return{mon:s,day:a,hr:l,minute:u,sec:h}}function bb(e,t,n,i,o,r){var s=arguments.length>6&&arguments[6]!==void 0?arguments[6]:0;return 367*e-Math.floor(7*(e+Math.floor((t+9)/12))*.25)+Math.floor(275*t/9)+n+17210135e-1+((s/6e4+r/60+o)/60+i)/24}function Vm(e,t,n,i,o,r){var s=arguments.length>6&&arguments[6]!==void 0?arguments[6]:0;if(e instanceof Date){var a=e;return bb(a.getUTCFullYear(),a.getUTCMonth()+1,a.getUTCDate(),a.getUTCHours(),a.getUTCMinutes(),a.getUTCSeconds(),a.getUTCMilliseconds())}return bb(e,t,n,i,o,r,s)}function pE(e,t){var n=e.e3,i=e.ee2,o=e.peo,r=e.pgho,s=e.pho,a=e.pinco,c=e.plo,l=e.se2,u=e.se3,h=e.sgh2,d=e.sgh3,f=e.sgh4,p=e.sh2,g=e.sh3,_=e.si2,m=e.si3,b=e.sl2,C=e.sl3,y=e.sl4,v=e.t,M=e.xgh2,w=e.xgh3,E=e.xgh4,k=e.xh2,T=e.xh3,I=e.xi2,R=e.xi3,S=e.xl2,A=e.xl3,L=e.xl4,F=e.zmol,P=e.zmos,O=t.init,D=t.opsmode,$=t.ep,x=t.inclp,N=t.nodep,G=t.argpp,W=t.mp,V,H,B,q,z,j,ne,ee,re,se,me,be,J,Z,ae,oe,le,Y,K,_e,he,Ce=119459e-10,ye=.01675,ve=.00015835218,pe=.0549;he=P+Ce*v,O==="y"&&(he=P),_e=he+2*ye*Math.sin(he),le=Math.sin(_e),se=.5*le*le-.25,me=-.5*le*Math.cos(_e);var te=l*se+u*me,de=_*se+m*me,U=b*se+C*me+y*le,Le=h*se+d*me+f*le,ke=p*se+g*me;he=F+ve*v,O==="y"&&(he=F),_e=he+2*pe*Math.sin(he),le=Math.sin(_e),se=.5*le*le-.25,me=-.5*le*Math.cos(_e);var Ne=i*se+n*me,Se=I*se+R*me,Ue=S*se+A*me+L*le,rt=M*se+w*me+E*le,Q=k*se+T*me;return be=te+Ne,ae=de+Se,oe=U+Ue,J=Le+rt,Z=ke+Q,O==="n"&&(be-=o,ae-=a,oe-=c,J-=r,Z-=s,x+=ae,$+=be,q=Math.sin(x),B=Math.cos(x),x>=.2?(Z/=q,J-=B*Z,G+=J,N+=Z,W+=oe):(j=Math.sin(N),z=Math.cos(N),V=q*j,H=q*z,ne=Z*z+ae*B*j,ee=-Z*j+ae*B*z,V+=ne,H+=ee,N%=ct,N<0&&D==="a"&&(N+=ct),Y=W+G+B*N,re=oe+J-ae*N*q,Y+=re,K=N,N=Math.atan2(V,H),N<0&&D==="a"&&(N+=ct),Math.abs(K-N)>Et&&(N.0034906585&&(ee=1),j>=.00826&&j<=.00924&&H>=.5&&(ee=2);var Oe=l*Vn*f,ut=u*Vn*(_+m),Xe=-Vn*h*(p+g-14-6*V),Be=d*Vn*(y+v-6),ot=-Vn*u*(b+C);(q<.052359877||q>Et-.052359877)&&(ot=0),c!==0&&(ot/=c);var Kt=Be-t*ot;_e=Oe+i*bn*a,he=ut+o*bn*(P+O),Ce=Xe-bn*r*(L+F-14-6*V);var it=s*bn*(x+N-6),Hn=-bn*o*(D+$);(q<.052359877||q>Et-.052359877)&&(Hn=0),ve=Kt+it,ye=ot,c!==0&&(ve-=t/c*Hn,ye+=Hn/c);var Cn=0,ss=(E+w*hi)%ct;if(H+=_e*M,q+=he*M,B+=ve*M,ne+=ye*M,z+=Ce*M,ee!==0){if(ht=Math.pow(j/ei,la),ee===2){bt=t*t;var gu=H;H=G;var _u=V;V=W,st=H*V,Ae=-.306-(H-.64)*.44,H<=.65?(xe=3.616-13.247*H+16.29*V,Ee=-19.302+117.39*H-228.419*V+156.591*st,Ie=-18.9068+109.7927*H-214.6334*V+146.5816*st,Pe=-41.122+242.694*H-471.094*V+313.953*st,Fe=-146.407+841.88*H-1629.014*V+1083.435*st,De=-532.114+3017.977*H-5740.032*V+3708.276*st):(xe=-72.099+331.819*H-508.738*V+266.724*st,Ee=-346.844+1582.851*H-2415.925*V+1246.113*st,Ie=-342.585+1554.908*H-2366.899*V+1215.972*st,Pe=-1052.797+4758.686*H-7193.992*V+3651.957*st,Fe=-3581.69+16178.11*H-24462.77*V+12422.52*st,H>.715?De=-5149.66+29936.92*H-54087.36*V+31324.56*st:De=1464.74-4664.75*H+3763.64*V),H<.7?(ze=-919.2277+4988.61*H-9064.77*V+5542.21*st,Qe=-822.71072+4568.6173*H-8491.4146*V+5337.524*st,Ze=-853.666+4690.25*H-8624.77*V+5341.4*st):(ze=-37995.78+161616.52*H-229838.2*V+109377.94*st,Qe=-51752.104+218913.95*H-309468.16*V+146349.42*st,Ze=-40023.88+170470.89*H-242699.48*V+115605.82*st),nt=c*c,Se=.75*(1+2*t+bt),Ue=1.5*nt,Q=1.875*c*(1-2*t-3*bt),X=-1.875*c*(1+2*t-3*bt),ce=35*nt*Se,ue=39.375*nt*nt,fe=9.84375*c*(nt*(1-2*t-5*bt)+.33333333*(-2+4*t+6*bt)),Me=c*(4.92187512*nt*(-2-4*t+10*bt)+6.56250012*(1+2*t-3*bt)),Te=29.53125*c*(2-8*t+bt*(-12+8*t+10*bt)),Re=29.53125*c*(-2-8*t+bt*(12+8*t-10*bt)),Vt=j*j,_n=ht*ht,je=3*Vt*_n,$e=je*rs,se=$e*Se*Ae,me=$e*Ue*xe,je*=ht,$e=je*jo,be=$e*Q*Ee,J=$e*X*Ie,je*=ht,$e=2*je*zo,Z=$e*ce*Pe,ae=$e*ue*Fe,je*=ht,$e=je*qo,oe=$e*fe*De,le=$e*Me*Ze,$e=2*je*di,Y=$e*Te*Qe,K=$e*Re*ze,Le=(k+R+R-(ss+ss))%ct,U=T+Ce+2*(S+ye-hi)-I,H=gu,V=_u}ee===1&&(we=1+V*(-2.5+.8125*V),Ee=1+2*V,ge=1+V*(-6+6.60937*V),Se=.75*(1+t)*(1+t),rt=.9375*c*c*(1+3*t)-.75*(1+t),ie=1+t,ie*=1.875*ie*ie,pe=3*j*j*ht*ht,te=2*pe*Se*we*Bn,de=3*pe*ie*ge*os*ht,pe=pe*rt*Ee*Wt*ht,Le=(k+R+n-ss)%ct,U=T+A+Ce+ve+ye-(I+hi)),ke=Le,Ne=I,re=0,j=I+Cn}return{em:H,argpm:B,inclm:q,mm:z,nm:j,nodem:ne,irez:ee,atime:re,d2201:se,d2211:me,d3210:be,d3222:J,d4410:Z,d4422:ae,d5220:oe,d5232:le,d5421:Y,d5433:K,dedt:_e,didt:he,dmdt:Ce,dndt:Cn,dnodt:ye,domdt:ve,del1:pe,del2:te,del3:de,xfact:U,xlamo:Le,xli:ke,xni:Ne}}function Cb(e){var t=(e-2451545)/36525,n=-62e-7*t*t*t+.093104*t*t+(876600*3600+8640184812866e-6)*t+67310.54841;return n=n*ys/240%ct,n<0&&(n+=ct),n}function po(e,t,n,i,o,r,s){return e instanceof Date?Cb(Vm(e)):Cb(e)}function bH(e){var t=e.ecco,n=e.epoch,i=e.inclo,o=e.opsmode,r=e.no,s=t*t,a=1-s,c=Math.sqrt(a),l=Math.cos(i),u=l*l,h=Math.pow(ei/r,la),d=.75*fo*(3*u-1)/(c*a),f=d/(h*h),p=h*(1-f*f-f*(1/3+134*f*f/81));f=d/(p*p),r/=1+f;var g=Math.pow(ei/r,la),_=Math.sin(i),m=g*a,b=1-5*u,C=-b-u-u,y=1/g,v=m*m,M=g*(1-t),w="n",E;if(o==="a"){var k=n-7305,T=Math.floor(k+1e-8),I=k-T,R=.017202791694070362,S=1.7321343856509375,A=5075514194322695e-30,L=R+ct;E=(S+R*T+L*I+k*k*A)%ct,E<0&&(E+=ct)}else E=po(n+24332815e-1);return{no:r,method:w,ainv:y,ao:g,con41:C,con42:b,cosio:l,cosio2:u,eccsq:s,omeosq:a,posq:v,rp:M,rteosq:c,sinio:_,gsto:E}}function CH(e){var t=e.irez,n=e.d2201,i=e.d2211,o=e.d3210,r=e.d3222,s=e.d4410,a=e.d4422,c=e.d5220,l=e.d5232,u=e.d5421,h=e.d5433,d=e.dedt,f=e.del1,p=e.del2,g=e.del3,_=e.didt,m=e.dmdt,b=e.dnodt,C=e.domdt,y=e.argpo,v=e.argpdot,M=e.t,w=e.tc,E=e.gsto,k=e.xfact,T=e.xlamo,I=e.no,R=e.atime,S=e.em,A=e.argpm,L=e.inclm,F=e.xli,P=e.mm,O=e.xni,D=e.nodem,$=e.nm,x=.13130908,N=2.8843198,G=.37448087,W=5.7686396,V=.95240898,H=1.8014998,B=1.050833,q=4.4108898,z=.0043752690880113,j=720,ne=-720,ee=259200,re,se,me,be,J,Z,ae,oe,le=0,Y=0,K=(E+w*z)%ct;if(S+=d*M,L+=_*M,A+=C*M,D+=b*M,P+=m*M,t!==0){(R===0||M*R<=0||Math.abs(M)0?re=j:re=ne;for(var _e=381;_e===381;)t!==2?(ae=f*Math.sin(F-x)+p*Math.sin(2*(F-N))+g*Math.sin(3*(F-G)),J=O+k,Z=f*Math.cos(F-x)+2*p*Math.cos(2*(F-N))+3*g*Math.cos(3*(F-G)),Z*=J):(oe=y+v*R,me=oe+oe,se=F+F,ae=n*Math.sin(me+F-W)+i*Math.sin(F-W)+o*Math.sin(oe+F-V)+r*Math.sin(-oe+F-V)+s*Math.sin(me+se-H)+a*Math.sin(se-H)+c*Math.sin(oe+F-B)+l*Math.sin(-oe+F-B)+u*Math.sin(oe+se-q)+h*Math.sin(-oe+se-q),J=O+k,Z=n*Math.cos(me+F-W)+i*Math.cos(F-W)+o*Math.cos(oe+F-V)+r*Math.cos(-oe+F-V)+c*Math.cos(oe+F-B)+l*Math.cos(-oe+F-B)+2*(s*Math.cos(me+se-H)+a*Math.cos(se-H)+u*Math.cos(oe+se-q)+h*Math.cos(-oe+se-q)),Z*=J),Math.abs(M-R)>=j?_e=381:(Y=M-R,_e=0),_e===381&&(F+=J*re+ae*ee,O+=ae*re+Z*ee,R+=re);$=O+ae*Y+Z*Y*Y*.5,be=F+J*Y+ae*Y*Y*.5,t!==1?(P=be-2*D+2*K,le=$-I):(P=be-D-A+K,le=$-I),$=I+le}return{atime:R,em:S,argpm:A,inclm:L,xli:F,mm:P,xni:O,nodem:D,dndt:le,nm:$}}var _i;(function(e){e[e.None=0]="None",e[e.MeanEccentricityOutOfRange=1]="MeanEccentricityOutOfRange",e[e.MeanMotionBelowZero=2]="MeanMotionBelowZero",e[e.PerturbedEccentricityOutOfRange=3]="PerturbedEccentricityOutOfRange",e[e.SemiLatusRectumBelowZero=4]="SemiLatusRectumBelowZero",e[e.Decayed=6]="Decayed"})(_i||(_i={}));function gE(e,t){var n,i,o,r,s,a,c,l,u,h,d,f,p,g,_,m,b,C,y,v,M,w,E,k,T,I,R,S=15e-13;e.t=t,e.error=_i.None;var A=e.mo+e.mdot*e.t,L=e.argpo+e.argpdot*e.t,F=e.nodeo+e.nodedot*e.t;u=L,M=A;var P=e.t*e.t;if(E=F+e.nodecf*P,b=1-e.cc1*e.t,C=e.bstar*e.cc4*e.t,y=e.t2cof*P,e.isimp!==1){c=e.omgcof*e.t;var O=1+e.eta*Math.cos(A);a=e.xmcof*(O*O*O-e.delmo),m=c+a,M=A+m,u=L-m,f=P*e.t,p=f*e.t,b=b-e.d2*P-e.d3*f-e.d4*p,C+=e.bstar*e.cc5*(Math.sin(M)-e.sinmao),y=y+e.t3cof*f+p*(e.t4cof+e.t*e.t5cof)}w=e.no;var D=e.ecco;if(v=e.inclo,e.method==="d"){g=e.t;var $={irez:e.irez,d2201:e.d2201,d2211:e.d2211,d3210:e.d3210,d3222:e.d3222,d4410:e.d4410,d4422:e.d4422,d5220:e.d5220,d5232:e.d5232,d5421:e.d5421,d5433:e.d5433,dedt:e.dedt,del1:e.del1,del2:e.del2,del3:e.del3,didt:e.didt,dmdt:e.dmdt,dnodt:e.dnodt,domdt:e.domdt,argpo:e.argpo,argpdot:e.argpdot,t:e.t,tc:g,gsto:e.gsto,xfact:e.xfact,xlamo:e.xlamo,no:e.no,atime:e.atime,em:D,argpm:u,inclm:v,xli:e.xli,mm:M,xni:e.xni,nodem:E,nm:w},x=CH($);D=x.em,u=x.argpm,v=x.inclm,M=x.mm,E=x.nodem,w=x.nm}if(w<=0)return e.error=_i.MeanMotionBelowZero,null;var N=Math.pow(ei/w,la)*b*b;if(w=ei/Math.pow(N,1.5),D-=C,D>=1||D<-.001)return e.error=_i.MeanEccentricityOutOfRange,null;D<1e-6&&(D=1e-6),M+=e.no*y,T=M+u+E,E%=ct,u%=ct,T%=ct,M=(T-u-E)%ct;var G={am:N,em:D,im:v,Om:E,om:u,mm:M,nm:w},W=Math.sin(v),V=Math.cos(v),H=D;if(k=v,h=u,R=E,I=M,r=W,o=V,e.method==="d"){var B={inclo:e.inclo,init:"n",ep:H,inclp:k,nodep:R,argpp:h,mp:I,opsmode:e.operationmode},q=pE(e,B);if(H=q.ep,R=q.nodep,h=q.argpp,I=q.mp,k=q.inclp,k<0&&(k=-k,R+=Et,h-=Et),H<0||H>1)return e.error=_i.PerturbedEccentricityOutOfRange,null}e.method==="d"&&(r=Math.sin(k),o=Math.cos(k),e.aycof=-.5*mo*r,Math.abs(o+1)>15e-13?e.xlcof=-.25*mo*r*(3+5*o)/(1+o):e.xlcof=-.25*mo*r*(3+5*o)/S);var z=H*Math.cos(h);m=1/(N*(1-H*H));var j=H*Math.sin(h)+m*e.aycof,ne=I+h+R+m*e.xlcof*z,ee=(ne-R)%ct;l=ee,_=9999.9;for(var re=1;Math.abs(_)>=1e-12&&re<=10;)i=Math.sin(l),n=Math.cos(l),_=1-n*z-i*j,_=(ee-j*n+z*i-l)/_,Math.abs(_)>=.95&&(_>0?_=.95:_=-.95),l+=_,re+=1;var se=z*n+j*i,me=z*i-j*n,be=z*z+j*j,J=N*(1-be);if(J<0)return e.error=_i.SemiLatusRectumBelowZero,null;var Z=N*(1-se),ae=Math.sqrt(N)*me/Z,oe=Math.sqrt(J)/Z,le=Math.sqrt(1-be);m=me/(1+le);var Y=N/Z*(i-j-z*m),K=N/Z*(n-z+j*m);d=Math.atan2(Y,K);var _e=(K+K)*Y,he=1-2*Y*Y;m=1/J;var Ce=.5*fo*m,ye=Ce*m;e.method==="d"&&(s=o*o,e.con41=3*s-1,e.x1mth2=1-s,e.x7thm1=7*s-1);var ve=Z*(1-1.5*ye*le*e.con41)+.5*Ce*e.x1mth2*he;if(ve<1)return e.error=_i.Decayed,null;d-=.25*ye*e.x7thm1*_e;var pe=R+1.5*ye*o*_e,te=k+1.5*ye*o*r*he,de=ae-w*Ce*e.x1mth2*_e/ei,U=oe+w*Ce*(e.x1mth2*he+1.5*e.con41)/ei,Le=Math.sin(d),ke=Math.cos(d),Ne=Math.sin(pe),Se=Math.cos(pe),Ue=Math.sin(te),rt=Math.cos(te),Q=-Ne*rt,X=Se*rt,ie=Q*Le+Se*ke,ce=X*Le+Ne*ke,ue=Ue*Le,fe=Q*ke-Se*Le,Me=X*ke-Ne*Le,Te=Ue*ke,Re={x:ve*ie*Gt,y:ve*ce*Gt,z:ve*ue*Gt},we={x:(de*ie+U*fe)*id,y:(de*ce+U*Me)*id,z:(de*ue+U*Te)*id};return{position:Re,velocity:we,meanElements:G}}function yH(e,t){var n=t.opsmode,i=t.epoch,o=t.xbstar,r=t.xecco,s=t.xargpo,a=t.xinclo,c=t.xmo,l=t.xno,u=t.xnodeo,h,d,f,p,g,_,m,b,C,y,v,M,w,E,k,T,I,R,S,A,L,F,P,O,D,$,x,N,G,W,V,H,B,q,z,j,ne,ee,re,se,me,be,J,Z,ae,oe,le,Y,K,_e,he,Ce,ye,ve,pe,te,de=15e-13,U=e;U.isimp=0,U.method="n",U.aycof=0,U.con41=0,U.cc1=0,U.cc4=0,U.cc5=0,U.d2=0,U.d3=0,U.d4=0,U.delmo=0,U.eta=0,U.argpdot=0,U.omgcof=0,U.sinmao=0,U.t=0,U.t2cof=0,U.t3cof=0,U.t4cof=0,U.t5cof=0,U.x1mth2=0,U.x7thm1=0,U.mdot=0,U.nodedot=0,U.xlcof=0,U.xmcof=0,U.nodecf=0,U.irez=0,U.d2201=0,U.d2211=0,U.d3210=0,U.d3222=0,U.d4410=0,U.d4422=0,U.d5220=0,U.d5232=0,U.d5421=0,U.d5433=0,U.dedt=0,U.del1=0,U.del2=0,U.del3=0,U.didt=0,U.dmdt=0,U.dnodt=0,U.domdt=0,U.e3=0,U.ee2=0,U.peo=0,U.pgho=0,U.pho=0,U.pinco=0,U.plo=0,U.se2=0,U.se3=0,U.sgh2=0,U.sgh3=0,U.sgh4=0,U.sh2=0,U.sh3=0,U.si2=0,U.si3=0,U.sl2=0,U.sl3=0,U.sl4=0,U.gsto=0,U.xfact=0,U.xgh2=0,U.xgh3=0,U.xgh4=0,U.xh2=0,U.xh3=0,U.xi2=0,U.xi3=0,U.xl2=0,U.xl3=0,U.xl4=0,U.xlamo=0,U.zmol=0,U.zmos=0,U.atime=0,U.xli=0,U.xni=0,U.bstar=o,U.ecco=r,U.argpo=s,U.inclo=a,U.mo=c,U.no=l,U.nodeo=u,U.operationmode=n;var Le=78/Gt+1,ke=42/Gt,Ne=ke*ke*ke*ke;U.init="y",U.t=0;var Se={ecco:U.ecco,epoch:i,inclo:U.inclo,no:U.no,method:U.method,opsmode:U.operationmode},Ue=bH(Se),rt=Ue.ao,Q=Ue.con42,X=Ue.cosio,ie=Ue.cosio2,ce=Ue.eccsq,ue=Ue.omeosq,fe=Ue.posq,Me=Ue.rp,Te=Ue.rteosq,Re=Ue.sinio;if(U.no=Ue.no,U.con41=Ue.con41,U.gsto=Ue.gsto,U.a=Math.pow(U.no*dH,-2/3),U.alta=U.a*(1+U.ecco)-1,U.altp=U.a*(1-U.ecco)-1,U.error=0,ue>=0||U.no>=0){if(U.isimp=0,Me<220/Gt+1&&(U.isimp=1),x=Le,L=Ne,R=(Me-1)*Gt,R<156){x=R-78,R<98&&(x=20);var we=(120-x)/Gt;L=we*we*we*we,x=x/Gt+1}S=1/fe,oe=1/(rt-x),U.eta=rt*U.ecco*oe,M=U.eta*U.eta,v=U.ecco*U.eta,A=Math.abs(1-M),_=L*Math.pow(oe,4),m=_/Math.pow(A,3.5),p=m*U.no*(rt*(1+1.5*M+v*(4+M))+.375*fo*oe/A*U.con41*(8+3*M*(8+M))),U.cc1=U.bstar*p,g=0,U.ecco>1e-4&&(g=-2*_*oe*mo*U.no*Re/U.ecco),U.x1mth2=1-ie,U.cc4=2*U.no*m*rt*ue*(U.eta*(2+.5*M)+U.ecco*(.5+2*M)-fo*oe/(rt*A)*(-3*U.con41*(1-2*v+M*(1.5-.5*v))+.75*U.x1mth2*(2*M-v*(1+M))*Math.cos(2*U.argpo))),U.cc5=2*m*rt*ue*(1+2.75*(M+v)+v*M),b=ie*ie,J=1.5*fo*S*U.no,Z=.5*J*fo*S,ae=-.46875*fH*S*S*U.no,U.mdot=U.no+.5*J*Te*U.con41+.0625*Z*Te*(13-78*ie+137*b),U.argpdot=-.5*J*Q+.0625*Z*(7-114*ie+395*b)+ae*(3-36*ie+49*b),Y=-J*X,U.nodedot=Y+(.5*Z*(4-19*ie)+2*ae*(3-7*ie))*X,le=U.argpdot+U.nodedot,U.omgcof=U.bstar*g*Math.cos(U.argpo),U.xmcof=0,U.ecco>1e-4&&(U.xmcof=-la*_*U.bstar/v),U.nodecf=3.5*ue*Y*U.cc1,U.t2cof=1.5*U.cc1,Math.abs(X+1)>15e-13?U.xlcof=-.25*mo*Re*(3+5*X)/(1+X):U.xlcof=-.25*mo*Re*(3+5*X)/de,U.aycof=-.5*mo*Re;var Ae=1+U.eta*Math.cos(U.mo);if(U.delmo=Ae*Ae*Ae,U.sinmao=Math.sin(U.mo),U.x7thm1=7*ie-1,2*Et/U.no>=225){U.method="d",U.isimp=1,me=0,k=U.inclo;var xe={epoch:i,ep:U.ecco,argpp:U.argpo,tc:me,inclp:U.inclo,nodep:U.nodeo,np:U.no,e3:U.e3,ee2:U.ee2,peo:U.peo,pgho:U.pgho,pho:U.pho,pinco:U.pinco,plo:U.plo,se2:U.se2,se3:U.se3,sgh2:U.sgh2,sgh3:U.sgh3,sgh4:U.sgh4,sh2:U.sh2,sh3:U.sh3,si2:U.si2,si3:U.si3,sl2:U.sl2,sl3:U.sl3,sl4:U.sl4,xgh2:U.xgh2,xgh3:U.xgh3,xgh4:U.xgh4,xh2:U.xh2,xh3:U.xh3,xi2:U.xi2,xi3:U.xi3,xl2:U.xl2,xl3:U.xl3,xl4:U.xl4,zmol:U.zmol,zmos:U.zmos},ge=gH(xe);U.e3=ge.e3,U.ee2=ge.ee2,U.peo=ge.peo,U.pgho=ge.pgho,U.pho=ge.pho,U.pinco=ge.pinco,U.plo=ge.plo,U.se2=ge.se2,U.se3=ge.se3,U.sgh2=ge.sgh2,U.sgh3=ge.sgh3,U.sgh4=ge.sgh4,U.sh2=ge.sh2,U.sh3=ge.sh3,U.si2=ge.si2,U.si3=ge.si3,U.sl2=ge.sl2,U.sl3=ge.sl3,U.sl4=ge.sl4,d=ge.sinim,h=ge.cosim,C=ge.em,y=ge.emsq,F=ge.s1,P=ge.s2,O=ge.s3,D=ge.s4,$=ge.s5,N=ge.ss1,G=ge.ss2,W=ge.ss3,V=ge.ss4,H=ge.ss5,B=ge.sz1,q=ge.sz3,z=ge.sz11,j=ge.sz13,ne=ge.sz21,ee=ge.sz23,re=ge.sz31,se=ge.sz33,U.xgh2=ge.xgh2,U.xgh3=ge.xgh3,U.xgh4=ge.xgh4,U.xh2=ge.xh2,U.xh3=ge.xh3,U.xi2=ge.xi2,U.xi3=ge.xi3,U.xl2=ge.xl2,U.xl3=ge.xl3,U.xl4=ge.xl4,U.zmol=ge.zmol,U.zmos=ge.zmos,I=ge.nm,K=ge.z1,_e=ge.z3,he=ge.z11,Ce=ge.z13,ye=ge.z21,ve=ge.z23,pe=ge.z31,te=ge.z33;var Ee={inclo:k,init:U.init,ep:U.ecco,inclp:U.inclo,nodep:U.nodeo,argpp:U.argpo,mp:U.mo,opsmode:U.operationmode},Ie=pE(U,Ee);U.ecco=Ie.ep,U.inclo=Ie.inclp,U.nodeo=Ie.nodep,U.argpo=Ie.argpp,U.mo=Ie.mp,w=0,E=0,T=0;var Pe={cosim:h,emsq:y,argpo:U.argpo,s1:F,s2:P,s3:O,s4:D,s5:$,sinim:d,ss1:N,ss2:G,ss3:W,ss4:V,ss5:H,sz1:B,sz3:q,sz11:z,sz13:j,sz21:ne,sz23:ee,sz31:re,sz33:se,t:U.t,tc:me,gsto:U.gsto,mo:U.mo,mdot:U.mdot,no:U.no,nodeo:U.nodeo,nodedot:U.nodedot,xpidot:le,z1:K,z3:_e,z11:he,z13:Ce,z21:ye,z23:ve,z31:pe,z33:te,ecco:U.ecco,eccsq:ce,em:C,argpm:w,inclm:k,mm:T,nm:I,nodem:E,irez:U.irez,atime:U.atime,d2201:U.d2201,d2211:U.d2211,d3210:U.d3210,d3222:U.d3222,d4410:U.d4410,d4422:U.d4422,d5220:U.d5220,d5232:U.d5232,d5421:U.d5421,d5433:U.d5433,dedt:U.dedt,didt:U.didt,dmdt:U.dmdt,dnodt:U.dnodt,domdt:U.domdt,del1:U.del1,del2:U.del2,del3:U.del3,xfact:U.xfact,xlamo:U.xlamo,xli:U.xli,xni:U.xni},Fe=_H(Pe);U.irez=Fe.irez,U.atime=Fe.atime,U.d2201=Fe.d2201,U.d2211=Fe.d2211,U.d3210=Fe.d3210,U.d3222=Fe.d3222,U.d4410=Fe.d4410,U.d4422=Fe.d4422,U.d5220=Fe.d5220,U.d5232=Fe.d5232,U.d5421=Fe.d5421,U.d5433=Fe.d5433,U.dedt=Fe.dedt,U.didt=Fe.didt,U.dmdt=Fe.dmdt,U.dnodt=Fe.dnodt,U.domdt=Fe.domdt,U.del1=Fe.del1,U.del2=Fe.del2,U.del3=Fe.del3,U.xfact=Fe.xfact,U.xlamo=Fe.xlamo,U.xli=Fe.xli,U.xni=Fe.xni}U.isimp!==1&&(f=U.cc1*U.cc1,U.d2=4*rt*oe*f,be=U.d2*oe*U.cc1/3,U.d3=(17*rt+x)*be,U.d4=.5*be*rt*oe*(221*rt+31*x)*U.cc1,U.t3cof=U.d2+2*f,U.t4cof=.25*(3*U.d3+U.cc1*(12*U.d2+10*f)),U.t5cof=.2*(3*U.d4+12*U.cc1*U.d3+6*U.d2*U.d2+15*f*(2*U.d2+f)))}gE(U,0),U.init="n"}function Hm(e,t){var n="i",i=0,o=e.substring(2,7),r=parseInt(e.substring(18,20),10),s=parseFloat(e.substring(20,32)),a=parseFloat(e.substring(33,43)),c=parseFloat("".concat(e.substring(44,45),".").concat(e.substring(45,50),"E").concat(e.substring(50,52))),l=parseFloat("".concat(e.substring(53,54),".").concat(e.substring(54,59),"E").concat(e.substring(59,61))),u=parseFloat(t.substring(8,16))*ys,h=parseFloat(t.substring(17,25))*ys,d=parseFloat(".".concat(t.substring(26,33).replace(/\s/g,"0"))),f=parseFloat(t.substring(34,42))*ys,p=parseFloat(t.substring(43,51))*ys,g=parseFloat(t.substring(52,63))/mH,_=r<57?r+2e3:r+1900,m=pH(_,s),b=m.mon,C=m.day,y=m.hr,v=m.minute,M=m.sec,w=Vm(_,b,C,y,v,M),E={error:i,satnum:o,epochyr:r,epochdays:s,ndot:a,nddot:c,bstar:l,inclo:u,nodeo:h,ecco:d,argpo:f,mo:p,no:g,jdsatepoch:w};return yH(E,{opsmode:n,satn:E.satnum,epoch:E.jdsatepoch-24332815e-1,xbstar:E.bstar,xecco:E.ecco,xargpo:E.argpo,xinclo:E.inclo,xmo:E.mo,xno:E.no,xnodeo:E.nodeo}),E}function Fh(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;iEt/2)throw new RangeError("Latitude radians must be in range [-pi/2; pi/2].");return _E(e)}function vb(e){if(e<-Et||e>Et)throw new RangeError("Longitude radians must be in range [-pi; pi].");return _E(e)}function vH(e){var t=e.longitude,n=e.latitude,i=e.height,o=6378.137,r=6356.7523142,s=(o-r)/o,a=2*s-s*s,c=o/Math.sqrt(1-a*(Math.sin(n)*Math.sin(n))),l=(c+i)*Math.cos(n)*Math.cos(t),u=(c+i)*Math.cos(n)*Math.sin(t),h=(c*(1-a)+i)*Math.sin(n);return{x:l,y:u,z:h}}function Mb(e,t){for(var n=6378.137,i=6356.7523142,o=Math.sqrt(e.x*e.x+e.y*e.y),r=(n-i)/n,s=2*r-r*r,a=Math.atan2(e.y,e.x)-t;a<-Et;)a+=ct;for(;a>Et;)a-=ct;for(var c=20,l=0,u=Math.atan2(e.z,Math.sqrt(e.x*e.x+e.y*e.y)),h;l++=e._denseIds.length&&(e._denseCursor=0);const d=e._denseIds[e._denseCursor++];if(d===e._trackedNorad)continue;const f=e._catalog.get(d),p=e._points.get(d);if(!f||!p)continue;const g=n.orbits.propagatePosition(f.satrec,u);g&&(p.position=Cesium.Cartesian3.fromDegrees(g.longitude,g.latitude,g.altitude))}}async function s({signal:l=null}={}){var f;if(!e._viewer||!e._pointCollection)return{status:"source-unavailable",reason:"layer-unavailable"};(f=e._denseLoadController)==null||f.abort();const u=new AbortController;e._denseLoadController=u;const h=l?AbortSignal.any([l,u.signal]):u.signal,d=++e._denseLoadToken;e._denseStatus="loading",e._denseError=null,n.controls._notifyRowControls();try{h.throwIfAborted();const p=await i.readGroup(Ua,{signal:h});if(!p.ok)return console.warn(`[Data:Satellites] Dense group '${Ua}' fetch failed (${p.status})`),a(d,`feed unavailable (${p.status})`),{status:"source-unavailable",reason:`feed unavailable (${p.status})`};const g=p.text;if(h.throwIfAborted(),d!==e._denseLoadToken||e._params.catalog!=="dense")return{status:"superseded",reason:"dense-load-superseded"};const _=n.orbits.parseTLE(g),m=Vs.dense,b=new Date;let C=0;for(let y=0;y<_.length;y+=gb){if(h.throwIfAborted(),d!==e._denseLoadToken||e._params.catalog!=="dense"||!e._pointCollection)return{status:"superseded",reason:"dense-load-superseded"};const v=Math.min(y+gb,_.length);for(let M=y;MsetTimeout(M,0)),h.throwIfAborted()}return C===0?(console.warn(`[Data:Satellites] Dense group '${Ua}' returned no usable satellites`),a(d,"feed returned no satellites"),{status:"source-unavailable",reason:"feed returned no satellites"}):(e._count=e._points.size,e._catalogRevision++,e._denseStatus="ready",console.log(`[Data:Satellites] Dense catalog: +${C} ${Ua} (points only)`),n.controls._notifyRowControls(),n.tracking._applyPendingTrackingRestore(),{status:"ready",added:C})}catch(p){return h.aborted||(p==null?void 0:p.name)==="AbortError"?{status:"cancelled",reason:String(h.reason||"aborted")}:(console.warn("[Data:Satellites] Dense catalog load failed:",p),a(d,"feed unreachable"),{status:"source-unavailable",reason:"feed unreachable"})}finally{e._denseLoadController===u&&(e._denseLoadController=null)}}function a(l,u){l===e._denseLoadToken&&(e._params.catalog="core",c(),e._denseStatus="failed",e._denseError=u,n.controls._notifyRowControls())}function c(){var l,u;(l=e._denseLoadController)==null||l.abort(),e._denseLoadController=null,e._denseLoadToken++,e._trackedNorad!==null&&((u=e._catalog.get(e._trackedNorad))==null?void 0:u.group)==="dense"&&n.tracking._clearTracking();for(const h of e._denseIds){const d=e._points.get(h);d&&e._pointCollection&&e._pointCollection.remove(d),e._points.delete(h),e._catalog.delete(h)}e._denseIds=[],e._denseCursor=0,e._count=e._points.size,e._catalogRevision++}return{_abortActiveUpdates:o,_propagateDenseChunk:r,_loadDenseCatalog:s,_denseLoadFailed:a,_removeDenseCatalog:c}}function AH({state:e,services:t,parts:n,source:i}){function o(l){return{id:String(_t),position:l,variant:"label",title:"ISS",accent:"#ff4444",priority:1e3,collisionGroup:"ambient-label",paintLane:"ambient-label",interactive:!1,distanceScale:{near:1e6,nearValue:1,far:3e7,farValue:.4},gapPx:14,verticalOnly:!0,placement:"above",edgeFade:"keyhole",horizonCull:!0,terrainOcclusion:!1}}function r(){var l;return((l=e._points.get(_t))==null?void 0:l.position)||null}function s(l){const u=e._trackedNorad===null?null:n.tracking._trackedDisplayCached();if(!u)return e._dockedCompanions.size===0?!1:(e._dockedCompanions=new Set,!0);if(l-e._lastDockedScanMsh||(p.add(g),f++,e._dockedCompanions.has(g)||(d=!0))}return f!==e._dockedCompanions.size&&(d=!0),d&&(e._dockedCompanions=p),d}function a(){var u,h;const l=[];for(const d of e._dockedCompanions)l.push(((h=(u=e._catalog.get(d))==null?void 0:u.name)==null?void 0:h.trim())||`SAT-${d}`);return l.sort()}function c(){if(!(e._enabled&&e._params.showOrbits&&e._trackedNorad!==_t&&!e._dockedCompanions.has(_t)&&e._catalog.has(_t)&&r())){e._overlayHost.clearSource(Rn),e._overlayHost.setVisible(Rn,!1);return}e._overlayHost.setEntries(Rn,[o(r)],QV),e._overlayHost.setVisible(Rn,!0)}return{createIssOverlayEntry:o,_issDisplayCached:r,_refreshDockedCompanions:s,_dockedCompanionNames:a,_syncIssOverlay:c}}const wb=180/Math.PI,Eb=Math.PI/180;function Tb(e,t,n,i){const o=new Date(t),r=Fh(e,o),s=r&&r.position;if(!s||typeof s=="boolean")return null;const a=MH(s,po(o)),c=TH({latitude:n*Eb,longitude:i*Eb,height:0},a);return{elevDeg:c.elevation*wb,azDeg:(c.azimuth*wb%360+360)%360}}function IH({satrec:e,latDeg:t,lonDeg:n,fromMs:i,minElevDeg:o=10,horizonHours:r=24,coarseStepSec:s=30,fineStepSec:a=5}){const c=C=>{var y;return((y=Tb(e,C,t,n))==null?void 0:y.elevDeg)??-90},l=i+r*36e5,u=s*1e3,h=a*1e3;let d=null;for(let C=i;C<=l;C+=u)if(c(C)>=o){d=C;break}if(d==null)return null;let f=d;for(;f-h>i&&c(f-h)>=o;)f-=h;let p=-90,g=f,_=f;for(;_<=l;){const C=c(_);if(Cf)break;C>p&&(p=C,g=_),_+=h}const m=_,b=Tb(e,f,t,n);return{riseMs:f,setMs:m,maxElevDeg:p,maxElevMs:g,riseAzDeg:b?b.azDeg:0}}function RH({state:e,services:t,parts:n,source:i}){function o(m,b,C=new Cesium.Matrix4){const y=po(b)-m,v=Cesium.Matrix3.fromRotationZ(-y,e._scratchRingRotation);return Cesium.Matrix4.fromRotationTranslation(v,Cesium.Cartesian3.ZERO,C)}function r(m){const b=m.trim().split(` +`).map(y=>y.trim()).filter(y=>y.length>0),C=[];for(let y=0;y=5&&(v.includes(M)||M.includes(v))&&(w+=200+Math.min(v.length,M.length));const E=new Set(["group","block","mission","launch","falcon","rocket"]),k=C.split(/[^a-z0-9]+/).filter(T=>T.length>=4&&!E.has(T));return w+=k.reduce((T,I)=>T+(y.includes(I)?I.length:0),0),w}function h(m){const b=String((m==null?void 0:m.intldesg)||"").match(/^(\d{2})/);if(!b)return null;const C=Number(b[1]);return C>=57?1900+C:2e3+C}function d(m){return m!==e._lookupTleText&&(e._lookupTleText=m,e._lookupTleEntries=r(m)),e._lookupTleEntries}function f(m){const b=Number(String(m||"").slice(9,11));return Number.isFinite(b)?b>=57?1900+b:2e3+b:null}function p(m,b){const C=new Date,y=s(b,C);return y?{noradId:Number(b.satnum),name:String(m||"").trim(),current:y,periodSec:a(b),orbitPath:c(b,C),gmstAtBake:po(C),positionAt:v=>s(b,v)}:null}function g(m,b,C={}){const y=Number.isFinite(Date.parse(C.launchTime))?new Date(C.launchTime).getUTCFullYear():null;let v=null,M=0;const w=String(m||"");for(const k of d(w)){const T=f(k.line1);if(y!==null&&T!==null&&T!==y)continue;const I=u(b,k.name);I>M&&(v=k,M=I)}if(!v||M<12)return null;const E=Hm(v.line1,v.line2);return!E||E.error!==0?null:p(v.name,E)}function _(m,b={}){var M;if(m==null||!((M=e._catalog)!=null&&M.size))return null;const C=String(m).trim().toLowerCase();let y=/^\d+$/.test(C)?Number(C):null;if(y===null||!e._catalog.has(y)){y=null;const w=Number.isFinite(Date.parse(b.launchTime))?new Date(b.launchTime).getUTCFullYear():null;let E=0;for(const[k,T]of e._catalog){const I=h(T.satrec);if(w!==null&&I!==null&&I!==w)continue;const R=u(C,T.name);R>E&&(E=R,y=k)}E<12&&(y=null)}if(y===null)return null;const v=e._catalog.get(y);return p(v.name,v.satrec)}return{orbitFrameModelMatrix:o,parseTLE:r,propagatePosition:s,orbitalPeriodSeconds:a,computeOrbitPath:c,getNextIssPass:l,scoreSatelliteNameMatch:u,internationalDesignatorYear:h,lookupTleEntries:d,tleLineLaunchYear:f,orbitTrackFromRecord:p,findSatelliteOrbitTrackInTle:g,getSatelliteOrbitTrack:_}}function LH({state:e,services:t,parts:n,source:i}){const{focusNowMs:o,getFocusTarget:r,focusPassIsNeeded:s,nearFarScalarValueAtDistance:a,advanceSpriteFocus:c,focusAlphaNeedsWrite:l}=t.focus;function u(m,b){if(e._orbitPaths.has(m))return;const C=e._catalog.get(m);if(!C||!e._viewer)return;const y=new Date,v=n.orbits.computeOrbitPath(C.satrec,y);if(v.length<2)return;const M=b||Cesium.Color.CYAN,w=new Cesium.Primitive({geometryInstances:new Cesium.GeometryInstance({geometry:new Cesium.PolylineGeometry({positions:v,width:m===_t?2.5:2,vertexFormat:Cesium.PolylineColorAppearance.VERTEX_FORMAT}),attributes:{color:Cesium.ColorGeometryInstanceAttribute.fromColor(M.withAlpha(.6)),depthFailColor:Cesium.ColorGeometryInstanceAttribute.fromColor(M.withAlpha(.35))}}),appearance:new Cesium.PolylineColorAppearance({translucent:!0}),depthFailAppearance:new Cesium.PolylineColorAppearance({translucent:!0}),asynchronous:!1,allowPicking:!1});e._viewer.scene.primitives.add(w),e._orbitPaths.set(m,{primitive:w,gmstAtBake:po(y)})}function h(m){if(e._orbitPaths.size!==0)for(const b of e._orbitPaths.values())b.primitive&&n.orbits.orbitFrameModelMatrix(b.gmstAtBake,m,b.primitive.modelMatrix)}function d(m){const b=e._orbitPaths.get(m);b&&(e._viewer&&e._viewer.scene.primitives.remove(b.primitive),e._orbitPaths.delete(m))}function f(){const m=new Date;let b=0;for(const[C,y]of e._catalog){if(y.group==="dense")continue;const v=n.orbits.propagatePosition(y.satrec,m);if(!v)continue;const M=Cesium.Cartesian3.fromDegrees(v.longitude,v.latitude,v.altitude),w=e._points.get(C);w&&(w.position=M,b++)}return b}function p(){if(!e._enabled)return;const m=o(Date.now()),b=e._trackedNorad?200:ZV;if(e._params.showPoints&&m-e._lastPropagation>=b&&(f(),e._lastPropagation=m),e._params.showPoints&&n.catalog._propagateDenseChunk(),e._trackedNorad!==null){const C=n.tracking._getTrackedFramePosition(),y=e._points.get(e._trackedNorad);C&&y&&(y.position=e._trackedFrameCartesian)}g(m),e._params.showOrbits&&m-e._lastRingRotation>=JV&&(h(new Date(m)),e._lastRingRotation=m)}function g(m){const b=r();if(!e._params.showPoints||!s(b,e._activeFocusCount)||m-e._lastFocusUpdate<80)return;e._lastFocusUpdate=m;const C=e._viewer.scene,y=e._viewer.camera,v=_({points:e._points,trackedId:e._trackedNorad,target:b,previousActiveCount:e._activeFocusCount,nowMs:m,screenPositionFor:M=>Cesium.SceneTransforms.worldToWindowCoordinates(C,M,e._scratchFocusScreen),cameraDistanceFor:M=>Cesium.Cartesian3.distance(y.positionWC,M),baseColorFor:M=>{var w;return n.controls._pointStyleFor(M,(w=e._catalog.get(M))==null?void 0:w.group).color}});e._activeFocusCount=v.activeCount}function _({points:m,trackedId:b,target:C,previousActiveCount:y=0,nowMs:v,screenPositionFor:M,cameraDistanceFor:w,baseColorFor:E,params:k}){var S;if(!s(C,y))return{writes:0,transitioning:!1,activeCount:0,ran:!1};let T=0,I=!1,R=0;for(const[A,L]of m||[]){if(A===b||!(L!=null&&L.position))continue;const F=w(L.position),P=a(L.scaleByDistance,F),O=(L.pixelSize||5)*P*.5,D=c(L,{screenPosition:L.show===!1?null:M(L.position),cameraDistance:F,nowMs:v,target:C,params:k,spriteHalfWidthPx:O,spriteHalfHeightPx:O});I||(I=D.transitioning),D.active&&(R+=1);const $=E(A),x=$.alpha*D.factor;l((S=L.color)==null?void 0:S.alpha,x,k)&&(L.color=$.withAlpha(x),T+=1)}return{writes:T,transitioning:I,activeCount:R,ran:!0}}return{_showOrbitPath:u,_updateOrbitPathRotations:h,_hideOrbitPath:d,_propagateAll:f,_preRenderTick:p,_updatePointFocus:g,applySatellitePointFocusDeemphasis:_}}function PH({state:e,services:t,parts:n,source:i}){const{clearFocusTarget:o,publishFocusTargetFromCachedPosition:r}=t.focus,{clearTrackedSubjectContext:s,getContextStore:a,refreshTrackedSubjectContext:c,selectTrackedSubjectContext:l}=t.context,{refreshTrackedReadout:u}=t.readout;function h(w){const E=Number(w);if(!Number.isFinite(E))return null;const k=Math.trunc(E);return k>0?k:null}function d(w,E){typeof window>"u"||!window.dispatchEvent||typeof CustomEvent>"u"||window.dispatchEvent(new CustomEvent(w,{detail:E}))}function f(){const w=e._pendingTrackingRestore;return!w||w.generation!==e._trackingIntentGeneration||!e._enabled||!e._viewer||!e._catalog.has(w.id)||!e._points.has(w.id)?!1:(e._pendingTrackingRestore=null,M(w.id,{origin:w.origin}),e._trackedNorad===w.id)}function p(){e._trackingIntentGeneration+=1,e._pendingTrackingRestore=null}function g(w=!1,{origin:E="programmatic"}={}){var I;if(e._dockedCompanions=new Set,e._lastDockedScanMs=Number.NEGATIVE_INFINITY,!e._trackedNorad){o("satellites"),n.labels._syncIssOverlay();return}const k=e._trackedNorad;o("satellites",e._trackedNorad);const T=e._points.get(e._trackedNorad);if(T){const R=n.controls._pointStyleFor(e._trackedNorad,(I=e._catalog.get(e._trackedNorad))==null?void 0:I.group);T.show=!0,T.pixelSize=R.pixelSize,T.color=R.color,T.outlineColor=R.outlineColor,T.outlineWidth=R.outlineWidth,T.disableDepthTestDistance=0}e._trackedFrameNumber=-1,e._trackedFrameGeo=null,e._trackedNorad!==_t&&n.rendering._hideOrbitPath(e._trackedNorad),e._viewer&&!w&&(e._viewer.trackedEntity=void 0),e._trackedEntity&&(e._viewer.entities.remove(e._trackedEntity),e._trackedEntity=null),e._trackedNorad=null,n.labels._syncIssOverlay(),s("satellites"),e._contextRefreshedAtMs=0,d("gev:awareness-subject-cleared",{layerId:"satellites",id:k,origin:E})}function _(){var k,T,I,R,S,A;if(e._trackedNorad===null)return null;const w=e._catalog.get(e._trackedNorad);if(!w)return null;const E=((I=(T=(k=e._viewer)==null?void 0:k.scene)==null?void 0:T.frameState)==null?void 0:I.frameNumber)??-1;if(E===-1||E!==e._trackedFrameNumber||e._trackedFrameGeo===null){const L=n.orbits.propagatePosition(w.satrec,e._trackedFrameNowForTest?new Date(e._trackedFrameNowForTest()):new Date);if(!L)return e._trackedFrameGeo;e._trackedFrameGeo=L,Cesium.Cartesian3.fromDegrees(L.longitude,L.latitude,L.altitude,void 0,e._trackedFrameCartesian),e._trackedFrameNumber=E;const F=n.labels._refreshDockedCompanions(e._trackedFrameNowForTest?e._trackedFrameNowForTest():Date.now());v(),y(),F&&n.labels._syncIssOverlay();const P=((R=w.name)==null?void 0:R.trim())||`SAT-${e._trackedNorad}`,O=`${Math.round(L.altitude/1e3)} km · NORAD ${e._trackedNorad}`,D=Math.max(P.length,O.length)*7.8+20,$=38,x=18;r({ownerLayer:"satellites",id:e._trackedNorad,scene:(S=e._viewer)==null?void 0:S.scene,camera:(A=e._viewer)==null?void 0:A.camera,displayPosition:e._trackedFrameCartesian,widthPx:Math.max(x,Math.min(260,D)),heightPx:x+18+$})}return e._trackedFrameGeo}function m(){return e._trackedFrameGeo?e._trackedFrameCartesian:null}function b(w,E=null){var S;const k=e._catalog.get(w);if(!k)return null;const T=E||_();if(!T)return null;const I=((S=k.name)==null?void 0:S.trim())||`SAT-${w}`,R=Number.isFinite(T.altitude)?Math.round(T.altitude/1e3):null;return{id:String(w),layerId:"satellites",layerName:"Satellites",source:"CelesTrak",label:I,latitude:T.latitude,longitude:T.longitude,properties:{name:I,operator:"",noradId:String(w),class:xh(k.group,{isIss:w===_t}),altitude:R===null?"":`${R.toLocaleString("en-US")} km`}}}async function C(){var T;const w=e._trackedNorad;if(w===null)return;const E=e._params.catalog==="dense"?e._denseLoadPromise:null;if(E)try{await E}catch{}if(e._trackedNorad!==w)return;const k=b(w);if(k){const I=a(),R=String(w);I.entities.has(R)?c(k):I.selectedEntityId||l(k),e._contextRefreshedAtMs=Date.now();return}e._catalog.size!==0&&((T=e._lastTrackingRefreshOutcome)==null?void 0:T.status)==="accepted"&&(E&&e._denseStatus!=="ready"||(s("satellites"),e._contextRefreshedAtMs=0))}function y(){if(e._trackedNorad===null)return;const w=Date.now();w-e._contextRefreshedAtMs0){const D=S.length-1;R.push(`DOCKED · ${S[0]}${D>0?` · +${D}`:""}`)}const A=e._trackedEntity.gevLabelModel;(A==null?void 0:A.title)===k&&((O=A==null?void 0:A.details)==null?void 0:O.length)===R.length&&R.every((D,$)=>A.details[$]===D)||(e._trackedEntity.gevLabelModel={title:k,details:R,accent:"#ffd84d"},u(e._trackedEntity))}function M(w,{origin:E="programmatic"}={}){g(!1,{origin:E});const k=e._points.get(w),T=e._catalog.get(w);if(!k||!T)return;e._trackedNorad=w,e._trackedFrameNumber=-1,e._trackedFrameGeo=null,n.labels._syncIssOverlay(),k.show=!1,n.rendering._showOrbitPath(w,Cesium.Color.YELLOW);const I=new Cesium.CallbackProperty(()=>_()?e._trackedFrameCartesian:k.position,!1),R=T.name.trim(),S=n.orbits.propagatePosition(T.satrec,new Date),A=S&&S.altitude>iH?oH:1,L=Cesium.Cartesian3.multiplyByScalar(nH,A,new Cesium.Cartesian3);e._trackedEntity=e._viewer.entities.add({position:I,viewFrom:L,point:{pixelSize:14,color:Cesium.Color.YELLOW,outlineColor:Cesium.Color.WHITE,outlineWidth:2,disableDepthTestDistance:Number.POSITIVE_INFINITY}}),e._trackedEntity.gevSelectionOrigin=E,e._trackedEntity.gevTrackedId=`satellites:${w}`,e._trackedEntity.gevDisplayPosition=m,v((S==null?void 0:S.altitude)??null),d("gev:awareness-subject-selected",{layerId:"satellites",id:w,label:R,position:Cesium.Cartesian3.clone(k.position),origin:E}),l(b(w,S)),e._contextRefreshedAtMs=Date.now(),e._viewer.trackedEntity=e._trackedEntity,console.log(`[Data:Satellites] Tracking ${R} (NORAD ${w})`)}return{_normalizeTrackedNorad:h,_emitAwarenessEvent:d,_applyPendingTrackingRestore:f,_cancelPendingTrackingRestore:p,_clearTracking:g,_getTrackedFramePosition:_,_trackedDisplayCached:m,_contextSubjectMetadata:b,_reconcileTrackedSubjectContext:C,_refreshTrackedSubjectContext:y,_updateTrackedSatelliteLabelModel:v,_trackSatellite:M}}function xH({state:e,services:t,parts:n,source:i}){function o({noradId:m,name:b,satrec:C,entity:y,point:v,viewer:M,now:w,neighbours:E=[]}){e._viewer=M,e._catalog=new Map([[m,{name:b,satrec:C,group:"stations"}]]),e._points=new Map([[m,v]]);for(const k of E)e._catalog.set(k.noradId,{name:k.name,satrec:k.satrec||C,group:k.group||"stations"}),e._points.set(k.noradId,k.point);e._dockedCompanions=new Set,e._lastDockedScanMs=Number.NEGATIVE_INFINITY,e._trackedNorad=m,e._trackedEntity=y,e._trackedFrameNumber=-1,e._trackedFrameGeo=null,e._trackedFrameNowForTest=w,e._params={catalog:"core",showPoints:!1,showOrbits:!1},e._enabled=!0}function r({status:m="accepted",failedGroups:b=[],catalog:C="core",densePromise:y=null}={}){const v=++e._trackingRefreshEpoch;e._lastTrackingRefreshOutcome={epoch:v,status:m,failedGroups:[...b]},e._params.catalog=C,e._denseLoadPromise=y||Promise.resolve({status:"not-requested"})}function s(){return e._trackedFrameCartesian}function a(){n.rendering._preRenderTick()}function c({catalog:m="core",showPoints:b=!0}={}){e._viewer={scene:{primitives:{add:C=>C,remove(){}}}},e._overlayHost={setEntries(){},setVisible(){},clearSource(){}},e._pointCollection={show:!0,add:C=>({...C}),remove(){},removeAll(){}},e._catalog=new Map,e._points=new Map,e._detectionObjects=new Map,e._orbitPaths=new Map,e._denseIds=[],e._denseCursor=0,e._denseLoadToken++,e._denseStatus="idle",e._denseError=null,e._catalogRevision++,e._trackedNorad=null,n.tracking._cancelPendingTrackingRestore(),e._params={catalog:m,showPoints:b,showOrbits:!1},e._enabled=!0}function l(){e._rowControlsListener=null,e._overlayHost=e.DEFAULT_OVERLAY_HOST,e._orbitPaths=new Map,e._viewer=null,e._pointCollection=null,e._catalog=new Map,e._points=new Map,e._denseIds=[],e._denseLoadToken++,e._denseStatus="idle",e._denseError=null,e._params={catalog:"core",showPoints:!0,showOrbits:!0},n.tracking._cancelPendingTrackingRestore(),e._enabled=!1}function u(m){var b;return(b=e._catalog.get(Number(m)))==null?void 0:b.group}function h({viewer:m,satrec:b,point:C,overlayHost:y,preservePending:v=!1}){e._viewer=m,e._catalog=new Map([[_t,{name:"ISS (ZARYA)",satrec:b,group:"stations"}]]),e._points=new Map([[_t,C]]),e._orbitPaths=new Map([[_t,{primitive:{show:!0,modelMatrix:new Cesium.Matrix4},gmstAtBake:0}]]),e._trackedNorad=null,e._trackedEntity=null,v||n.tracking._cancelPendingTrackingRestore(),e._trackedFrameNumber=-1,e._trackedFrameGeo=null,e._enabled=!0,e._params={catalog:"core",showPoints:!0,showOrbits:!0},e._overlayHost=y||e.DEFAULT_OVERLAY_HOST,n.labels._syncIssOverlay()}function d(){return n.tracking._trackSatellite(_t),e._trackedEntity}function f(){var m;return((m=e._pendingTrackingRestore)==null?void 0:m.id)??null}function p(){return n.tracking._applyPendingTrackingRestore()}function g(m){const b=Number(m);e._catalog.delete(b),e._points.delete(b)}function _(){n.tracking._clearTracking(),e._enabled=!1,e._overlayHost.clearSource(Rn),e._overlayHost.setVisible(Rn,!1),e._overlayHost=e.DEFAULT_OVERLAY_HOST}return{_setTrackedSatelliteRefreshStateForTest:o,_setSatelliteTrackingRefreshOutcomeForTest:r,_trackedFrameCartesianForTest:s,_runSatellitePreRenderForTest:a,_setDenseCatalogStateForTest:c,_clearDenseCatalogStateForTest:l,_catalogGroupForTest:u,_setSatelliteLabelLifecycleStateForTest:h,_trackIssForTest:d,_pendingSatelliteTrackingRestoreForTest:f,_applyPendingSatelliteTrackingRestoreForTest:p,_removeSatelliteTrackingCandidateForTest:g,_clearSatelliteLabelLifecycleForTest:_}}function FH({state:e,services:t,parts:n,source:i}){const{resolvePickId:o,isOwnedByOtherLayer:r}=t.picking;function s(c){e._enabled&&c.key==="Escape"&&e._trackedNorad&&(n.tracking._cancelPendingTrackingRestore(),n.tracking._clearTracking(!1,{origin:"user"}))}function a(c){e._clickHandler||(e._trackedEntityChangedRemove||(e._trackedEntityChangedRemove=c.trackedEntityChanged.addEventListener(()=>{var l;e._enabled&&e._trackedNorad&&e._viewer&&e._viewer.trackedEntity&&e._viewer.trackedEntity!==e._trackedEntity&&n.tracking._clearTracking(!0,{origin:((l=e._viewer.trackedEntity)==null?void 0:l.gevSelectionOrigin)||"programmatic"})})),e._clickHandler=new Cesium.ScreenSpaceEventHandler(c.scene.canvas),e._clickHandler.setInputAction(l=>{if(!Bt()||!e._enabled)return;const u=c.scene.pick(l.position);if(u){if(u.id===e._trackedEntity)return;const h=u.primitive;if(h&&h.id!=null){const d=Number(h.id);if(!isNaN(d)&&e._catalog.has(d)){n.tracking._cancelPendingTrackingRestore(),n.tracking._trackSatellite(d,{origin:"user"});return}}}if(u){const h=o(u);if(h&&r("satellites",h))return}e._trackedNorad&&(n.tracking._cancelPendingTrackingRestore(),n.tracking._clearTracking(!1,{origin:"user"}))},Cesium.ScreenSpaceEventType.LEFT_CLICK),document.addEventListener("keydown",s))}return{_onKeyDown:s,_installClickHandler:a}}function SH({state:e,services:t,parts:n,source:i}){const{clearFocusTarget:o}=t.focus,{holdContinuousRender:r,releaseContinuousRender:s}=t.render,{registerPickOwner:a,unregisterPickOwner:c}=t.picking;return{methods:{async init(u){n.catalog._abortActiveUpdates(),o("satellites"),e._viewer=u,e._catalog=new Map,e._points=new Map,e._detectionObjects=new Map,e._orbitPaths=new Map,e._count=0,e._lastUpdate=null,e._trackedNorad=null,n.tracking._cancelPendingTrackingRestore(),e._trackedEntity=null,e._trackedFrameNumber=-1,e._trackedFrameGeo=null,e._trackedFrameNowForTest=null,e._lastFocusUpdate=0,e._activeFocusCount=0,e._enabled=!1,e._overlayHost.clearSource(Rn),e._overlayHost.setVisible(Rn,!1),e._denseIds=[],e._denseCursor=0,e._denseLoadPromise=null,e._denseLoadToken++,e._denseStatus="idle",e._denseError=null,e._catalogRevision++,e._pointCollection=new Cesium.PointPrimitiveCollection,u.scene.primitives.add(e._pointCollection),n.interaction._installClickHandler(u),e._preRenderListener=u.scene.preRender.addEventListener(n.rendering._preRenderTick),console.log("[Data:Satellites] Initialized")},enable(u){e._enabled=!0,r("satellites"),e._pointCollection&&(e._pointCollection.show=n.controls.satelliteVisualsVisible(e._enabled,e._params.showPoints));for(const h of e._orbitPaths.values())h.primitive.show=n.controls.satelliteVisualsVisible(e._enabled,e._params.showOrbits);n.labels._syncIssOverlay(),n.interaction._installClickHandler(u),a("satellites",h=>{const d=Number(h);return Number.isFinite(d)&&e._points.has(d)}),!e._preRenderListener&&u&&(e._preRenderListener=u.scene.preRender.addEventListener(n.rendering._preRenderTick)),n.tracking._applyPendingTrackingRestore()},disable(u){n.catalog._abortActiveUpdates(),n.tracking._cancelPendingTrackingRestore(),e._enabled=!1,s("satellites"),e._pointCollection&&(e._pointCollection.show=!1);for(const h of e._orbitPaths.values())h.primitive.show=!1;n.tracking._clearTracking(),n.labels._syncIssOverlay(),e._clickHandler&&(e._clickHandler.destroy(),e._clickHandler=null),e._trackedEntityChangedRemove&&(e._trackedEntityChangedRemove(),e._trackedEntityChangedRemove=null),document.removeEventListener("keydown",n.interaction._onKeyDown),c("satellites"),e._preRenderListener&&(e._preRenderListener(),e._preRenderListener=null)},destroy(u){n.catalog._abortActiveUpdates(),s("satellites"),e._enabled=!1,n.tracking._clearTracking(),n.tracking._cancelPendingTrackingRestore(),e._clickHandler&&(e._clickHandler.destroy(),e._clickHandler=null),e._trackedEntityChangedRemove&&(e._trackedEntityChangedRemove(),e._trackedEntityChangedRemove=null),document.removeEventListener("keydown",n.interaction._onKeyDown),c("satellites"),e._preRenderListener&&(e._preRenderListener(),e._preRenderListener=null),e._overlayHost.clearSource(Rn),e._overlayHost.setVisible(Rn,!1),e._pointCollection&&(u.scene.primitives.remove(e._pointCollection),e._pointCollection=null);for(const h of e._orbitPaths.values())u.scene.primitives.remove(h.primitive);e._points.clear(),e._detectionObjects.clear(),e._orbitPaths.clear(),e._catalog.clear(),e._denseIds=[],e._denseCursor=0,e._denseLoadToken++,e._denseStatus="idle",e._denseError=null,e._catalogRevision++,e._rowControlsListener=null,e._count=0,e._lastUpdate=null,e._lastError=null,e._lastFocusUpdate=0,e._activeFocusCount=0,e._trackingRefreshEpoch+=1,e._lastTrackingRefreshOutcome={epoch:e._trackingRefreshEpoch,status:"destroyed",failedGroups:[]},e._viewer=null}}}}function NH({state:e,services:t,parts:n,source:i}){return{methods:{async update(r,{signal:s=null}={}){var u;const a=++e._trackingRefreshEpoch;e._lastTrackingRefreshOutcome={epoch:a,status:"source-unavailable",failedGroups:[]};const c=new AbortController;e._activeUpdateControllers.add(c);const l=s?AbortSignal.any([s,c.signal]):c.signal;try{l.throwIfAborted();const h=await Promise.all(eH.map(async _=>{try{const m=await i.readGroup(_.path,{signal:l});if(!m.ok)return{..._,entries:[],ok:!1};const b=n.orbits.parseTLE(m.text);return l.throwIfAborted(),{..._,entries:b,ok:b.length>0}}catch(m){if(l.aborted||(m==null?void 0:m.name)==="AbortError")throw m;return{..._,entries:[],ok:!1}}}));l.throwIfAborted();const d=h.filter(_=>!_.ok).map(_=>_.path);if(d.length>0&&console.warn(`[Data:Satellites] Groups failed or empty: ${d.join(", ")}`),console.log(`[Data:Satellites] Loaded ${h.map(_=>`${_.tag}:${_.entries.length}`).join(" ")}`),h.every(_=>!_.ok)){e._lastError="CelesTrak unreachable",console.warn("[Data:Satellites] All CelesTrak groups failed — keeping existing catalog, surfacing outage");return}e._lastError=d.length?`${d.length} CelesTrak group${d.length===1?"":"s"} unavailable`:null,e._pointCollection.removeAll(),e._points.clear();for(const _ of e._orbitPaths.values())r.scene.primitives.remove(_.primitive);e._orbitPaths.clear(),e._catalog.clear(),e._detectionObjects.clear(),e._denseIds=[],e._denseCursor=0,(u=e._denseLoadController)==null||u.abort(),e._denseLoadController=null,e._denseLoadToken++,n.labels._syncIssOverlay();const f=new Date,p=[];for(const _ of h)for(const m of _.entries)p.push({...m,group:_.tag});const g=new Set;for(const _ of p){const m=Hm(_.line1,_.line2);if(!m||m.error!==0)continue;const b=Number(m.satnum);if(g.has(b))continue;g.add(b),e._catalog.set(b,{name:_.name,satrec:m,group:_.group});const C=n.orbits.propagatePosition(m,f);if(!C)continue;const y=Cesium.Cartesian3.fromDegrees(C.longitude,C.latitude,C.altitude),v=n.controls._pointStyleFor(b,_.group),M=e._pointCollection.add({position:y,pixelSize:v.pixelSize,color:v.color,outlineColor:v.outlineColor,outlineWidth:v.outlineWidth,scaleByDistance:new Cesium.NearFarScalar(1e6,1.5,2e7,.6),id:b});e._points.set(b,M)}if(e._catalog.has(_t)){n.rendering._showOrbitPath(_t,Vs.iss.color);const _=e._orbitPaths.get(_t);_&&(_.primitive.show=e._params.showOrbits),n.labels._syncIssOverlay()}e._count=e._points.size,e._catalogRevision++,e._lastUpdate=Date.now(),e._lastPropagation=Date.now(),e._lastTrackingRefreshOutcome={epoch:a,status:d.length?"partial":"accepted",failedGroups:[...d]},console.log(`[Data:Satellites] ${e._count} satellites active, ISS path shown`),e._denseLoadPromise=e._params.catalog==="dense"?n.catalog._loadDenseCatalog({signal:l}):Promise.resolve({status:"not-requested"}),n.tracking._reconcileTrackedSubjectContext(),n.tracking._applyPendingTrackingRestore()}catch(h){if(l.aborted||(h==null?void 0:h.name)==="AbortError")throw new DOMException("Satellite update aborted","AbortError");console.warn("[Data:Satellites] Fetch error:",h)}finally{e._activeUpdateControllers.delete(c)}}}}}function DH({services:e}){const{setOverlayEntries:t,setOverlaySourceVisible:n,clearOverlaySource:i}=e.overlays,o={};return o.DEFAULT_OVERLAY_HOST=Object.freeze({setEntries:t,setVisible:n,clearSource:i}),o._overlayHost=o.DEFAULT_OVERLAY_HOST,o._catalog=new Map,o._pointCollection=null,o._points=new Map,o._detectionObjects=new Map,o._orbitPaths=new Map,o._count=0,o._lastUpdate=null,o._lastError=null,o._activeUpdateControllers=new Set,o._denseLoadController=null,o._viewer=null,o._preRenderListener=null,o._lastPropagation=0,o._lastRingRotation=0,o._lastFocusUpdate=0,o._activeFocusCount=0,o._scratchFocusScreen=new Cesium.Cartesian2,o._enabled=!1,o._trackedNorad=null,o._pendingTrackingRestore=null,o._trackingIntentGeneration=0,o._trackingRefreshEpoch=0,o._lastTrackingRefreshOutcome={epoch:0,status:"unavailable",failedGroups:[]},o._trackedEntity=null,o._clickHandler=null,o._trackedEntityChangedRemove=null,o._params={catalog:"core",showPoints:!0,showOrbits:!0},o._denseIds=[],o._denseCursor=0,o._denseLoadToken=0,o._denseLoadPromise=null,o._denseStatus="idle",o._denseError=null,o._catalogRevision=0,o._classTallyCache={revision:-1,counts:null},o._rowControlsListener=null,o._dockedCompanions=new Set,o._lastDockedScanMs=Number.NEGATIVE_INFINITY,o._trackedFrameNumber=-1,o._trackedFrameGeo=null,o._trackedFrameCartesian=new Cesium.Cartesian3,o._trackedFrameNowForTest=null,o._scratchCartesian=new Cesium.Cartesian3,o._scratchRingRotation=new Cesium.Matrix3,o._contextRefreshedAtMs=0,o._lookupTleText=null,o._lookupTleEntries=[],o}const OH=new Set(["stations","visual","gps-ops","glo-ops","galileo","geo","starlink"]);function BH({fetchImpl:e=(...t)=>globalThis.fetch(...t)}={}){return{async readGroup(t,{signal:n}={}){if(!OH.has(t))throw new TypeError("Unknown satellite group");n==null||n.throwIfAborted();const i=await e(`/api/celestrak/${t}`,{signal:n}),o=i.ok?await i.text():"";return n==null||n.throwIfAborted(),{ok:i.ok,status:i.status,text:o}}}}function VH({services:e,source:t}){if(typeof(t==null?void 0:t.readGroup)!="function")throw new TypeError("A satellites source is required");const n=DH({services:e}),i={},o={state:n,services:e,parts:i,source:t};return i.controls=aH(o),i.catalog=kH(o),i.labels=AH(o),i.orbits=RH(o),i.rendering=LH(o),i.tracking=PH(o),i.testing=xH(o),i.interaction=FH(o),i.lifecycle=SH(o),i.ingestion=NH(o),Object.assign({},i.controls.methods,i.lifecycle.methods,i.ingestion.methods,{satelliteVisualsVisible:i.controls.satelliteVisualsVisible,satelliteCatalogModeChanged:i.controls.satelliteCatalogModeChanged,createIssOverlayEntry:i.labels.createIssOverlayEntry,orbitFrameModelMatrix:i.orbits.orbitFrameModelMatrix,_setTrackedSatelliteRefreshStateForTest:i.testing._setTrackedSatelliteRefreshStateForTest,_setSatelliteTrackingRefreshOutcomeForTest:i.testing._setSatelliteTrackingRefreshOutcomeForTest,_trackedFrameCartesianForTest:i.testing._trackedFrameCartesianForTest,_runSatellitePreRenderForTest:i.testing._runSatellitePreRenderForTest,_setDenseCatalogStateForTest:i.testing._setDenseCatalogStateForTest,_clearDenseCatalogStateForTest:i.testing._clearDenseCatalogStateForTest,_catalogGroupForTest:i.testing._catalogGroupForTest,_setSatelliteLabelLifecycleStateForTest:i.testing._setSatelliteLabelLifecycleStateForTest,_trackIssForTest:i.testing._trackIssForTest,_pendingSatelliteTrackingRestoreForTest:i.testing._pendingSatelliteTrackingRestoreForTest,_applyPendingSatelliteTrackingRestoreForTest:i.testing._applyPendingSatelliteTrackingRestoreForTest,_removeSatelliteTrackingCandidateForTest:i.testing._removeSatelliteTrackingCandidateForTest,_clearSatelliteLabelLifecycleForTest:i.testing._clearSatelliteLabelLifecycleForTest,applySatellitePointFocusDeemphasis:i.rendering.applySatellitePointFocusDeemphasis,getNextIssPass:i.orbits.getNextIssPass,scoreSatelliteNameMatch:i.orbits.scoreSatelliteNameMatch,findSatelliteOrbitTrackInTle:i.orbits.findSatelliteOrbitTrackInTle,getSatelliteOrbitTrack:i.orbits.getSatelliteOrbitTrack})}function HH({source:e}){return VH({source:e,services:{picking:rn,focus:ma,readout:rm,overlays:ui,context:Go,render:Pt,layerState:Yk}})}const $H=30,Zo="rocket-missions",Jo="rocket-mission-selected",Sh=48,GH=24,UH=Object.freeze({cohortLimit:12,collisionCapacity:0,moving:!0,solveIntervalMs:0}),zH=Object.freeze({cohortLimit:Sh,collisionCapacity:GH,moving:!1}),kb=12,jH=8,qH=36,bE=28,WH=10,CE=5,Nh=3500,KH=9e5,YH=24e5,XH=42e4,QH=18e6,yE=.2,ZH=Cesium.Math.toRadians(30),JH=Cesium.Math.toRadians(45),e$=.45,od=.25,Ab=4,Ib=.25,t$=1,n$=1500,i$=Cesium.Math.TWO_PI/86164.0905,o$=600,Dh=1e5,vs=18e4,$m=5e6,Rb=12e3,Lb={catalog:"core",showPoints:!0,showOrbits:!0},rd=4,sd=100,Pb=500,r$=12e4,s$=18e4,za=["#ff9f43","#ff66c4","#a78bfa","#7bed9f","#ffd166","#60a5fa"];function a$({state:e,services:t,parts:n,source:i}){function o(g){return{...Lb,...g||{},catalog:"dense",showPoints:!1,showOrbits:!1}}function r(g){return{...Lb,...g||{}}}function s(g){return!/\b(?:fail(?:ed|ure)?|partial failure)\b/i.test(String(g||""))}function a(g,_=!1){var y;const m=((y=g==null?void 0:g.orbit)==null?void 0:y.name)||(typeof(g==null?void 0:g.orbit)=="string"?g.orbit:null),b=s(g==null?void 0:g.status),C=Array.isArray(g==null?void 0:g.trajectory)?g.trajectory.filter(v=>Number.isFinite(Number(v==null?void 0:v.latitude))&&Number.isFinite(Number(v==null?void 0:v.longitude))).length:0;return{orbit:m?`${b?"":"PLANNED · "}${m}`:null,ascent:C>1?"SUPPLIED TRAJECTORY POINTS":_?"RECONSTRUCTED ESTIMATE":"UNAVAILABLE",replayAvailable:!!_}}function c(g){var m,b;let _=0;for(const C of["flights","military"]){const y=(b=(m=g==null?void 0:g.layers)==null?void 0:m.get(C))==null?void 0:b.module;typeof(y==null?void 0:y.stopTracking)=="function"&&(y.stopTracking(),_++)}return _}function l({layerActive:g,selectedLaunchId:_,launchId:m,cameraHeightM:b,cameraDistanceM:C}){return!!(g&&_&&_===m&&Number.isFinite(b)&&b<=r$&&Number.isFinite(C)&&C<=s$)}function u(g={}){var b;let _=0;const m=C=>C!=null&&C!=="";return _+=m(g.provider)?1:0,_+=m(g.mission)?2:0,_+=m(g.missionName)?1:0,_+=m(((b=g.orbit)==null?void 0:b.name)||g.orbit)?2:0,_+=Array.isArray(g.payloads)?Math.min(g.payloads.length,5)*2:0,_+=Array.isArray(g.recoveryStages)?Math.min(g.recoveryStages.length,4)*2:0,_+=Array.isArray(g.trajectory)?Math.min(g.trajectory.length,12):0,_+=Array.isArray(g.timeline)?Math.min(g.timeline.length,6):0,_}function h(g){return(g||[]).map((_,m)=>({launch:_,index:m})).sort((_,m)=>{var v,M;const b=u(m.launch)-u(_.launch);if(b!==0)return b;const C=Date.parse((v=_.launch)==null?void 0:v.launchTime),y=Date.parse((M=m.launch)==null?void 0:M.launchTime);return Number.isFinite(C)&&Number.isFinite(y)&&C!==y?y-C:m.index-_.index})}function d(g){const _=new Date(g);return!g||!Number.isFinite(_.getTime())?"UNAVAILABLE":`${_.toISOString().slice(0,10)} +${_.toISOString().slice(11,19)} UTC`}function f(g){const _=String(g||"").trim().match(/^(-)?P(?:(\d+(?:\.\d+)?)D)?(?:T(?:(\d+(?:\.\d+)?)H)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)S)?)?$/);if(!_)return null;const m=Number(_[2]||0)*86400+Number(_[3]||0)*3600+Number(_[4]||0)*60+Number(_[5]||0);return _[1]?-m:m}function p(g){var b;if(!e._viewer||!g||e._selectedLaunchId)return;const _=n.panel.missionHoverPreviewRange((b=e._viewer.camera.positionCartographic)==null?void 0:b.height),m=Cesium.Cartesian3.fromDegrees(g.lon,g.lat);e._viewer.camera.flyToBoundingSphere(new Cesium.BoundingSphere(m,0),{offset:new Cesium.HeadingPitchRange(0,-Cesium.Math.PI_OVER_TWO,_),duration:.8,easingFunction:Cesium.EasingFunction.CUBIC_IN_OUT})}return{satelliteParamsForSpaceMissions:o,satelliteParamsAfterSpaceMissions:r,launchStatusAllowsOrbit:s,missionPathPresentation:a,releaseAircraftTracking:c,launchPadZoneVisible:l,missionDataCompleteness:u,missionRosterEntries:h,formatMissionEventTime:d,parseMissionDurationSeconds:f,previewMissionFromRoster:p}}function l$({state:e,services:t,parts:n,source:i}){function o({enabled:f,retryCount:p,activeTleText:g,renderedTleText:_}){return!!(f&&g&&g!==_&&p{e._retryTimer=null,e._enabled&&f===e._lifecycleToken&&h()},n$))}function a(f){if(e._activeTleText)return Promise.resolve(e._activeTleText);if(e._activeTlePromise&&e._activeTlePromiseToken===f)return e._activeTlePromise;const p=i.getActiveTle({signal:e._sourceController.signal}).then(g=>!e._enabled||f!==e._lifecycleToken?null:(e._activeTleText=g,e._focusAfterActiveLookup=!!e._selectedLaunchId,s(f),g)).catch(g=>(e._enabled&&f===e._lifecycleToken&&console.warn("[Data:RocketLaunches] Active satellite lookup unavailable:",g.message),null)).finally(()=>{e._activeTlePromise===p&&(e._activeTlePromise=null,e._activeTlePromiseToken=0)});return e._activeTlePromise=p,e._activeTlePromiseToken=f,p}async function c(){var g,_;if(!e._dataManager||e._satelliteStateBeforeMission)return;e._satelliteStateBeforeMission={enabled:((_=(g=e._dataManager).isEffectivelyEnabled)==null?void 0:_.call(g,"satellites"))??e._dataManager.isEnabled("satellites"),params:n.policyHelpers.satelliteParamsAfterSpaceMissions(e._dataManager.getLayerParams("satellites"))},e._dataManager.setLayerParams("satellites",n.policyHelpers.satelliteParamsForSpaceMissions(e._satelliteStateBeforeMission.params));const f=e._lifecycleToken,p=Promise.resolve(e._dataManager.setEnabled("satellites",!0));e._satelliteActivationPromise=p;try{const m=await p;if(f===e._lifecycleToken&&e._enabled&&(m===!1||!e._dataManager.isEnabled("satellites")))throw new Error("Space Missions requires the satellites layer, which failed to start")}finally{f===e._lifecycleToken&&e._satelliteActivationPromise===p&&(e._satelliteActivationPromise=null)}}async function l(){const f=e._satelliteStateBeforeMission;if(!f||!e._dataManager)return;if(e._satelliteStateBeforeMission=null,e._satelliteActivationPromise=null,e._dataManager.setLayerParams("satellites",n.policyHelpers.satelliteParamsAfterSpaceMissions(f.params)),await e._dataManager.setEnabled("satellites",f.enabled)===!1||e._dataManager.isEnabled("satellites")!==f.enabled)throw new Error("Space Missions could not restore the satellites layer")}async function u(f){try{a(f);const p=await i.getLaunches({signal:e._sourceController.signal}),g=n.model.normalizeRocketLaunches(p);if(!e._enabled||f!==e._lifecycleToken||!e._dataSource)return;const _=e._activeTleText;e._replayCameraLaunchId&&n.replay.stopMissionReplay(),e._launches=g,n.orbitRendering.removeMissionOrbitPrimitives(),e._dataSource.entities.removeAll(),e._missionOverlayRecords.clear(),e._satelliteTelemetry.clear(),e._replayTracks.clear(),e._orbitMatches=0,g.forEach(m=>n.rendering.addLaunchEntity(m,_)),e._renderedTleText=_,e._renderedTleText===e._activeTleText&&r(),e._count=g.length,n.panel.renderMissionRoster(),!e._selectedLaunchId||!g.some(m=>m.id===e._selectedLaunchId)?n.selection.setSelectedMission(null,!1):(n.selection.setSelectedMission(e._selectedLaunchId,!0),e._focusAfterActiveLookup&&n.selection.focusMission(g.find(m=>m.id===e._selectedLaunchId))),e._focusAfterActiveLookup=!1,n.panel.renderMissionPanel(),e._lastUpdate=Date.now(),e._lastError=null}catch(p){e._enabled&&f===e._lifecycleToken&&(e._lastError=p.message,console.warn("[Data:RocketLaunches] Fetch error:",p))}}function h(){if(!e._enabled)return Promise.resolve();const f=e._lifecycleToken;if(e._updateDirty=!0,e._updatePromise&&e._updatePromiseToken===f)return e._updatePromise;let p;return p=(async()=>{for(;e._enabled&&f===e._lifecycleToken&&e._updateDirty;)e._updateDirty=!1,await u(f)})().finally(()=>{e._updatePromise===p&&(e._updatePromise=null,e._updatePromiseToken=0)}),e._updatePromise=p,e._updatePromiseToken=f,p}return{shouldRetryAfterActiveTle:o,clearPostTleRetry:r,schedulePostTleRetry:s,ensureActiveTleLookup:a,captureSatelliteDependency:c,restoreSatelliteDependency:l,performMissionUpdate:u,requestMissionUpdate:h,methods:{update(){return h()}}}}function c$({state:e,services:t,parts:n,source:i}){const{orbitFrameModelMatrix:o}=t.satellites;function r(){e._missionOrbitPatternRegistered||(new Cesium.Material({fabric:{type:"GevMissionOrbitTactical",uniforms:{color:Cesium.Color.CYAN,groupCount:rd,dashCount:sd},source:` + czm_material czm_getMaterial(czm_materialInput materialInput) { + czm_material material = czm_getDefaultMaterial(materialInput); + float groupPosition = fract(materialInput.st.s * groupCount); + float markPosition = groupPosition * (dashCount + 1.0); + float markIndex = floor(markPosition); + float localPosition = fract(markPosition); + float centerDistance = abs(localPosition - 0.5); + float edge = max(fwidth(localPosition) * 1.35, 0.012); + float dashAlong = 1.0 - smoothstep(0.27 - edge, 0.27 + edge, centerDistance); + float dashAcross = 1.0 - smoothstep(0.12, 0.24, abs(materialInput.st.t - 0.5)); + float dash = dashAlong * dashAcross; + float dotAlong = (localPosition - 0.5) / 0.32; + float dotAcross = (materialInput.st.t - 0.5) / 0.5; + float dot = 1.0 - smoothstep(0.78, 1.0, length(vec2(dotAlong, dotAcross))); + float isDot = 1.0 - step(0.5, markIndex); + float visible = mix(dash, dot, isDot); + material.diffuse = color.rgb; + material.emission = color.rgb * mix(0.07, 0.65, isDot); + material.alpha = color.a * visible * mix(0.58, 1.0, isDot); + return material; + }`}}),e._missionOrbitPatternRegistered=!0)}function s(f){return r(),Cesium.Material.fromType("GevMissionOrbitTactical",{color:f,groupCount:rd,dashCount:sd})}function a(f){var p;return!!(e._enabled&&((p=e._dataSource)!=null&&p.show)&&(!e._selectedLaunchId||e._selectedLaunchId===f))}function c(){for(const[f,p]of e._missionOrbitPrimitives)p.primitive&&(p.primitive.show=a(f))}function l(){var f,p;for(const g of e._missionOrbitPrimitives.values())g.primitive&&((p=(f=e._viewer)==null?void 0:f.scene)!=null&&p.primitives)&&e._viewer.scene.primitives.remove(g.primitive);e._missionOrbitPrimitives.clear()}function u(f){for(const[p,g]of e._missionOrbitPrimitives)!g.primitive||!a(p)||(o(g.gmstAtBake,f,g.primitive.modelMatrix),g.labelBakePosition&&g.labelPosition&&Cesium.Matrix4.multiplyByPoint(g.primitive.modelMatrix,g.labelBakePosition,g.labelPosition))}function h(f,p,g){if(!e._viewer||!g||!Number.isFinite(g.gmstAtBake))return!1;const _=new Cesium.PolylineCollection;return _.add({positions:p,width:3,material:s(Cesium.Color.fromCssColorString("#22e6e6").withAlpha(.95))}),_.show=a(f.id),o(g.gmstAtBake,new Date,_.modelMatrix),e._viewer.scene.primitives.add(_),e._missionOrbitPrimitives.set(f.id,{primitive:_,gmstAtBake:g.gmstAtBake}),!0}function d(f){r(),this._color=f,this._definitionChanged=new Cesium.Event}return Object.defineProperties(d.prototype,{isConstant:{get(){return!0}},definitionChanged:{get(){return this._definitionChanged}}}),d.prototype.getType=function(){return"GevMissionOrbitTactical"},d.prototype.getValue=function(p,g){return Cesium.defined(g)||(g={}),g.color=this._color,g.groupCount=rd,g.dashCount=sd,g},d.prototype.equals=function(p){return this===p},{ensureMissionOrbitPatternRegistered:r,createMissionOrbitPatternMaterial:s,missionOrbitPrimitiveVisible:a,syncMissionOrbitPrimitiveVisibility:c,removeMissionOrbitPrimitives:l,updateMissionOrbitPrimitiveFrames:u,addMissionOrbitPrimitive:h,MissionOrbitPatternMaterialProperty:d}}function u$({state:e,services:t,parts:n,source:i}){function o(y,v,M=.012){if(!y||!v)return!1;const w=Cesium.Cartesian3.magnitude(y);if(!Number.isFinite(w)||w<=Cesium.Ellipsoid.WGS84.maximumRadius)return!1;const E=Cesium.Cartesian3.normalize(y,new Cesium.Cartesian3),k=Cesium.Cartesian3.normalize(v,new Cesium.Cartesian3),T=Cesium.Ellipsoid.WGS84.maximumRadius/w;return Cesium.Cartesian3.dot(E,k)>T+M}function r(y,v,M,w=null){return w&&M!==w?!1:o(y,v)}function s(y,v=24){const w=String(y||"Unnamed mission").replace(/\s+/g," ").trim().split(" | ")[0].split(" — ")[0].trim();return w.length>v?`${w.slice(0,v-1).trimEnd()}…`:w}function a(y){const v=String(y||"").replace(/\s+/g," ").trim();if(!v||/^(unknown|unavailable|n\/a)$/i.test(v))return null;const M=/^(?:orbital\s+launch\s+pad|space\s+launch\s+complex|launch\s+(?:area|complex|pad|site))\s*[-·:]?\s*/i;return v.replace(M,"").trim()||null}function c(y,v,M=!1){const w=s(y==null?void 0:y.name,26).toUpperCase(),E=a(y==null?void 0:y.launchSite),k=Date.parse(y==null?void 0:y.launchTime),T=M?[E?`LAUNCH SITE · ${s(E,20).toUpperCase()}`:"LAUNCH SITE"]:[];return{id:`launch:${y==null?void 0:y.id}`,position:v,variant:"label",title:w,details:T,accent:"#22e6e6",priority:M?Number.MAX_SAFE_INTEGER:Number.isFinite(k)?Math.floor(k/1e3):0,selected:M,protected:M,paintLane:M?"selected":"ambient-label",collisionGroup:"ambient-label",interactive:!1,distanceScale:{near:1e3,nearValue:1.08,far:2e7,farValue:.78},gapPx:12,verticalOnly:!0,placement:"above",edgeFade:"keyhole",horizonCull:!0,terrainOcclusion:!1}}function l({id:y,position:v,text:M,accent:w,priority:E=0,gapPx:k=8}){const[T,...I]=String(M||"").split(` +`);return{id:String(y),position:v,variant:"label",title:T,details:I,accent:w,priority:E,selected:!0,protected:!0,paintLane:"selected",collisionGroup:"ambient-label",interactive:!1,gapPx:k,verticalOnly:!0,placement:"above",edgeFade:"keyhole",horizonCull:!0,terrainOcclusion:!1}}function u(y,v=Sh){const M=Math.max(0,Math.min(Sh,Math.floor(Number(v)||0)));return!Array.isArray(y)||M===0?[]:y.slice().sort((w,E)=>E.priority-w.priority||String(w.id).localeCompare(String(E.id))).slice(0,M)}function h(){if(e._missionHoverReticleImage)return e._missionHoverReticleImage;const y=document.createElement("canvas"),v=48,M=6,w=12;y.width=v,y.height=v;const E=y.getContext("2d");return E.strokeStyle="#22e6e6",E.lineWidth=2,E.lineCap="square",E.shadowColor="rgba(34, 230, 230, .72)",E.shadowBlur=5,E.beginPath(),E.moveTo(M,M+w),E.lineTo(M,M),E.lineTo(M+w,M),E.moveTo(v-M-w,M),E.lineTo(v-M,M),E.lineTo(v-M,M+w),E.moveTo(M,v-M-w),E.lineTo(M,v-M),E.lineTo(M+w,v-M),E.moveTo(v-M-w,v-M),E.lineTo(v-M,v-M),E.lineTo(v-M,v-M-w),E.stroke(),e._missionHoverReticleImage=y,y}function d({replayActive:y,ascending:v,countdownActive:M,preCountdownActive:w=!1}){return!y||w?null:M?"countdown":v?"ascent":"orbit"}function f(){if(e._replayVehicleOverlay||typeof document>"u")return;const y=document.getElementById("cesiumContainer")||document.body;e._replayVehicleOverlay=document.createElement("div"),e._replayVehicleOverlay.className="mission-replay-vehicle-overlay",e._replayVehicleOverlay.hidden=!0,e._replayVehicleOverlay.setAttribute("aria-hidden","true"),e._replayVehicleOverlay.innerHTML=` +
+ + +
+ +
+ + +
`,y.appendChild(e._replayVehicleOverlay)}function p(){e._replayVehicleOverlay&&(e._replayVehicleOverlay.hidden=!0,e._replayVehicleOverlay.classList.remove("is-thrusting","is-paused"))}function g(){var y;(y=e._replayVehicleOverlay)==null||y.remove(),e._replayVehicleOverlay=null,e._replayVehicleOverlayText=""}function _(){e._selectedMissionOverlayTimeText=null,e._missionOverlayHost.clearSource(Zo),e._missionOverlayHost.setVisible(Zo,!1),e._missionOverlayHost.clearSource(Jo),e._missionOverlayHost.setVisible(Jo,!1)}function m(){var M;if(!e._enabled||!((M=e._dataSource)!=null&&M.show)){_();return}const y=e._selectedLaunchId?e._missionOverlayRecords.get(e._selectedLaunchId):null;if(y){e._missionOverlayHost.clearSource(Zo),e._missionOverlayHost.setVisible(Zo,!1);const w=y.elementEntryFactories.map(E=>E());e._replayCameraLaunchId!==y.launch.id&&w.unshift(c(y.launch,y.anchorPosition,!0)),e._missionOverlayHost.setEntries(Jo,w,UH),e._missionOverlayHost.setVisible(Jo,!0),e._selectedMissionOverlayTimeText=y.liveEventTime?n.policyHelpers.formatMissionEventTime(y.liveEventTime()):null;return}e._missionOverlayHost.clearSource(Jo),e._missionOverlayHost.setVisible(Jo,!1),e._selectedMissionOverlayTimeText=null;const v=u(Array.from(e._missionOverlayRecords.values(),w=>{const E=c(w.launch,w.anchorPosition);return w.launch.id===e._hoveredRosterLaunchId&&(E.pinned=!0,E.priority=Number.MAX_SAFE_INTEGER-1),E}));e._missionOverlayHost.setEntries(Zo,v,zH),e._missionOverlayHost.setVisible(Zo,!0)}function b(){const y=e._selectedLaunchId?e._missionOverlayRecords.get(e._selectedLaunchId):null;if(!(y!=null&&y.liveEventTime))return;n.policyHelpers.formatMissionEventTime(y.liveEventTime())!==e._selectedMissionOverlayTimeText&&m()}function C(y){if(!e._viewer||!e._replayVehicleOverlay||!e._selectedLaunchId)return p(),null;const v=e._launches.find(N=>N.id===e._selectedLaunchId),M=e._replayTracks.get(e._selectedLaunchId);if(!v||!M)return p(),null;const w=e._replayCameraLaunchId===v.id,E=M.getReplayState(),k=d({replayActive:w,ascending:E.ascending,countdownActive:E.countdownActive,preCountdownActive:E.preCountdownActive});if(!k)return M.lastOverlayWindowPosition=null,M.lastOverlayMode=null,p(),null;const T=E.ascending?M.ascentPath:M.animatedOrbitPath,I=n.paths.samplePath(T,E.phaseProgress);if(!I||!y.isPointVisible(I))return p(),null;const R=Cesium.SceneTransforms.worldToWindowCoordinates(e._viewer.scene,I);if(!R)return p(),null;const S=e._viewer.scene.canvas;if(R.x<-80||R.y<-100||R.x>S.clientWidth+80||R.y>S.clientHeight+100)return p(),null;const A=!w&&M.lastOverlayMode===k?n.replay.smoothReplayWindowPosition(M.lastOverlayWindowPosition,R):R;M.lastOverlayWindowPosition=A,M.lastOverlayMode=k,e._replayVehicleOverlay.hidden=!1,e._replayVehicleOverlay.dataset.mode=k,e._replayVehicleOverlay.classList.toggle("is-thrusting",w&&E.ascending&&!E.countdownActive),e._replayVehicleOverlay.classList.toggle("is-paused",w&&e._replayPaused),e._replayVehicleOverlay.style.transform=`translate3d(${A.x}px, ${A.y}px, 0) translate(-50%, -50%)`;let L=0;if(w&&!E.countdownActive){const N=Math.max(.002,.8/Math.max(2,T.length-1)),G=Math.min(1,E.phaseProgress+N),W=Math.max(0,E.phaseProgress-N),V=G>E.phaseProgress,H=n.paths.samplePath(T,V?G:W),B=H?Cesium.SceneTransforms.worldToWindowCoordinates(e._viewer.scene,H):null;B&&(Math.hypot(B.x-R.x,B.y-R.y)>=2?(L=V?n.replay.replayVehicleScreenRotation(R,B):n.replay.replayVehicleScreenRotation(B,R),M.lastVehicleRotation=L):Number.isFinite(M.lastVehicleRotation)&&(L=M.lastVehicleRotation))}e._replayVehicleOverlay.style.setProperty("--mission-replay-rotation",`${Cesium.Math.toDegrees(L)}deg`);const F=s(v.name,22).toUpperCase(),P=a(v.launchSite),O=P?`LAUNCH SITE · ${s(P,20).toUpperCase()}`:"LAUNCH SITE";let D=F,$=O;k==="countdown"?(D=`T−${String(E.countdownSeconds).padStart(2,"0")} · ${F}`,$=`LAUNCH STANDBY +${O}`):k==="ascent"?(D=E.elapsedSinceStart<1?`LIFTOFF · ${F}`:`${v.trajectory.length>1?"ASCENT REPLAY":"ASCENT ESTIMATE"} · ${F}`,$=n.policyHelpers.formatMissionEventTime(E.eventTime)):k==="recovery"?(D=`STAGE RE-ENTRY / RECOVERY · ${F}`,$=n.policyHelpers.formatMissionEventTime(E.eventTime)):k==="orbit"&&(D=`ORBIT REPLAY · ${F}`,$=n.policyHelpers.formatMissionEventTime(E.eventTime)),e._replayPaused&&(D=`PAUSED · ${D}`);const x=`${D} +${$}`;return x!==e._replayVehicleOverlayText&&(e._replayVehicleOverlayText=x,e._replayVehicleOverlay.querySelector("[data-replay-overlay-title]").textContent=D,e._replayVehicleOverlay.querySelector("[data-replay-overlay-detail]").textContent=$),k}return{missionAnchorHorizonVisible:o,missionAnchorVisible:r,shortMissionLabel:s,compactLaunchSiteName:a,createRocketMissionMarkerOverlayEntry:c,createRocketMissionElementOverlayEntry:l,selectRocketMissionMarkerOverlayCohort:u,missionHoverReticleImage:h,replayOverlayMode:d,createReplayVehicleOverlay:f,hideReplayVehicleOverlay:p,destroyReplayVehicleOverlay:g,clearMissionOverlaySources:_,syncMissionOverlayEntries:m,refreshSelectedMissionOverlayText:b,updateReplayVehicleOverlay:C}}function d$({state:e,services:t,parts:n,source:i}){const{getKeyholeGeometry:o}=t.geometry;function r(d,f=2.4){var k,T,I,R;const p=(k=d==null?void 0:d.scene)==null?void 0:k.canvas,g=(p==null?void 0:p.clientHeight)||(p==null?void 0:p.height),_=(p==null?void 0:p.clientWidth)||(p==null?void 0:p.width),m=(T=d==null?void 0:d.camera)==null?void 0:T.positionCartographic,b=(R=(I=d==null?void 0:d.camera)==null?void 0:I.frustum)==null?void 0:R.fovy;if(!(_>0)||!(g>0)||!m||!Number.isFinite(b)||b<=0||b>=Math.PI)return;const C=Cesium.Ellipsoid.WGS84.maximumRadius,v=o(_,g).radius*.61,M=Math.atan(v/(g*.5)*Math.tan(b*.5)),w=C/Math.max(Math.sin(M),1e-4),E=Math.max(C*1.55,w-C);d.camera.flyTo({destination:Cesium.Cartesian3.fromRadians(m.longitude,m.latitude,E),orientation:{heading:d.camera.heading,pitch:-Cesium.Math.PI_OVER_TWO,roll:0},duration:f,easingFunction:Cesium.EasingFunction.CUBIC_IN_OUT})}function s(d){if(!(d!=null&&d.id)||typeof d.id!="string")return null;const f=d.id.match(/^rocket-[^:]+:([^:]+)/);return(f==null?void 0:f[1])||null}function a(d,f=!0){if(d&&n.panel.clearMissionRosterHover(),e._replayCameraLaunchId&&e._replayCameraLaunchId!==d&&n.replay.stopMissionReplay(),e._missionZoomAnchorId&&e._missionZoomAnchorId!==d&&c(),e._selectedLaunchId=d,e._explicitSelection=!!(d&&f),d&&e._animationStarts.set(d,Date.now()),!d&&e._viewer&&(c(),e._viewer.selectedEntity=void 0),!!e._dataSource){for(const p of e._dataSource.entities.values){const g=s(p);p.show=d?g===d:p.id.startsWith("rocket-launch:")}n.orbitRendering.syncMissionOrbitPrimitiveVisibility(),n.overlays.syncMissionOverlayEntries(),n.panel.renderMissionPanel()}}function c(){var d;e._missionZoomAnchorRemover&&e._missionZoomAnchorRemover(),e._missionZoomAnchorRemover=null,e._missionZoomAnchorId=null,(d=e._viewer)!=null&&d.camera&&!e._replayCameraLaunchId&&e._viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY)}function l(d,f){if(!e._viewer||!d||e._replayCameraLaunchId)return;c();const p=Cesium.Cartesian3.fromDegrees(d.lon,d.lat),g=Math.max(2e3,Number(f)||$m);e._missionZoomAnchorId=d.id,e._viewer.camera.lookAt(p,new Cesium.HeadingPitchRange(0,n.camera.missionZoomPitch(g),g))}function u(d){var M,w,E;if(!e._viewer||!d)return;c(),e._viewer.selectedEntity=e._dataSource.entities.getById(`rocket-launch:${d.id}`);const f=e._dataSource.entities.getById(`rocket-orbit:${d.id}`),p=(w=(M=f==null?void 0:f.polyline)==null?void 0:M.positions)==null?void 0:w.getValue(Cesium.JulianDate.now()),g=Cesium.Cartesian3.fromDegrees(d.lon,d.lat);let _=18e6;if((p==null?void 0:p.length)>1){const k=e._viewer.scene.canvas,T=((E=e._viewer.camera.frustum)==null?void 0:E.fovy)||Cesium.Math.toRadians(60),I=Math.max(.1,(k.clientWidth||k.width)/Math.max(1,k.clientHeight||k.height)),R=2*Math.atan(Math.tan(T*.5)*I),S=Math.min(T,R)*.5*.62,A=p.reduce((L,F)=>Math.max(L,Cesium.Cartesian3.distance(g,F)),0);_=Math.max(A/Math.max(Math.sin(S),.1),18e6)}const m=Cesium.Cartesian3.normalize(g,new Cesium.Cartesian3),b=Cesium.Cartesian3.add(g,Cesium.Cartesian3.multiplyByScalar(m,_,new Cesium.Cartesian3),new Cesium.Cartesian3),C=Cesium.Cartesian3.negate(m,new Cesium.Cartesian3);let y=Cesium.Cartesian3.cross(C,Cesium.Cartesian3.UNIT_Z,new Cesium.Cartesian3);Cesium.Cartesian3.magnitudeSquared(y)<1e-8&&(y=Cesium.Cartesian3.cross(C,Cesium.Cartesian3.UNIT_Y,y)),Cesium.Cartesian3.normalize(y,y);const v=Cesium.Cartesian3.normalize(Cesium.Cartesian3.cross(y,C,new Cesium.Cartesian3),new Cesium.Cartesian3);e._viewer.camera.flyTo({destination:b,orientation:{direction:C,up:v},duration:1.1,complete:()=>{e._selectedLaunchId===d.id&&l(d,_)}})}function h(d){if(!e._viewer||!d)return;n.replay.stopMissionReplay(),c();const f=Cesium.Cartesian3.fromDegrees(d.lon,d.lat);e._viewer.selectedEntity=e._dataSource.entities.getById(`rocket-launch:${d.id}`),e._viewer.camera.flyToBoundingSphere(new Cesium.BoundingSphere(f,0),{offset:new Cesium.HeadingPitchRange(0,Cesium.Math.toRadians(-42),Rb),duration:1.4,easingFunction:Cesium.EasingFunction.CUBIC_IN_OUT,complete:()=>{e._selectedLaunchId===d.id&&l(d,Rb)}})}return{focusFullGlobe:r,entityLaunchId:s,setSelectedMission:a,stopMissionZoomAnchor:c,startMissionZoomAnchor:l,focusMission:u,focusLaunchSite:h}}function h$({state:e,services:t,parts:n,source:i}){function o(C,y){const v=Number(y==null?void 0:y.x)-Number(C==null?void 0:C.x),M=Number(y==null?void 0:y.y)-Number(C==null?void 0:C.y);return!Number.isFinite(v)||!Number.isFinite(M)||Math.hypot(v,M)<.01?0:Math.atan2(v,-M)}function r(C,y,v=.55,M=24){if(!C||!y)return y;const w=Math.hypot(y.x-C.x,y.y-C.y);if(!Number.isFinite(w)||w>M)return y;const E=Cesium.Math.clamp(Number(v)||0,0,1);return{x:Cesium.Math.lerp(C.x,y.x,E),y:Cesium.Math.lerp(C.y,y.y,E)}}function s(C,y=[]){const v=n.paths.orbitInsertionOffsetSeconds(C);let M=v>0?v:null;if(!M&&y.length>1){const w=y.slice(1).reduce((E,k,T)=>E+Cesium.Cartesian3.distance(y[T],k),0);M=Math.max(180,w/9e3)}return M||(M=kb*50),Cesium.Math.clamp(kb*(M/600),jH,qH)}function a(C){const y=Number(C);if(!Number.isFinite(y))return 1;const v=Cesium.Math.clamp(y,od,Ab);return Math.round(v/Ib)*Ib}function c(C,y,v){return[C,y,v].every(Number.isFinite)?C+Math.max(0,v-y):C}function l(C,y,v,M,w,E=1,k=Date.now(),T=0,I=!0){const R=v+M,S=(k-y)/1e3,A=Math.max(0,Number(T)||0),L=A>0&&S<-A,F=S<0&&!L,P=F?Math.ceil(-S):0,O=Math.max(0,S*a(E)),D=I?O%R:Math.min(O,Math.max(0,R-1e-6)),$=n.paths.orbitInsertionOffsetSeconds(C),x=DI.id===C),v=e._replayTracks.get(C);if(!e._viewer||!y||!v)return!1;if(e._replayCameraLaunchId===C)return m(),!1;n.selection.stopMissionZoomAnchor(),m(),e._replayCameraLaunchId=C,e._replayPaused=!1,e._replayPausedAtMs=null;const M=++e._replayCameraToken,w=v.ascentDurationSec,E=n.camera.replayInitialCameraHeading(v.ascentPath);v.lastCameraHeading=E,u(),n.overlays.syncMissionOverlayEntries(),n.policyHelpers.releaseAircraftTracking(e._dataManager),e._viewer.trackedEntity=void 0,e._viewer.camera.cancelFlight(),e._animationStarts.set(C,Date.now()+(CE+WH)*1e3);let k=!1,T=null;return e._replayCameraRemover=e._viewer.scene.preUpdate.addEventListener(()=>{var V,H;if(M!==e._replayCameraToken||e._replayCameraLaunchId!==C)return;const I=v.beginReplayFrame();if(h(I),!k)return;const R=I.ascending?v.ascentPath:v.animatedOrbitPath,S=n.paths.samplePath(R,I.phaseProgress);if(!S)return;const A=n.camera.cameraHeadingForPath(R,I.phaseProgress,v.lastCameraHeading),L=I.ascending?0:Cesium.Math.clamp((Number(I.phaseProgress)||0)/yE,0,1),F=n.camera.replayChaseCameraHeading(A,L);I.ascending&&(v.orbitCameraWorldFrame=!1);const P=performance.now(),O=Number.isFinite(T)?Cesium.Math.clamp(P-T,4,50):1e3/60;T=P,v.lastCameraHeading=n.camera.smoothReplayCameraHeading(v.lastCameraHeading,F,Cesium.Math.toRadians(2)*O/(1e3/60));const D=Cesium.Ellipsoid.WGS84.cartesianToCartographic(S),$=Math.max(0,(D==null?void 0:D.height)||0),x=n.camera.replayCameraView(I,$),N=I.ascending?S:n.camera.replayOrbitGlobeAnchor(S,L),G=I.ascending?N:n.camera.replayOrbitCameraTarget(N,(V=v.orbitFrameSphere)==null?void 0:V.center,L),W=I.ascending?x.range:n.camera.replayOrbitGlobeRange(x.range,$,L,(H=v.orbitFrameSphere)==null?void 0:H.radius);if(I.ascending)e._viewer.camera.lookAt(G,new Cesium.HeadingPitchRange(v.lastCameraHeading,x.pitch,W));else{const B=Math.max(.002,.8/Math.max(2,R.length-1)),q=Math.min(1,I.phaseProgress+B),z=n.paths.samplePath(R,q>I.phaseProgress?q:Math.max(0,I.phaseProgress-B)),j=n.camera.replayOrbitCameraPose(S,z,G,W,x.pitch);j&&(v.orbitCameraWorldFrame||(e._viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY),v.orbitCameraWorldFrame=!0),e._viewer.camera.setView({destination:j.destination,orientation:{direction:j.direction,up:j.up}}))}I.elapsedSinceStart>=w+bE&&m()}),e._viewer.camera.flyToBoundingSphere(new Cesium.BoundingSphere(v.ascentPath[0],0),{offset:new Cesium.HeadingPitchRange(E,Cesium.Math.toRadians(-20),Nh),duration:1.4,easingFunction:Cesium.EasingFunction.CUBIC_IN_OUT,complete:()=>{k=!0},cancel:()=>{M===e._replayCameraToken&&e._replayCameraLaunchId===C&&m()}}),!0}return{replayVehicleScreenRotation:o,smoothReplayWindowPosition:r,replayAscentDurationSeconds:s,normalizeReplaySpeed:a,replayStartAfterPause:c,replayState:l,syncReplayButton:u,syncReplayCountdownButton:h,syncReplaySpeedControl:d,setReplaySpeed:f,replayClockNow:p,pauseMissionReplay:g,resumeMissionReplay:_,stopMissionReplay:m,startMissionReplay:b}}function f$({state:e,services:t,parts:n,source:i}){function o(v){const M=Number(v);return Math.max(vs,Number.isFinite(M)?M:$m)}function r({preview:v,clear:M}){let w=null,E=null,k=null,T=null;const I=()=>{const R=k==="pointer"?w??E:E??w;R!==T&&(T=R,Number.isInteger(R)?v(R):M())};return{pointerEnter(R){w=R,k="pointer",I()},pointerLeave(){w=null,k==="pointer"&&(k=E===null?null:"focus"),I()},focus(R){E=R,k="focus",I()},blur(R=null){E=Number.isInteger(R)?R:null,k==="focus"&&(k=E===null?w===null?null:"pointer":"focus"),I()},reset(){w=null,E=null,k=null,T=null,M()}}}function s(v,M,w,E){v.addEventListener("mouseenter",()=>w.pointerEnter(M)),v.addEventListener("mouseleave",()=>w.pointerLeave()),v.addEventListener("focus",()=>w.focus(M)),v.addEventListener("blur",k=>{var R,S;const T=(S=(R=k.relatedTarget)==null?void 0:R.closest)==null?void 0:S.call(R,"[data-mission-roster-index]"),I=T&&E.contains(T)?Number(T.dataset.missionRosterIndex):null;w.blur(I)})}function a(v,M=(w=>(w=globalThis.document)==null?void 0:w.activeElement)()){var T;const E=(T=M==null?void 0:M.closest)==null?void 0:T.call(M,"[data-mission-roster-id]");if(!E||!(v!=null&&v.contains(E)))return null;const k=E.dataset.missionRosterId;return k?{launchId:k}:null}function c(v,M,w){var k;if(!(M!=null&&M.launchId))return"none";const E=Array.from(((k=v==null?void 0:v.querySelectorAll)==null?void 0:k.call(v,"[data-mission-roster-id]"))||[]).find(T=>T.dataset.missionRosterId===M.launchId);return E?(E.focus({preventScroll:!0}),"restored"):w!=null&&w.focus?(w.focus({preventScroll:!0}),"continued"):"none"}function l(v,M){return(v||[]).find(w=>w.id===M)||null}function u(v,M,w){return v.length?v.map(E=>E).join(""):`${w}`}function h(v,M,w=""){var I;const E=(I=e._missionPanel)==null?void 0:I.querySelector(v);if(!E)return;const k=E.closest("[data-mission-field]"),T=M!=null&&String(M).trim()!=="";if(k&&(k.hidden=!T),!T){E.textContent="",E.removeAttribute("title");return}E.textContent=M,w?E.title=w:E.removeAttribute("title")}function d(){if(!e._missionPanel)return;const v=e._launches.find(R=>R.id===e._selectedLaunchId),M=v?e._launches.indexOf(v):-1;if(e._missionPanel.hidden=!v,!v)return;e._missionPanel.querySelector("[data-mission-title]").textContent=n.overlays.shortMissionLabel(v.name,32).toUpperCase(),h("[data-mission-provider]",v.provider),h("[data-mission-status]",v.status),h("[data-mission-site]",v.launchSite&&v.launchSite!=="Unknown launch site"?v.launchSite:null),h("[data-mission-time]",v.launchTime);const w=n.policyHelpers.missionPathPresentation(v,e._replayTracks.has(v.id));h("[data-mission-orbit]",w.orbit),e._missionPanel.querySelector("[data-mission-ascent-source]").textContent=w.ascent;const E=v.payloads.length?v.payloads.slice(0,5).map(R=>{var A;const S=[R.manufacturer,R.operator&&R.operator!==R.manufacturer?R.operator:null,Number.isFinite(R.massKg)?`${R.massKg.toLocaleString()} KG`:null].filter(Boolean).join(" · ");return`${p(R.name)}${R.amount>1?` ×${R.amount}`:""}${S?`${p(S)}`:""}${p(R.type||"UNSPECIFIED")}${p(R.destination||((A=v.orbit)==null?void 0:A.name)||"UNAVAILABLE")}`}):[];v.payloads.length>5&&E.push(`+${v.payloads.length-5} additional payload records`),e._missionPanel.querySelector("[data-mission-payloads]").innerHTML=u(E,3,"PAYLOAD DATA UNAVAILABLE");const k=v.recoveryStages.map(R=>{const S=R.endpoint,A=R.destination||((S==null?void 0:S.accuracy)==="PAD / RTLS"?v.launchSite:"UNAVAILABLE"),L=S?`${S.lat.toFixed(2)}, ${S.lon.toFixed(2)} · ${S.accuracy}`:R.downrangeKm>0?`${R.downrangeKm.toLocaleString()} KM DOWNRANGE`:"POSITION UNAVAILABLE",F=[Number.isFinite(R.flightNumber)?`FLIGHT ${R.flightNumber}`:null,R.reused?"REUSED":null,R.recoveryType].filter(Boolean).join(" · ");return`${p(R.name)}${F?`${p(F)}`:""}${p(R.status)}${p(A)}${p(L)}`});e._missionPanel.querySelector("[data-mission-stages]").innerHTML=u(k,3,"NO STAGE RE-ENTRY / RECOVERY DATA");const T=e._missionPanel.querySelector("[data-mission-stages-section]");T&&(T.hidden=k.length===0),g(!0),e._missionPanel.querySelector("[data-mission-index]").textContent=`${M+1} / ${e._launches.length}`,e._missionPanel.querySelector("[data-mission-prev]").disabled=M<=0,e._missionPanel.querySelector("[data-mission-next]").disabled=M<0||M>=e._launches.length-1,n.replay.syncReplayButton();const I=e._missionPanel.closest(".global-context-panel-inner");I&&(I.scrollTop=0)}function f(){var k;if(!e._missionRoster)return;const v=e._missionRoster.querySelector("[data-mission-roster-list]"),M=e._missionRoster.querySelector("[data-mission-roster-count]");if(M&&(M.textContent=`${e._launches.length} / 30D`),!v)return;const w=a(v);(k=e._missionRosterPreviewOwnership)==null||k.reset();const E=n.policyHelpers.missionRosterEntries(e._launches);if(!E.length){v.innerHTML='
NO MISSIONS AVAILABLE IN THE CURRENT 30-DAY WINDOW
',c(v,w,e._missionRoster.querySelector("[data-mission-roster-focus-continuation]"));return}v.innerHTML=E.map(({launch:T,index:I})=>{var F;const R=n.model.missionMarkerColor(T).toCssColorString(),S=((F=T.launchTime)==null?void 0:F.slice(0,10))||"DATE UNAVAILABLE",A=T.provider||"UNSPECIFIED OPERATOR",L=n.overlays.shortMissionLabel(T.name,27).toUpperCase();return``}).join(""),v.querySelectorAll("[data-mission-roster-index]").forEach(T=>{const I=Number(T.dataset.missionRosterIndex);s(T,I,e._missionRosterPreviewOwnership,e._missionRoster)}),c(v,w,e._missionRoster.querySelector("[data-mission-roster-focus-continuation]"))}function p(v){return String(v??"").replace(/[&<>"']/g,M=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[M])}function g(v=!1){var I,R,S;if(!e._missionPanel||!e._selectedLaunchId||!e._dataSource)return;const M=performance.now();if(!v&&M-e._lastPanelTelemetryMs<250)return;e._lastPanelTelemetryMs=M;const w=e._dataSource.entities.getById(`rocket-satellite:${e._selectedLaunchId}`),E=(I=w==null?void 0:w.position)==null?void 0:I.getValue(Cesium.JulianDate.now(e._declutterTime)),k=E?(R=Cesium.Cartographic.fromCartesian(E))==null?void 0:R.height:null;h("[data-mission-distance]",Number.isFinite(k)?`${Math.max(0,k/1e3).toLocaleString(void 0,{maximumFractionDigits:0})} KM`:null);const T=(S=e._satelliteTelemetry.get(e._selectedLaunchId))==null?void 0:S.speedMps;h("[data-mission-speed]",Number.isFinite(T)?`${(T/1e3).toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})} KM/S`:null,Number.isFinite(T)?`${(T*3.6).toLocaleString(void 0,{maximumFractionDigits:0})} km/h`:"")}function _(v){const M=e._launches[v];M&&(n.selection.setSelectedMission(M.id,!0),n.selection.focusMission(M))}function m(){e._missionRosterHoverTimer&&clearTimeout(e._missionRosterHoverTimer),e._missionRosterHoverTimer=null;const v=e._hoveredRosterLaunchId!==null;e._hoveredRosterLaunchId=null,v&&n.overlays.syncMissionOverlayEntries()}function b(){e._missionRosterPreviewOwnership?e._missionRosterPreviewOwnership.reset():m()}function C(v){const M=e._launches[v];!M||e._selectedLaunchId||(e._missionRosterHoverTimer&&clearTimeout(e._missionRosterHoverTimer),e._hoveredRosterLaunchId=M.id,n.overlays.syncMissionOverlayEntries(),e._missionRosterHoverTimer=setTimeout(()=>{if(e._missionRosterHoverTimer=null,e._hoveredRosterLaunchId!==M.id)return;const w=l(e._launches,M.id);w&&n.policyHelpers.previewMissionFromRoster(w)},140))}function y(){if(e._missionPanel||typeof document>"u")return;const v=document.getElementById("space-mission-panel-host")||document.getElementById("right-context-rail");v&&(e._missionRoster=document.getElementById("space-mission-roster"),e._missionRoster&&(e._missionRosterPreviewOwnership=r({preview:C,clear:m}),e._missionRoster.onclick=M=>{const w=M.target instanceof Element?M.target.closest("[data-mission-roster-index]"):null;w&&_(Number(w.dataset.missionRosterIndex))}),e._missionPanel=document.createElement("aside"),e._missionPanel.id="space-mission-panel",e._missionPanel.className="context-space-mission-detail",e._missionPanel.setAttribute("aria-label","Selected Space Mission"),e._missionPanel.innerHTML='
SELECTED SPACE MISSION
MISSIONSTATUS · LAUNCH SITE · LAUNCH TIME · ORBIT · ASCENT PATH · CURRENT DISTANCE FROM EARTH · SATELLITE SPEED ·

PAYLOAD

NAMETYPEDESTINATION

STAGE / RE-ENTRY / RECOVERY

STAGESTATUSFINAL POSITION
1×
—
',e._missionPanel.querySelector(".mission-action-row").insertAdjacentHTML("beforeend",``),v.appendChild(e._missionPanel),e._missionPanel.querySelector("[data-mission-prev]").addEventListener("click",()=>_(e._launches.findIndex(M=>M.id===e._selectedLaunchId)-1)),e._missionPanel.querySelector("[data-mission-next]").addEventListener("click",()=>_(e._launches.findIndex(M=>M.id===e._selectedLaunchId)+1)),e._missionPanel.querySelector("[data-mission-close]").addEventListener("click",()=>n.selection.setSelectedMission(null)),e._missionPanel.querySelector("[data-mission-show-all]").addEventListener("click",()=>n.selection.setSelectedMission(null)),e._missionPanel.querySelector("[data-mission-focus]").addEventListener("click",()=>{const M=e._launches.find(w=>w.id===e._selectedLaunchId);M&&n.selection.focusLaunchSite(M)}),e._missionPanel.querySelector("[data-mission-replay]").addEventListener("click",()=>{e._selectedLaunchId&&n.replay.startMissionReplay(e._selectedLaunchId)}),e._missionPanel.querySelector("[data-mission-replay-toggle]").addEventListener("click",()=>{e._replayPaused?n.replay.resumeMissionReplay():n.replay.pauseMissionReplay()}),e._missionPanel.querySelector("[data-mission-replay-cancel]").addEventListener("click",n.replay.stopMissionReplay),e._missionPanel.querySelector("[data-mission-replay-speed]").addEventListener("input",M=>{n.replay.setReplaySpeed(M.currentTarget.value)}),n.replay.syncReplaySpeedControl())}return{missionHoverPreviewRange:o,createMissionRosterPreviewOwnership:r,bindMissionRosterItemKeyboardPreview:s,captureMissionRosterFocus:a,restoreMissionRosterFocus:c,resolveMissionRosterPreviewLaunch:l,missionTableRows:u,setMissionPanelField:h,renderMissionPanel:d,renderMissionRoster:f,escapeMissionText:p,updateMissionTelemetry:g,selectMissionAt:_,clearMissionRosterPreviewState:m,clearMissionRosterHover:b,scheduleMissionRosterPreview:C,createMissionPanel:y}}function m$({state:e,services:t,parts:n,source:i}){function o(C){const y=(C.timeline||[]).filter(w=>Number.isFinite(w.offsetSeconds)&&w.offsetSeconds>=0);if(!y.length)return null;const v=y.filter(w=>/deploy|payload separation|spacecraft separation|orbit insertion|injection/i.test(w.name));if(v.length)return Math.max(...v.map(w=>w.offsetSeconds));const M=y.filter(w=>/seco|second engine cutoff/i.test(w.name));return M.length?Math.max(...M.map(w=>w.offsetSeconds)):Math.max(...y.map(w=>w.offsetSeconds))}function r(C){if(!(C!=null&&C.length))return 5400;const y=C.reduce((v,M)=>v+Cesium.Cartesian3.magnitude(M),0)/C.length;return 2*Math.PI*Math.sqrt(y**3/3986004418e5)}function s(C){var x;if(!((x=C.orbit)!=null&&x.name)||!Number.isFinite(C.lat)||!Number.isFinite(C.lon))return null;const y=C.orbit.name.toLowerCase(),v=y.includes("geostationary")||y.includes("transfer")?35786e3:y.includes("medium")?202e5:55e4,M=Cesium.Ellipsoid.WGS84.maximumRadius+v,w=Cesium.Math.toRadians(C.lon),E=Cesium.Math.toRadians(C.lat),k=new Cesium.Cartesian3(Math.cos(E)*Math.cos(w),Math.cos(E)*Math.sin(w),Math.sin(E)),T=new Cesium.Cartesian3(-Math.sin(w),Math.cos(w),0),I=new Cesium.Cartesian3(-Math.sin(E)*Math.cos(w),-Math.sin(E)*Math.sin(w),Math.cos(E)),R=y.includes("polar")||y.includes("sun"),S=C.lat>20&&C.lat<60&&C.lon>-140&&C.lon<-105,A=R?C.lat>=0?180:0:S?190:90,L=Cesium.Math.toRadians(A),F=Cesium.Cartesian3.normalize(Cesium.Cartesian3.add(Cesium.Cartesian3.multiplyByScalar(I,Math.cos(L),new Cesium.Cartesian3),Cesium.Cartesian3.multiplyByScalar(T,Math.sin(L),new Cesium.Cartesian3),new Cesium.Cartesian3),new Cesium.Cartesian3),P=Cesium.Math.toRadians(R?8:12),O=Cesium.Cartesian3.normalize(Cesium.Cartesian3.add(Cesium.Cartesian3.multiplyByScalar(k,Math.cos(P),new Cesium.Cartesian3),Cesium.Cartesian3.multiplyByScalar(F,Math.sin(P),new Cesium.Cartesian3),new Cesium.Cartesian3),new Cesium.Cartesian3),D=Cesium.Cartesian3.normalize(Cesium.Cartesian3.cross(O,F,new Cesium.Cartesian3),new Cesium.Cartesian3),$=Cesium.Cartesian3.normalize(Cesium.Cartesian3.cross(D,O,new Cesium.Cartesian3),new Cesium.Cartesian3);return Array.from({length:97},(N,G)=>{const W=G/96*Math.PI*2;return new Cesium.Cartesian3(M*(Math.cos(W)*O.x+Math.sin(W)*$.x),M*(Math.cos(W)*O.y+Math.sin(W)*$.y),M*(Math.cos(W)*O.z+Math.sin(W)*$.z))})}function a(C,y,v){if(!(C!=null&&C.length))return;if(C.length===1)return v?Cesium.Cartesian3.clone(C[0],v):C[0];let M=e._pathDistanceCache.get(C);if(!M){M=new Float64Array(C.length);for(let A=1;A0))return v?Cesium.Cartesian3.clone(C[0],v):C[0];const E=Cesium.Math.clamp(y,0,1)*w;let k=1,T=M.length-1;for(;k0?(E-M[I])/R:0;return Cesium.Cartesian3.lerp(C[I],C[I+1],S,v||new Cesium.Cartesian3)}function c(C,y){const v=Math.max(1,Number(y)||1);return Cesium.Math.mod((Number(C)||0)/1e3,v)/v}function l(C,y,v=512){const M=Cesium.Ellipsoid.WGS84,w=M.cartesianToCartographic(C),E=M.cartesianToCartographic(y);if(!w||!E)return[C,y];const k=new Cesium.EllipsoidGeodesic(new Cesium.Cartographic(w.longitude,w.latitude),new Cesium.Cartographic(E.longitude,E.latitude),M);return Array.from({length:v+1},(T,I)=>{const R=I/v;if(I===0)return C;if(I===v)return y;const S=R**4,A=k.interpolateUsingFraction(S,new Cesium.Cartographic),L=i$*o$*Math.sin(Math.PI*R**3);return A.longitude=Cesium.Math.negativePiToPi(A.longitude+L),A.height=Cesium.Math.lerp(Math.max(0,w.height),Math.max(0,E.height),Math.sin(R*Cesium.Math.PI_OVER_TWO)),M.cartographicToCartesian(A)})}function u(C,y){if(!(C!=null&&C.length)||!y)return 0;const v=Cesium.Cartesian3.normalize(y,new Cesium.Cartesian3);let M=0,w=-Number.MAX_VALUE;return C.forEach((E,k)=>{const T=Cesium.Cartesian3.normalize(E,new Cesium.Cartesian3),I=Cesium.Cartesian3.dot(v,T);I>w&&(w=I,M=k)}),M}function h(C,y){if(!(C!=null&&C.length))return[];const v=C[0],M=C.at(-1),E=C.length>2&&Cesium.Cartesian3.distance(v,M)<1e3?C.slice(0,-1):C.slice();if(!E.length)return C.slice();const k=Cesium.Math.mod(y,E.length),T=[...E.slice(k),...E.slice(0,k)];return T.push(T[0]),T}function d(C,y){const v=Cesium.Ellipsoid.WGS84,M=v.cartesianToCartographic(C),w=v.cartesianToCartographic(y);if(!M||!w)return[C,y];const E=new Cesium.EllipsoidGeodesic(new Cesium.Cartographic(M.longitude,M.latitude),new Cesium.Cartographic(w.longitude,w.latitude),v),k=Cesium.Math.clamp(Math.ceil(E.surfaceDistance/75e3),2,256),T=[];for(let I=0;I<=k;I++){const R=I/k,S=R*R*(3-2*R),A=E.interpolateUsingFraction(R,new Cesium.Cartographic);A.height=Cesium.Math.lerp(M.height,w.height,S),T.push(v.cartographicToCartesian(A))}return T[0]=C,T[T.length-1]=y,T}function f(C){if(!(C!=null&&C.length))return[];if(C.length===1)return C.slice();const y=[];for(let v=0;v{var x;return Math.max(0,((x=M.cartesianToCartographic($))==null?void 0:x.height)||0)}),L=Cesium.Cartesian3.normalize(Cesium.Cartesian3.subtract(R,S,new Cesium.Cartesian3),new Cesium.Cartesian3),P=Math.max(Cesium.Cartesian3.distance(R,w),1e3)*.28,O=Cesium.Cartesian3.add(R,Cesium.Cartesian3.multiplyByScalar(L,P,new Cesium.Cartesian3),new Cesium.Cartesian3),D=Cesium.Cartesian3.add(w,Cesium.Cartesian3.multiplyByScalar(k,-P,new Cesium.Cartesian3),new Cesium.Cartesian3);for(let $=0;$<=T;$++){const x=$/T,N=1-x,G=new Cesium.Cartesian3;Cesium.Cartesian3.multiplyByScalar(R,N**3,G),Cesium.Cartesian3.add(G,Cesium.Cartesian3.multiplyByScalar(O,3*N**2*x,new Cesium.Cartesian3),G),Cesium.Cartesian3.add(G,Cesium.Cartesian3.multiplyByScalar(D,3*N*x**2,new Cesium.Cartesian3),G),Cesium.Cartesian3.add(G,Cesium.Cartesian3.multiplyByScalar(w,x**3,new Cesium.Cartesian3),G);const W=M.cartesianToCartographic(G),V=A[$]??0;W&&W.height0)||!v)return null;const w=Cesium.Ellipsoid.WGS84,E=Cesium.Cartographic.fromDegrees(y.lon,y.lat),k=w.cartesianToCartographic(v);if(!k)return null;const I=new Cesium.EllipsoidGeodesic(E,k,w).startHeading,R=C.downrangeKm*1e3/w.maximumRadius,S=E.latitude,A=E.longitude,L=Math.asin(Math.sin(S)*Math.cos(R)+Math.cos(S)*Math.sin(R)*Math.cos(I)),F=A+Math.atan2(Math.sin(I)*Math.sin(R)*Math.cos(S),Math.cos(R)-Math.sin(S)*Math.sin(L));return{lat:Cesium.Math.toDegrees(L),lon:Cesium.Math.toDegrees(Cesium.Math.negativePiToPi(F)),accuracy:"EST. DOWNRANGE"}}function m(C,y,v,M){if(!(C!=null&&C.length)||!y)return[];const w=Cesium.Math.clamp(.28+v/Math.max(M,1)*.34,.28,.68),E=a(C,w),k=Cesium.Cartesian3.fromDegrees(y.lon,y.lat,12);return d(E,k)}function b(C){var v,M;if(!(C!=null&&C.length))return 0;const y=Cesium.Ellipsoid.WGS84;for(let w=1;wDh&&k<=Dh)return w}return Math.min(Math.max(Math.round(C.length*.55),0),C.length-1)}return{orbitInsertionOffsetSeconds:o,estimatedOrbitPeriodSeconds:r,approximateOrbitPath:s,samplePath:a,orbitProgressAtTime:c,reconstructedAscentPath:l,nearestOrbitIndex:u,orbitPathFromInsertion:h,surfaceSafeSegment:d,surfaceSafePath:f,blendAscentIntoOrbitTangent:p,buildMissionPaths:g,landingEndpoint:_,stageReentryRecoveryPath:m,atmosphericReentryIndex:b}}function p$({state:e,services:t,parts:n,source:i}){function o(){e._launchPadZonePrimitive&&(e._launchPadZonePrimitive.show=!1)}function r(){var l,u;e._launchPadZonePrimitive&&((u=(l=e._viewer)==null?void 0:l.scene)!=null&&u.primitives)&&e._viewer.scene.primitives.remove(e._launchPadZonePrimitive),e._launchPadZonePrimitive=null,e._launchPadZoneLaunchId=null}function s(l){r();const u=new Cesium.Material({fabric:{type:"GevLaunchPadZone",uniforms:{color:Cesium.Color.fromCssColorString("#22e6e6"),fillAlpha:.105,rimAlpha:.72},source:` + czm_material czm_getMaterial(czm_materialInput materialInput) { + czm_material material = czm_getDefaultMaterial(materialInput); + vec2 centered = (materialInput.st - vec2(0.5)) * 2.0; + float radius = length(centered); + float inside = 1.0 - smoothstep(0.985, 1.0, radius); + float rim = smoothstep(0.952, 0.985, radius) * inside; + material.diffuse = color.rgb; + material.emission = color.rgb * rim * 0.35; + material.alpha = color.a * inside * mix(fillAlpha, rimAlpha, rim); + return material; + }`}}),h=new Cesium.EllipseGeometry({center:Cesium.Cartesian3.fromDegrees(l.lon,l.lat),semiMajorAxis:Pb,semiMinorAxis:Pb,granularity:Cesium.Math.toRadians(.08),vertexFormat:Cesium.MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat});e._launchPadZonePrimitive=e._viewer.scene.primitives.add(new Cesium.GroundPrimitive({geometryInstances:new Cesium.GeometryInstance({geometry:h,id:`rocket-pad-zone:${l.id}`}),appearance:new Cesium.MaterialAppearance({material:u,translucent:!0,closed:!1,faceForward:!0,flat:!0,renderState:{depthTest:{enabled:!0},depthMask:!1,polygonOffset:{enabled:!0,factor:-1,units:-4},blending:Cesium.BlendingState.ALPHA_BLEND}}),classificationType:Cesium.ClassificationType.BOTH,asynchronous:!0,show:!0})),e._launchPadZoneLaunchId=l.id}function a(){!e._viewer||e._launchPadZoneRemover||(e._launchPadZoneRemover=e._viewer.scene.preRender.addEventListener(()=>{var p,g,_,m;if(!e._enabled||!((p=e._dataSource)!=null&&p.show)){o();return}const l=Date.now();l-e._lastMissionRingRotationMs>=1e3&&(e._missionRingDate.setTime(l),n.orbitRendering.updateMissionOrbitPrimitiveFrames(e._missionRingDate),e._lastMissionRingRotationMs=l);const u=e._launches.find(b=>b.id===e._selectedLaunchId),h=(g=e._viewer)==null?void 0:g.camera;if(!u||!h){o();return}const d=Cesium.Cartesian3.fromDegrees(u.lon,u.lat);if(!n.policyHelpers.launchPadZoneVisible({layerActive:!!((_=e._dataSource)!=null&&_.show),selectedLaunchId:e._selectedLaunchId,launchId:u.id,cameraHeightM:(m=h.positionCartographic)==null?void 0:m.height,cameraDistanceM:Cesium.Cartesian3.distance(h.positionWC,d)})){o();return}e._launchPadZoneLaunchId!==u.id&&s(u),e._launchPadZonePrimitive.show=!0}))}function c(){e._launchPadZoneRemover&&e._launchPadZoneRemover(),e._launchPadZoneRemover=null,r()}return{hideLaunchPadZone:o,removeLaunchPadZonePrimitive:r,createLaunchPadZonePrimitive:s,initLaunchPadZonePrimitive:a,destroyLaunchPadZonePrimitive:c}}function g$({state:e,services:t,parts:n,source:i}){function o(g,_,m=Math.PI){if(!(g!=null&&g.length))return m;const b=n.paths.samplePath(g,_),C=Cesium.Ellipsoid.WGS84.cartesianToCartographic(b);if(!C)return m;for(const y of[.01,.025,.05,.1,.2]){const v=n.paths.samplePath(g,Math.min(1,_+y)),M=Cesium.Ellipsoid.WGS84.cartesianToCartographic(v);if(!M)continue;const w=new Cesium.EllipsoidGeodesic(C,M);if(w.surfaceDistance>10&&Number.isFinite(w.startHeading))return Cesium.Math.zeroToTwoPi(w.startHeading)}return m}function r(g){return Cesium.Math.zeroToTwoPi(o(g,0,Math.PI)+Cesium.Math.PI_OVER_TWO)}function s(g,_=0){const m=Cesium.Math.clamp(Number(_)||0,0,1);return Cesium.Math.zeroToTwoPi(g+Cesium.Math.lerp(ZH,JH,m))}function a(g,_,m=Cesium.Math.toRadians(2)){if(!Number.isFinite(g))return Cesium.Math.zeroToTwoPi(_);if(!Number.isFinite(_))return Cesium.Math.zeroToTwoPi(g);const b=Cesium.Math.negativePiToPi(_-g),C=Cesium.Math.clamp(b,-Math.abs(m),Math.abs(m));return Cesium.Math.zeroToTwoPi(g+C)}function c(g){const _=Math.max(0,Number(g)||0),m=Cesium.Math.clamp((Math.log(Math.max(_,vs))-Math.log(vs))/(Math.log($m)-Math.log(vs)),0,1);return Cesium.Math.lerp(Cesium.Math.toRadians(-42),-Cesium.Math.PI_OVER_TWO,m)}function l(g,_){const m=Math.max(0,Number(_)||0),b=Cesium.Math.clamp(Nh+m*.7,Nh,KH),C=Cesium.Math.clamp((m-2e4)/(XH-2e4),0,1),y=C*C*(3-2*C),v=Cesium.Math.clamp(18e4+m*3.8,vs,YH),M=Cesium.Math.lerp(b,v,y),w=Cesium.Math.lerp(Cesium.Math.toRadians(-20),Cesium.Math.toRadians(-34),y);if(g!=null&&g.ascending)return{range:M,pitch:w};const E=Cesium.Math.clamp((Number(g==null?void 0:g.phaseProgress)||0)/yE,0,1),k=E*E*(3-2*E);return{range:Cesium.Math.lerp(M,QH,k),pitch:Cesium.Math.lerp(w,Cesium.Math.toRadians(-45),k)}}function u(g,_=0){if(!g)return g;const m=Cesium.Math.clamp(Number(_)||0,0,1);if(m<=0)return Cesium.Cartesian3.clone(g);const b=Cesium.Ellipsoid.WGS84.cartesianToCartographic(g);if(!b)return Cesium.Cartesian3.clone(g);const C=Math.max(0,b.height||0);return Cesium.Cartesian3.fromRadians(b.longitude,b.latitude,Cesium.Math.lerp(C,C*.1,m))}function h(g,_,m=0){if(!g)return g;if(!_)return Cesium.Cartesian3.clone(g);const b=Cesium.Math.clamp(Number(m)||0,0,1)*e$;return Cesium.Cartesian3.lerp(g,_,b,new Cesium.Cartesian3)}function d(g,_,m,b,C){if(!g||!_||!m)return null;const y=Cesium.Cartesian3.normalize(Cesium.Cartesian3.clone(g),new Cesium.Cartesian3),v=Cesium.Cartesian3.subtract(_,g,new Cesium.Cartesian3);if(Cesium.Cartesian3.magnitudeSquared(v)<1)return null;Cesium.Cartesian3.normalize(v,v);const M=Cesium.Cartesian3.cross(y,v,new Cesium.Cartesian3);if(Cesium.Cartesian3.magnitudeSquared(M)<1e-12)return null;Cesium.Cartesian3.normalize(M,M);const w=Math.max(1,Number(b)||1),E=Cesium.Math.clamp(Math.abs(Number(C)||0),Cesium.Math.toRadians(5),Cesium.Math.toRadians(80)),k=Cesium.Cartesian3.multiplyByScalar(M,Math.cos(E)*w,new Cesium.Cartesian3),T=Cesium.Cartesian3.multiplyByScalar(y,Math.sin(E)*w,new Cesium.Cartesian3),I=Cesium.Cartesian3.add(m,k,new Cesium.Cartesian3);Cesium.Cartesian3.add(I,T,I);const R=Cesium.Cartesian3.normalize(Cesium.Cartesian3.subtract(m,I,new Cesium.Cartesian3),new Cesium.Cartesian3),S=Cesium.Cartesian3.multiplyByScalar(R,Cesium.Cartesian3.dot(y,R),new Cesium.Cartesian3),A=Cesium.Cartesian3.normalize(Cesium.Cartesian3.subtract(y,S,new Cesium.Cartesian3),new Cesium.Cartesian3);return{destination:I,direction:R,up:A}}function f(g=[]){const _=new Cesium.BoundingSphere(Cesium.Cartesian3.ZERO,Cesium.Ellipsoid.WGS84.maximumRadius);if(!Array.isArray(g)||g.length<2)return _;const m=Cesium.BoundingSphere.fromPoints(g);return Cesium.BoundingSphere.union(_,m,new Cesium.BoundingSphere)}function p(g,_,m=0,b=0){const C=Math.max(0,Number(g)||0),y=Math.max(0,Number(_)||0),v=Math.max(0,Number(b)||0),M=Cesium.Math.clamp(Number(m)||0,0,1),w=Math.max(C,y+Cesium.Ellipsoid.WGS84.maximumRadius*2.4,v*3);return Cesium.Math.lerp(C,w,M)}return{cameraHeadingForPath:o,replayInitialCameraHeading:r,replayChaseCameraHeading:s,smoothReplayCameraHeading:a,missionZoomPitch:c,replayCameraView:l,replayOrbitGlobeAnchor:u,replayOrbitCameraTarget:h,replayOrbitCameraPose:d,replayOrbitFrameSphere:f,replayOrbitGlobeRange:p}}function _$({state:e,services:t,parts:n,source:i}){function o(u){const h=Number(u);return Number.isFinite(h)?h:null}function r(u){var d,f;const h=((d=u.rocket)==null?void 0:d.payloads)||u.payloads||((f=u.mission)==null?void 0:f.payloads)||[];return Array.isArray(h)?h.map((p,g)=>{var m,b,C,y;const _=p.payload||p;return{id:String(p.id||_.id||`payload-${g}`),name:_.name||p.name||"Unnamed payload",type:((m=_.type)==null?void 0:m.name)||((b=p.type)==null?void 0:b.name)||null,manufacturer:((C=_.manufacturer)==null?void 0:C.name)||null,operator:((y=_.operator)==null?void 0:y.name)||null,destination:p.destination||_.destination||null,amount:Number.isFinite(Number(p.amount))?Number(p.amount):1,massKg:(typeof _.mass=="number"||typeof _.mass=="string"&&_.mass.trim()!=="")&&Number.isFinite(Number(_.mass))&&Number(_.mass)>=0?Number(_.mass):null}}):[]}function s(u,h,d,f){var E,k,T,I;const p=u==null?void 0:u.landing,g=(p==null?void 0:p.landing_location)||{},_=(u==null?void 0:u.launcher)||(u==null?void 0:u.spacecraft)||{},m=_.serial_number||(u==null?void 0:u.serial_number)||null,b=((E=u==null?void 0:u.type)==null?void 0:E.name)||(u==null?void 0:u.type)||d,C=(p==null?void 0:p.attempt)===!0,y=p==null?void 0:p.success,v=((k=p==null?void 0:p.type)==null?void 0:k.name)||null,M=((T=_.status)==null?void 0:T.name)||null,w=y===!0?"RECOVERED":y===!1?"LOST":C?"RECOVERY ATTEMPT":v?v.toUpperCase():M?M.toUpperCase():"NO RECOVERY DATA";return{id:String((u==null?void 0:u.id)||(p==null?void 0:p.id)||`${d}-${f}`),category:d,name:[b,m].filter(Boolean).join(" · ")||h,serial:m,reused:(u==null?void 0:u.reused)===!0,flightNumber:o(u==null?void 0:u.launcher_flight_number),status:w,attempted:C,success:y===!0?!0:y===!1?!1:null,recoveryType:v,destination:g.name||(p==null?void 0:p.destination)||((I=p==null?void 0:p.type)==null?void 0:I.name)||null,description:(p==null?void 0:p.description)||null,downrangeKm:o(p==null?void 0:p.downrange_distance),lat:o(g.latitude??(p==null?void 0:p.latitude)),lon:o(g.longitude??(p==null?void 0:p.longitude))}}function a(u,h){const d=u.rocket||{},f=Array.isArray(d.launcher_stage)?d.launcher_stage:[],p=Array.isArray(d.spacecraft_stage)?d.spacecraft_stage:[],g=[...f.map((m,b)=>s(m,`Launcher stage ${b+1}`,"LAUNCHER",b)),...p.map((m,b)=>s(m,`Spacecraft stage ${b+1}`,"SPACECRAFT",b))],_=d.payloads||u.payloads||[];return Array.isArray(_)&&_.forEach((m,b)=>{var C,y,v;m!=null&&m.landing&&g.push(s({...m,type:((C=h[b])==null?void 0:C.type)||"Payload",serial_number:(y=h[b])==null?void 0:y.name},((v=h[b])==null?void 0:v.name)||`Payload ${b+1}`,"PAYLOAD",b))}),g}function c(u){const h=`${u.provider||""} ${u.name||""} ${u.missionName||""}`.toLowerCase();return/nasa|national aeronautics/.test(h)?Cesium.Color.fromCssColorString("#ff9f43"):/starlink|spacex|space exploration/.test(h)?Cesium.Color.fromCssColorString("#4cc9f0"):/rocket lab/.test(h)?Cesium.Color.fromCssColorString("#7bed9f"):/isro|indian space/.test(h)?Cesium.Color.fromCssColorString("#ff66c4"):/cnsa|china national|long march/.test(h)?Cesium.Color.fromCssColorString("#ffd166"):/blue origin/.test(h)?Cesium.Color.fromCssColorString("#a78bfa"):/ula|united launch alliance/.test(h)?Cesium.Color.fromCssColorString("#f97316"):/arianespace|esa|european space/.test(h)?Cesium.Color.fromCssColorString("#60a5fa"):u.provider?Cesium.Color.fromCssColorString("#c084fc"):Cesium.Color.fromCssColorString("#22e6e6")}function l(u,h=new Date){const d=Array.isArray(u)?u:u==null?void 0:u.results;if(!Array.isArray(d))return[];const f=h.getTime()-$H*864e5;return d.map(p=>{var k,T,I,R,S,A,L,F;const g=p.net||p.window_start||((T=(k=p.pad)==null?void 0:k.location)==null?void 0:T.name),_=Date.parse(g),m=p.pad||{},b=m.location||{},C=b.coordinates||"",[y,v]=String(C).split(",").map(Number),M=Number.isFinite(Number(m.latitude))?Number(m.latitude):v,w=Number.isFinite(Number(m.longitude))?Number(m.longitude):y,E=r(p);return{id:String(p.id||p.slug||p.name||`launch-${_}`),name:p.name||"Unnamed launch",status:((I=p.status)==null?void 0:I.name)||"Unknown",launchTime:Number.isFinite(_)?new Date(_).toISOString():null,launchSite:m.name||b.name||"Unknown launch site",lat:Number.isFinite(M)?M:null,lon:Number.isFinite(w)?w:null,provider:((R=p.launch_service_provider)==null?void 0:R.name)||null,mission:((S=p.mission)==null?void 0:S.description)||null,missionName:((A=p.mission)==null?void 0:A.name)||null,satelliteQuery:((L=p.mission)==null?void 0:L.name)||p.name||null,payloads:E,recoveryStages:a(p,E),trajectory:Array.isArray(p.trajectory)?p.trajectory:[],timeline:Array.isArray(p.timeline)?p.timeline.map(P=>{var O,D;return{name:((O=P.type)==null?void 0:O.abbrev)||((D=P.type)==null?void 0:D.name)||P.name||"Mission event",relativeTime:P.relative_time||P.relativeTime||null,offsetSeconds:n.policyHelpers.parseMissionDurationSeconds(P.relative_time||P.relativeTime)}}):[],orbit:((F=p.mission)==null?void 0:F.orbit)||p.orbit||null,source:"Launch Library 2",inWindow:Number.isFinite(_)&&_>=f&&_<=h.getTime()}}).filter(p=>p.inWindow&&p.lat!==null&&p.lon!==null)}return{finiteCoordinate:o,normalizePayloadFlights:r,normalizeLanding:s,normalizeRecoveryStages:a,missionMarkerColor:c,normalizeRocketLaunches:l}}function b$({state:e,services:t,parts:n,source:i}){const{getSatelliteOrbitTrack:o,findSatelliteOrbitTrackInTle:r}=t.satellites;function s(l,u,h){var p,g;if(!l)return;const d=!!u;((g=(p=l.show)==null?void 0:p.getValue)==null?void 0:g.call(p,h))!==d&&(l.show=d)}function a(){var u;if(!e._enabled||!e._viewer||!((u=e._dataSource)!=null&&u.show)){n.overlays.hideReplayVehicleOverlay();return}n.panel.updateMissionTelemetry();const l=Cesium.JulianDate.now(e._declutterTime);e._declutterOccluder.cameraPosition=e._viewer.scene.camera.positionWC,n.overlays.updateReplayVehicleOverlay(e._declutterOccluder),n.overlays.refreshSelectedMissionOverlayText();for(const h of e._dataSource.entities.values){if(!h.show||!h.position)continue;const d=n.selection.entityLaunchId(h);if(!d)continue;const f=h.position.getValue(l);let p=!!(f&&e._declutterOccluder.isPointVisible(f));const g=h.id.startsWith("rocket-launch:");g&&(p=n.overlays.missionAnchorVisible(e._viewer.scene.camera.positionWC,f,d,e._selectedLaunchId)),h.point&&s(h.point,p,l),g&&h.billboard&&s(h.billboard,p&&d===e._hoveredRosterLaunchId,l)}}function c(l,u=e._activeTleText){var b,C;const h=Cesium.Cartesian3.fromDegrees(l.lon,l.lat),d={launch:l,anchorPosition:h,elementEntryFactories:[],liveEventTime:null};e._missionOverlayRecords.set(l.id,d);const f=n.policyHelpers.launchStatusAllowsOrbit(l.status),g=(f&&l.satelliteQuery?o(l.satelliteQuery,{launchTime:l.launchTime}):null)||(f&&u&&l.satelliteQuery?r(u,l.satelliteQuery,{launchTime:l.launchTime}):null),_=f?((b=g==null?void 0:g.orbitPath)==null?void 0:b.length)>1?g.orbitPath:n.paths.approximateOrbitPath(l):null;l.recoveryStages.forEach(y=>{y.endpoint=n.paths.landingEndpoint(y,l,(_==null?void 0:_[0])||null)}),g&&e._orbitMatches++,e._dataSource.entities.add({id:`rocket-launch:${l.id}`,position:h,point:{pixelSize:5,color:n.model.missionMarkerColor(l),outlineColor:n.model.missionMarkerColor(l),outlineWidth:0,disableDepthTestDistance:Number.POSITIVE_INFINITY},billboard:{image:n.overlays.missionHoverReticleImage(),width:24,height:24,show:!1,horizontalOrigin:Cesium.HorizontalOrigin.CENTER,verticalOrigin:Cesium.VerticalOrigin.CENTER,disableDepthTestDistance:Number.POSITIVE_INFINITY},properties:{launchId:l.id,launchName:l.name,launchTime:l.launchTime,launchSite:l.launchSite,provider:l.provider,mission:l.mission,status:l.status,source:l.source,orbit:JSON.stringify(l.orbit||{}),satelliteName:(g==null?void 0:g.name)||"",noradId:(g==null?void 0:g.noradId)||""}});const m=l.trajectory.filter(y=>Number.isFinite(Number(y.latitude))&&Number.isFinite(Number(y.longitude))).map(y=>({stage:String(y.stage||y.stage_name||y.phase||y.stageName||"trajectory"),position:Cesium.Cartesian3.fromDegrees(Number(y.longitude),Number(y.latitude),Number(y.altitude||0))}));if(m.length>1){const y=[];m.forEach(v=>{const M=y.at(-1);(!M||M.stage!==v.stage)&&y.push({stage:v.stage,positions:[]}),y.at(-1).positions.push(v.position)}),y.forEach((v,M)=>{v.positions.length<2||e._dataSource.entities.add({id:`rocket-trajectory:${l.id}:${M}`,polyline:{positions:n.paths.surfaceSafePath(v.positions),width:2,material:Cesium.Color.fromCssColorString(za[M%za.length]).withAlpha(.8),clampToGround:!1,arcType:Cesium.ArcType.NONE},properties:{launchId:l.id,stage:v.stage,source:l.source}})})}if((_==null?void 0:_.length)>1){const y=(g==null?void 0:g.current)||{longitude:l.lon,latitude:l.lat,altitude:0},v=(g==null?void 0:g.periodSec)||n.paths.estimatedOrbitPeriodSeconds(_),M=Date.parse(l.launchTime),w=n.paths.orbitInsertionOffsetSeconds(l),E=Number.isFinite(w)?Math.max(0,w):600,k=Number.isFinite(M)?M+E*1e3:Number.NaN;let T=((C=m.at(-1))==null?void 0:C.position)||null;if(!T&&(g!=null&&g.positionAt)&&Number.isFinite(k)){const z=g.positionAt(new Date(k));z&&(T=Cesium.Cartesian3.fromDegrees(z.longitude,z.latitude,z.altitude))}if(!T&&!g){const z=Cesium.Math.clamp(E/v,.010416666666666666,.16);T=n.paths.samplePath(_,z)}const{ascentPath:I,animatedOrbitPath:R}=n.paths.buildMissionPaths(h,m.map(z=>z.position),_,T),S=n.replay.replayAscentDurationSeconds(l,I);let A=null;const L=()=>n.replay.replayState(l,e._animationStarts.get(l.id)||Date.now(),S,bE,v,e._replaySpeed,n.replay.replayClockNow(l.id),CE,e._replayCameraLaunchId!==l.id),F=()=>(A=L(),A),P=()=>(A||(A=L()),A);l.recoveryStages.forEach((z,j)=>{z.endpoint=n.paths.landingEndpoint(z,l,I.at(-1));const ne=n.paths.stageReentryRecoveryPath(I,z.endpoint,j,l.recoveryStages.length);if(ne.length<2)return;const ee=n.paths.atmosphericReentryIndex(ne),re=ne.slice(ee),se=Cesium.Color.fromCssColorString(za[(j+1)%za.length]);if(e._dataSource.entities.add({id:`rocket-reentry-recovery:${l.id}:${j}`,polyline:{positions:ne,width:2,material:new Cesium.PolylineDashMaterialProperty({color:se.withAlpha(.82),dashLength:12,dashPattern:43690}),arcType:Cesium.ArcType.NONE},properties:{launchId:l.id,stageId:z.id,phase:"STAGE_REENTRY_RECOVERY",accuracy:z.endpoint.accuracy,source:l.source}}),re.length>1){e._dataSource.entities.add({id:`rocket-reentry:${l.id}:${j}`,polyline:{positions:re,width:2.5,material:new Cesium.PolylineDashMaterialProperty({color:Cesium.Color.fromCssColorString("#ffd166").withAlpha(.9),dashLength:8,dashPattern:61680}),arcType:Cesium.ArcType.NONE},properties:{launchId:l.id,stageId:z.id,phase:"ATMOSPHERIC_REENTRY",altitudeM:Dh,source:"Estimated 100 km atmospheric interface"}});const me=ne[ee];d.elementEntryFactories.push(()=>n.overlays.createRocketMissionElementOverlayEntry({id:`reentry:${l.id}:${j}`,position:me,text:"STAGE RE-ENTRY",accent:"#ffd166",priority:7e5-j,gapPx:8}))}e._dataSource.entities.add({id:`rocket-recovery-end:${l.id}:${j}`,position:ne.at(-1),point:{pixelSize:4,color:se,outlineWidth:0,disableDepthTestDistance:Number.POSITIVE_INFINITY},properties:{launchId:l.id,stageId:z.id,phase:"RECOVERY_ENDPOINT",source:l.source}})}),e._replayTracks.set(l.id,{ascentPath:I,animatedOrbitPath:R,orbitFrameSphere:n.camera.replayOrbitFrameSphere(R),ascentDurationSec:S,beginReplayFrame:F,getReplayState:P,lastCameraHeading:Math.PI,orbitCameraWorldFrame:!1,lastVehicleRotation:0,lastOverlayWindowPosition:null,lastOverlayMode:null});let O=Cesium.Cartesian3.fromDegrees(y.longitude,y.latitude,y.altitude);const D=new Date,$={speedMps:null};e._satelliteTelemetry.set(l.id,$);let x=-1;const N=n.paths.estimatedOrbitPeriodSeconds(_),G=()=>{var ne,ee,re,se;const z=((re=(ee=(ne=e._viewer)==null?void 0:ne.scene)==null?void 0:ee.frameState)==null?void 0:re.frameNumber)??-1;if(z!==-1&&z===x)return;x=z;const j=Date.now();if(D.setTime(j),g){const me=((se=g.positionAt)==null?void 0:se.call(g,D))||g.current;me&&(Cesium.Cartesian3.fromDegrees(me.longitude,me.latitude,me.altitude,void 0,O),$.speedMps=Number.isFinite(me.speedMps)?me.speedMps:null)}else O=n.paths.samplePath(_,n.paths.orbitProgressAtTime(j,N),O)||O};e._dataSource.entities.add({id:`rocket-satellite:${l.id}`,position:new Cesium.CallbackProperty(()=>(G(),O),!1),point:{pixelSize:6,color:Cesium.Color.fromCssColorString(g?"#7bed9f":"#ffd166"),outlineWidth:0,disableDepthTestDistance:Number.POSITIVE_INFINITY},properties:{launchId:l.id,noradId:(g==null?void 0:g.noradId)||"",phase:g?"CURRENT_SATELLITE_POSITION":"ESTIMATED_ORBIT_POSITION",source:g?"Satellites layer":"Approximate mission orbit"}}),d.liveEventTime=()=>D,d.elementEntryFactories.push(()=>{const z=g?n.overlays.shortMissionLabel(g.name,22).toUpperCase():"EST. ORBIT POSITION";return n.overlays.createRocketMissionElementOverlayEntry({id:`payload-position:${l.id}`,position:()=>O,text:`${z} +${n.policyHelpers.formatMissionEventTime(D)}`,accent:g?"#7bed9f":"#ffd166",priority:9e5,gapPx:12})}),n.orbitRendering.addMissionOrbitPrimitive(l,_,g)||e._dataSource.entities.add({id:`rocket-orbit:${l.id}`,polyline:{positions:_,width:3,material:new n.orbitRendering.MissionOrbitPatternMaterialProperty(Cesium.Color.fromCssColorString("#c084fc").withAlpha(.95)),arcType:Cesium.ArcType.NONE},properties:{launchId:l.id,satelliteName:"",noradId:"",source:"Approximate mission orbit"}});const V=I.at(-1);let H=V;const B=e._missionOrbitPrimitives.get(l.id);B&&(B.labelBakePosition=V,B.labelPosition=Cesium.Matrix4.multiplyByPoint(B.primitive.modelMatrix,V,new Cesium.Cartesian3),H=()=>B.labelPosition),d.elementEntryFactories.push(()=>n.overlays.createRocketMissionElementOverlayEntry({id:`orbit:${l.id}`,position:H,text:g?"ORBIT":"PROJECTED ORBIT",accent:g?"#22e6e6":"#c084fc",priority:8e5,gapPx:8}));const q=new Cesium.CallbackProperty(()=>{const z=P();return z.ascending?n.paths.samplePath(I,z.phaseProgress):n.paths.samplePath(R,z.phaseProgress)},!1);e._dataSource.entities.add({id:`rocket-vehicle:${l.id}`,position:q,properties:{launchId:l.id,noradId:(g==null?void 0:g.noradId)||"",phase:"ASCENT_THEN_ORBIT",source:g?"Satellite trajectory animation":"Approximate trajectory animation"}}),e._dataSource.entities.add({id:`rocket-transfer:${l.id}`,polyline:{positions:I,width:1.5,arcType:Cesium.ArcType.NONE,material:new Cesium.PolylineDashMaterialProperty({color:Cesium.Color.fromCssColorString("#7bed9f").withAlpha(.8),dashLength:24,dashPattern:61680})},properties:{launchId:l.id,phase:"APPROXIMATE_TRANSFER",source:g?"Launch site to propagated insertion":"Launch site to forward projected insertion"}})}}return{setGraphicVisibility:s,updateMissionFrame:a,addLaunchEntity:c}}function C$({state:e,services:t,parts:n,source:i}){function o(s=null){e._missionOverlayHost=s?{...e.DEFAULT_OVERLAY_HOST,...s}:e.DEFAULT_OVERLAY_HOST}function r(s=null){n.selection.setSelectedMission(s,!!s)}return{_setRocketMissionOverlayHostForTest:o,_setSelectedRocketMissionForTest:r}}function y$({state:e,services:t,parts:n,source:i}){return{methods:{id:"rocket-launches",name:"Space Missions (30d)",icon:"🚀",source:"Launch Library 2",updateInterval:3e5,releaseCameraOwnership(){n.panel.clearMissionRosterHover(),n.replay.stopMissionReplay(),n.selection.stopMissionZoomAnchor()},getStats(){return{count:e._count,orbitMatches:e._orbitMatches,lastUpdate:e._lastUpdate,error:e._lastError}},attachDataManager(r){e._dataManager=r}}}}function v$({state:e,services:t,parts:n,source:i}){const{holdContinuousRender:o,releaseContinuousRender:r}=t.render;return{methods:{init(a){e._viewer=a,e._enabled=!1,n.panel.createMissionPanel(),n.overlays.createReplayVehicleOverlay(),e._dataSource=new Cesium.CustomDataSource("rocket-launches"),e._dataSource.show=!1,a.dataSources.add(e._dataSource),e._count=0,e._lastUpdate=null,e._lastError=null,e._orbitMatches=0,n.overlays.clearMissionOverlaySources(),e._clickHandler=new Cesium.ScreenSpaceEventHandler(a.scene.canvas),e._clickHandler.setInputAction(c=>{var h;if(!Bt()||!e._enabled||!((h=e._dataSource)!=null&&h.show))return;const l=a.scene.drillPick(c.position,12).map(d=>d==null?void 0:d.id).find(d=>n.selection.entityLaunchId(d)),u=n.selection.entityLaunchId(l);u&&(n.selection.setSelectedMission(u),n.selection.focusMission(e._launches.find(d=>d.id===u)))},Cesium.ScreenSpaceEventType.LEFT_CLICK),e._moveHandler=new Cesium.ScreenSpaceEventHandler(a.scene.canvas),e._moveHandler.setInputAction(c=>{var u;if(!e._enabled||!((u=e._dataSource)!=null&&u.show))return;const l=a.scene.drillPick(c.endPosition,12).map(h=>h==null?void 0:h.id).find(h=>n.selection.entityLaunchId(h));a.scene.canvas.style.cursor=l?"pointer":""},Cesium.ScreenSpaceEventType.MOUSE_MOVE),e._declutterHandler=a.scene.preRender.addEventListener(n.rendering.updateMissionFrame),n.launchPad.initLaunchPadZonePrimitive()},async enable(){e._sourceController.abort(),e._sourceController=new AbortController,e._enabled=!0,o("rocket-launches"),e._lifecycleToken++,e._postTleRetryCount=0;try{await this._enableBody()}catch(a){try{await this.disable()}catch(c){console.warn("[Missions] enable rollback failed:",c)}throw a}},async _enableBody(){var a;e._updateDirty=!1,e._dataSource&&(e._dataSource.show=!0),n.orbitRendering.syncMissionOrbitPrimitiveVisibility(),n.selection.focusFullGlobe(e._viewer),(a=document.getElementById("cockpit-context"))==null||a.setAttribute("hidden",""),e._selectedLaunchId?n.selection.setSelectedMission(e._selectedLaunchId,e._explicitSelection):n.selection.setSelectedMission(null,!1),await n.ingestion.captureSatelliteDependency()},async disable(){var a,c;e._sourceController.abort(),e._enabled=!1,r("rocket-launches"),e._lifecycleToken++,e._updateDirty=!1,n.ingestion.clearPostTleRetry(),n.panel.clearMissionRosterHover(),n.replay.stopMissionReplay(),n.selection.stopMissionZoomAnchor(),e._dataSource&&(e._dataSource.show=!1),n.orbitRendering.syncMissionOrbitPrimitiveVisibility(),(c=(a=e._viewer)==null?void 0:a.scene)!=null&&c.canvas&&(e._viewer.scene.canvas.style.cursor=""),n.launchPad.hideLaunchPadZone(),n.overlays.hideReplayVehicleOverlay(),e._selectedLaunchId=null,n.overlays.clearMissionOverlaySources(),await n.ingestion.restoreSatelliteDependency(),n.panel.renderMissionPanel()},async destroy(a){var c;e._sourceController.abort(),r("rocket-launches"),e._enabled=!1,e._lifecycleToken++,e._updateDirty=!1,await n.ingestion.restoreSatelliteDependency(),n.panel.clearMissionRosterHover(),n.replay.stopMissionReplay(),n.selection.stopMissionZoomAnchor(),n.ingestion.clearPostTleRetry(),e._clickHandler&&e._clickHandler.destroy(),e._clickHandler=null,e._moveHandler&&e._moveHandler.destroy(),e._moveHandler=null,e._declutterHandler&&e._declutterHandler(),e._declutterHandler=null,n.launchPad.destroyLaunchPadZonePrimitive(),n.orbitRendering.removeMissionOrbitPrimitives(),n.overlays.clearMissionOverlaySources(),n.overlays.destroyReplayVehicleOverlay(),e._launches=[],e._missionOverlayRecords.clear(),e._animationStarts.clear(),e._satelliteTelemetry.clear(),e._replayTracks.clear(),(c=e._missionPanel)==null||c.remove(),e._missionPanel=null,e._missionRoster&&(e._missionRoster.onclick=null),e._missionRosterPreviewOwnership=null,e._missionRoster=null,e._viewer=null,e._dataSource&&a.dataSources.remove(e._dataSource,!0),e._dataSource=null,e._count=0,e._orbitMatches=0,e._lastUpdate=null,e._activeTleText=null,e._activeTlePromise=null,e._activeTlePromiseToken=0,e._renderedTleText=null,e._postTleRetryCount=0,e._satelliteStateBeforeMission=null,e._satelliteActivationPromise=null,e._dataManager=null}}}}function M$({services:e}){const{setOverlayEntries:t,setOverlaySourceVisible:n,clearOverlaySource:i}=e.overlays,o={};return o.DEFAULT_OVERLAY_HOST=Object.freeze({setEntries:t,setVisible:n,clearSource:i}),o._dataSource=null,o._count=0,o._lastUpdate=null,o._lastError=null,o._orbitMatches=0,o._clickHandler=null,o._moveHandler=null,o._viewer=null,o._declutterHandler=null,o._dataManager=null,o._retryTimer=null,o._postTleRetryCount=0,o._updatePromise=null,o._updatePromiseToken=0,o._updateDirty=!1,o._lifecycleToken=0,o._enabled=!1,o._selectedLaunchId=null,o._explicitSelection=!1,o._launches=[],o._missionPanel=null,o._missionRoster=null,o._missionRosterHoverTimer=null,o._hoveredRosterLaunchId=null,o._missionRosterPreviewOwnership=null,o._missionHoverReticleImage=null,o._replayVehicleOverlay=null,o._replayVehicleOverlayText="",o._animationStarts=new Map,o._satelliteTelemetry=new Map,o._lastPanelTelemetryMs=0,o._lastMissionRingRotationMs=0,o._activeTleText=null,o._activeTlePromise=null,o._activeTlePromiseToken=0,o._renderedTleText=null,o._focusAfterActiveLookup=!1,o._satelliteStateBeforeMission=null,o._satelliteActivationPromise=null,o._replayCameraRemover=null,o._replayCameraLaunchId=null,o._replayCameraToken=0,o._replayPaused=!1,o._replayPausedAtMs=null,o._replaySpeed=1,o._replayTracks=new Map,o._missionOverlayRecords=new Map,o._missionOverlayHost=o.DEFAULT_OVERLAY_HOST,o._selectedMissionOverlayTimeText=null,o._missionZoomAnchorRemover=null,o._missionZoomAnchorId=null,o._launchPadZonePrimitive=null,o._launchPadZoneRemover=null,o._launchPadZoneLaunchId=null,o._missionOrbitPrimitives=new Map,o._declutterTime=new Cesium.JulianDate,o._declutterOccluder=new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84,new Cesium.Cartesian3),o._missionRingDate=new Date(0),o._missionOrbitPatternRegistered=!1,o._pathDistanceCache=new WeakMap,o._sourceController=new AbortController,o}function w$({fetchImpl:e=(...t)=>globalThis.fetch(...t)}={}){return{async getLaunches({signal:t}={}){t==null||t.throwIfAborted();const n=await e("/api/launches",{signal:t});if(!n.ok)throw new Error(`HTTP ${n.status}`);const i=await n.json();if(t==null||t.throwIfAborted(),!Array.isArray(i)&&!Array.isArray(i==null?void 0:i.results))throw new Error("Malformed launch snapshot");return i},async getActiveTle({signal:t}={}){t==null||t.throwIfAborted();const n=await e("/api/celestrak/active",{signal:t});if(!n.ok)throw new Error(`HTTP ${n.status}`);const i=await n.text();return t==null||t.throwIfAborted(),i}}}function E$({services:e,source:t}){if(typeof(t==null?void 0:t.getLaunches)!="function")throw new TypeError("A launches source is required");const n=M$({services:e}),i={},o={state:n,services:e,parts:i,source:t};return i.policyHelpers=a$(o),i.ingestion=l$(o),i.orbitRendering=c$(o),i.overlays=u$(o),i.selection=d$(o),i.replay=h$(o),i.panel=f$(o),i.paths=m$(o),i.launchPad=p$(o),i.camera=g$(o),i.model=_$(o),i.rendering=b$(o),i.testing=C$(o),i.controls=y$(o),i.lifecycle=v$(o),Object.assign({},i.controls.methods,i.lifecycle.methods,i.ingestion.methods,{satelliteParamsForSpaceMissions:i.policyHelpers.satelliteParamsForSpaceMissions,satelliteParamsAfterSpaceMissions:i.policyHelpers.satelliteParamsAfterSpaceMissions,launchStatusAllowsOrbit:i.policyHelpers.launchStatusAllowsOrbit,missionPathPresentation:i.policyHelpers.missionPathPresentation,shouldRetryAfterActiveTle:i.ingestion.shouldRetryAfterActiveTle,releaseAircraftTracking:i.policyHelpers.releaseAircraftTracking,launchPadZoneVisible:i.policyHelpers.launchPadZoneVisible,missionAnchorHorizonVisible:i.overlays.missionAnchorHorizonVisible,missionAnchorVisible:i.overlays.missionAnchorVisible,compactLaunchSiteName:i.overlays.compactLaunchSiteName,createRocketMissionMarkerOverlayEntry:i.overlays.createRocketMissionMarkerOverlayEntry,createRocketMissionElementOverlayEntry:i.overlays.createRocketMissionElementOverlayEntry,selectRocketMissionMarkerOverlayCohort:i.overlays.selectRocketMissionMarkerOverlayCohort,replayOverlayMode:i.overlays.replayOverlayMode,replayVehicleScreenRotation:i.replay.replayVehicleScreenRotation,smoothReplayWindowPosition:i.replay.smoothReplayWindowPosition,missionDataCompleteness:i.policyHelpers.missionDataCompleteness,missionRosterEntries:i.policyHelpers.missionRosterEntries,missionHoverPreviewRange:i.panel.missionHoverPreviewRange,createMissionRosterPreviewOwnership:i.panel.createMissionRosterPreviewOwnership,bindMissionRosterItemKeyboardPreview:i.panel.bindMissionRosterItemKeyboardPreview,captureMissionRosterFocus:i.panel.captureMissionRosterFocus,restoreMissionRosterFocus:i.panel.restoreMissionRosterFocus,resolveMissionRosterPreviewLaunch:i.panel.resolveMissionRosterPreviewLaunch,formatMissionEventTime:i.policyHelpers.formatMissionEventTime,parseMissionDurationSeconds:i.policyHelpers.parseMissionDurationSeconds,replayAscentDurationSeconds:i.replay.replayAscentDurationSeconds,normalizeReplaySpeed:i.replay.normalizeReplaySpeed,replayStartAfterPause:i.replay.replayStartAfterPause,replayState:i.replay.replayState,approximateOrbitPath:i.paths.approximateOrbitPath,samplePath:i.paths.samplePath,orbitProgressAtTime:i.paths.orbitProgressAtTime,reconstructedAscentPath:i.paths.reconstructedAscentPath,buildMissionPaths:i.paths.buildMissionPaths,cameraHeadingForPath:i.camera.cameraHeadingForPath,replayInitialCameraHeading:i.camera.replayInitialCameraHeading,replayChaseCameraHeading:i.camera.replayChaseCameraHeading,smoothReplayCameraHeading:i.camera.smoothReplayCameraHeading,missionZoomPitch:i.camera.missionZoomPitch,replayCameraView:i.camera.replayCameraView,replayOrbitGlobeAnchor:i.camera.replayOrbitGlobeAnchor,replayOrbitCameraTarget:i.camera.replayOrbitCameraTarget,replayOrbitCameraPose:i.camera.replayOrbitCameraPose,replayOrbitFrameSphere:i.camera.replayOrbitFrameSphere,replayOrbitGlobeRange:i.camera.replayOrbitGlobeRange,missionMarkerColor:i.model.missionMarkerColor,normalizeRocketLaunches:i.model.normalizeRocketLaunches,_setRocketMissionOverlayHostForTest:i.testing._setRocketMissionOverlayHostForTest,_setSelectedRocketMissionForTest:i.testing._setSelectedRocketMissionForTest})}function T$({source:e,satellites:t}){return E$({source:e,services:{satellites:t,geometry:Gf,overlays:ui,render:Pt}})}const qn="alpr-cameras",k$="/api/overpass",A$=500,Hs=3,Oh=1500,vE=1500,xb=90,Fb=20,I$=63710088e-1,Bh=.05,R$=600*1e3,Vh="#52d4ff",L$="#ff6474",_l=38,Ms=60,Sb=64,P$=5e3;function mi(e){return String(e??"").trim()||null}function x$(e){if(e==null)return null;const t=String(e).trim();if(!t)return null;const n=Number(t);return Number.isFinite(n)?n:null}function F$(e,t=Bh){const n=o=>Math.floor(o/t)*t,i=o=>Math.ceil(o/t)*t;return{south:Math.max(-90,n(e.south)),west:Math.max(-180,n(e.west)),north:Math.min(90,i(e.north)),east:Math.min(180,i(e.east))}}function Hh(e,t){return!e||!t?!1:t.south>=e.south&&t.north<=e.north&&t.west>=e.west&&t.east<=e.east}function S$(e){return!Number.isFinite(e)||e<=0?3e4:Math.min(e*2,24e4)}function N$(e){return String(e??"").split(";").some(t=>t.trim().toUpperCase()==="ALPR")}function D$(e){if(!e||e.type!=="node"||!Number.isSafeInteger(e.id)||e.id<=0||!Number.isFinite(e.lat)||Math.abs(e.lat)>90||!Number.isFinite(e.lon)||Math.abs(e.lon)>180)return null;const t=e.tags||{};return N$(t["surveillance:type"])?{id:`alpr:${e.id}`,osmId:e.id,latitude:e.lat,longitude:e.lon,operator:mi(t.operator),manufacturer:mi(t.manufacturer),cameraType:mi(t["camera:type"]),zone:mi(t["surveillance:zone"]),directionDeg:O$(t["camera:direction"]??t.direction),ref:mi(t.ref),lastVerified:mi(t.check_date)||mi(t["survey:date"]),source:mi(t.source)}:null}function O$(e){const t=x$(e);return t!=null&&t>=0&&t<=360?t%360:null}function B$(e,t,n,i){return`[out:json][timeout:20];node["man_made"="surveillance"]["surveillance:type"~"(^|;)\\s*ALPR\\s*(;|$)",i](${e},${t},${n},${i});out body ${Oh};`}function V$(e){if(!Array.isArray(e==null?void 0:e.records)||typeof e.stale!="boolean"||typeof e.saturated!="boolean")throw new TypeError("Camera source returned an invalid snapshot");const t=new Set;for(const n of e.records){if(!n||typeof n.id!="string"||!n.id.trim()||t.has(n.id)||!Number.isFinite(n.latitude)||Math.abs(n.latitude)>90||!Number.isFinite(n.longitude)||Math.abs(n.longitude)>180||n.directionDeg!=null&&(!Number.isFinite(n.directionDeg)||n.directionDeg<0||n.directionDeg>=360))throw new TypeError("Camera source returned an invalid record");t.add(n.id)}return e}function Nb(e,t,n,i){const o=i/I$,r=Cesium.Math.toRadians(n),s=Cesium.Math.toRadians(e),a=Cesium.Math.toRadians(t),c=Math.asin(Math.sin(s)*Math.cos(o)+Math.cos(s)*Math.sin(o)*Math.cos(r)),l=a+Math.atan2(Math.sin(r)*Math.sin(o)*Math.cos(s),Math.cos(o)-Math.sin(s)*Math.sin(c));return{latitude:Cesium.Math.toDegrees(c),longitude:Cesium.Math.toDegrees(l)}}function H$(e){if(!(e!=null&&e.text)||!(e!=null&&e.href))return null;const t=new URL(e.href);if(t.protocol!=="https:"||t.username||t.password)throw new TypeError("Camera attribution requires a public HTTPS link");const n=i=>String(i).replace(/[&<>"']/g,o=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[o]);return`ALPR: ${n(e.text)}`}const $h=new URL("/assets/alpr-marker-normal-COAu686W.png",import.meta.url).href,Gh=new URL("/assets/alpr-marker-selected-WmayY1kQ.png",import.meta.url).href,$$=new URL("/assets/alpr-marker-selected-brackets-LQ7qLcLT.png",import.meta.url).href;function G$(e){return Number.isSafeInteger(e.osmId)?`ALPR-${String(e.osmId).slice(-4).padStart(4,"0")}`:"ALPR CAMERA"}function U$(e,t){var r;const n=((r=t.attribution)==null?void 0:r.name)||t.label||"Camera source",i=[n==="OpenStreetMap"?"OSM MAPPED":`Source: ${n}`];Number.isFinite(e.directionDeg)&&i.push(`DIRECTION ${Math.round(e.directionDeg)}°`);const o=[...new Set([e.manufacturer,e.operator,e.cameraType].map(s=>String(s||"").trim().toUpperCase()).filter(Boolean))];return o.length&&i.push(o.join(" · ")),n==="OpenStreetMap"&&i.push("PUBLIC MAP DATA"),i}function ME(e,t=0){if(!Number.isFinite(e.directionDeg))return null;const n=Nb(e.latitude,e.longitude,e.directionDeg-Fb,xb),i=Nb(e.latitude,e.longitude,e.directionDeg+Fb,xb);return[Cesium.Cartesian3.fromDegrees(e.longitude,e.latitude,t),Cesium.Cartesian3.fromDegrees(n.longitude,n.latitude,t),Cesium.Cartesian3.fromDegrees(i.longitude,i.latitude,t)]}function z$(e,t,n,i,o){const r=o?"255, 100, 116":"82, 212, 255",s=e.createLinearGradient(t.x,t.y,(n.x+i.x)/2,(n.y+i.y)/2),a=o?[.8,.48,.22,.06]:[.34,.2,.09,.025];[0,.36,.72,1].forEach((c,l)=>s.addColorStop(c,`rgba(${r}, ${a[l]})`)),e.beginPath(),e.moveTo(t.x,t.y),e.lineTo(n.x,n.y),e.lineTo(i.x,i.y),e.closePath(),e.fillStyle=s,e.fill(),e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(t.x,t.y),e.lineTo(i.x,i.y),e.strokeStyle=`rgba(${r}, ${o?.98:.76})`,e.lineWidth=o?2.5:1.5,e.lineJoin="round",e.stroke()}function Wn(e){return Number.isFinite(e)&&e>=-500&&e<=1e4}function j$({state:e,services:t}){let n,i,o,r=0,s=[],a=[],c=[],l=!1,u;const h=()=>{!l&&e.enabled&&(n==null||n.requestPaint())};function d(_,m){if(!_)return;const b=_.billboard;if(!m&&!_.gevAlprNativeAppearance)_.gevAlprNativeAppearance={position:_.position,heightReference:b.heightReference,scaleByDistance:b.scaleByDistance,color:b.color},_.position=_.gevAlprCanvasPosition,_.gevAlprPickPosition=_.position,b.heightReference=Cesium.HeightReference.NONE,b.scaleByDistance=void 0,b.color=Cesium.Color.WHITE.withAlpha(.01);else if(m&&_.gevAlprNativeAppearance){const C=_.gevAlprNativeAppearance;_.position===_.gevAlprPickPosition&&(_.position=C.position),b.heightReference=C.heightReference,b.scaleByDistance=C.scaleByDistance,b.color=C.color,_.gevAlprNativeAppearance=null,_.gevAlprPickPosition=null}b.show=m,_.polyline&&(_.polyline.show=m),_.polygon&&(_.polygon.show=m)}function f(){for(const _ of e.dataSource.entities.values)_.gevAlprCanvasPosition=null,_.gevAlprWedge=null,_.gevAlprDisplayPosition=null,d(_,!0);e.lastAnchorSampleAt=0,r=Date.now()+15e3,h()}function p(_,m){var v,M;if(m.gevAlprCanvasPosition)return m.gevAlprCanvasPosition;const b=e.viewer.scene,C=Cesium.Cartographic.fromDegrees(_.longitude,_.latitude);let y;if(b.sampleHeightSupported)try{y=b.sampleHeight(C,[m])}catch{}return!Wn(y)&&b.globe.show&&(y=(M=(v=b.globe).getHeight)==null?void 0:M.call(v,C)),Wn(y)||(y=t.groundFloor.cachedGroundFloor(_.latitude,_.longitude)),Wn(y)?(m.gevAlprCanvasPosition=Cesium.Cartesian3.fromDegrees(_.longitude,_.latitude,y),m.gevAlprWedge=ME(_,y),m.gevAlprCanvasPosition):null}function g({ctx:_,width:m,height:b,keyhole:C,occluder:y}){var w,E,k;if(a=[],!e.enabled||l)return;let v=!1;const M=[];for(const T of s){const I=e.dataSource.entities.getById(T.id);if(!I)continue;const R=T.id===e.selectedId,S=c[R?1:0];if(!(S!=null&&S.complete)||!S.naturalWidth||R&&!((w=c[2])!=null&&w.naturalWidth)){d(I,!0);continue}const A=p(T,I);if(!A){d(I,!0),v=!0;continue}if(d(I,!1),y&&!y.isPointVisible(A))continue;const L=e.viewer.scene,F=Cesium.SceneTransforms.worldToWindowCoordinates(L,A);if(!F)continue;const P=((k=(E=t.overlays).keyholeAlpha)==null?void 0:k.call(E,F.x,F.y,C))??1;if(!(P>0))continue;const O=I.gevAlprWedge;if(O){const D=Cesium.SceneTransforms.worldToWindowCoordinates(L,O[1]),$=Cesium.SceneTransforms.worldToWindowCoordinates(L,O[2]);D&&$&&(_.save(),_.globalAlpha*=P,z$(_,F,D,$,R),_.restore())}F.x<-60||F.x>m+60||F.y<-60||F.y>b+60||(I.billboard.show=!0,M.push({record:T,origin:F,selected:R,image:S,alpha:P}),R&&(I.gevAlprDisplayPosition=A))}for(const{record:T,origin:I,selected:R,image:S,alpha:A}of M){const L=R?Ms:_l;_.save(),_.globalAlpha*=A,_.drawImage(S,I.x-L/2,I.y-L/2,L,L),R&&_.drawImage(c[2],I.x-L/2,I.y-L/2,L,L),_.restore(),a.push({id:T.id,x:I.x,y:I.y,radius:L/2})}v&&!o&&Date.now(){o=null,h()},250))}return{init(){var _,m,b;l=!1,!(!((_=t.overlays)!=null&&_.registerPaintLane)||typeof Image>"u")&&(n=t.overlays.registerPaintLane("selected",g,{id:`alpr-${Cesium.createGuid()}`,active:!1}),c=[$h,Gh,$$].map(C=>{const y=new Image;return y.onload=h,y.onerror=h,y.src=C,y}),u=e.viewer.scene.globe.show,i=(b=(m=t.overlays).subscribeMapStack)==null?void 0:b.call(m,C=>{var v;if(((v=C.detail)==null?void 0:v.status)!=="ready")return;const y=e.viewer.scene.globe.show;y!==u&&(u=y,f())}))},sync(_){if(!n)return;for(const C of s)d(e.dataSource.entities.getById(C.id),!0);const m=e.viewer.camera.positionWC;s=_.filter(C=>Number.isFinite(C.directionDeg)&&C.id!==e.selectedId).map(C=>({record:C,distance:m?Cesium.Cartesian3.distanceSquared(m,Cesium.Cartesian3.fromDegrees(C.longitude,C.latitude)):0})).sort((C,y)=>C.distance-y.distance).slice(0,Sb).map(C=>C.record);const b=_.find(C=>C.id===e.selectedId);b&&(s.length>=Sb&&s.pop(),s.push(b)),a=[],r=Date.now()+15e3,n.setActive(e.enabled&&s.length>0),h()},pick(_){if(!e.enabled||!_)return null;let m,b=1/0;for(const C of a){const y=(C.x-_.x)**2+(C.y-_.y)**2;y<=C.radius**2&&y<=b&&(m=C.id,b=y)}return m||null},clear(){var _;clearTimeout(o),o=null;for(const m of s)d((_=e.dataSource)==null?void 0:_.entities.getById(m.id),!0);s=[],a=[],n==null||n.setActive(!1)},destroy(){this.clear(),l=!0,i==null||i(),i=null,n==null||n.unregister(),n=null;for(const _ of c)_.onload=null,_.onerror=null;c=[]}}}function q$({state:e,services:t,source:n}){const{governorRequestRender:i}=t.render,{clearSelectedEntityContextForLayer:o,getSelectedEntityContext:r,registerEntityContext:s,removeEntityContextsForLayer:a,selectEntityContext:c}=t.context,{cachedGroundFloor:l}=t.groundFloor,u=j$({state:e,services:t});let h=[],d=0;function f(k,T){const I=Cesium.Color.fromCssColorString(T?L$:Vh);k.billboard.image=T?Gh:$h,k.billboard.width=k.billboard.height=T?Ms:_l,k.polyline&&(k.polyline.width=T?3:1.75,k.polyline.material=I.withAlpha(T?.98:.82)),k.polygon&&(k.polygon.material=I.withAlpha(T?.8:.2)),k.gevLabelModel&&(k.gevLabelModel.accent=I.toCssColorString(),k.gevLabelModel.leaderAnimationStartedAt=T?d:0)}function p(){return Cesium.Color.fromCssColorString(Vh)}function g(k){var P;const T=k==null?void 0:k.camera,I=k==null?void 0:k.scene.canvas;if(typeof(T==null?void 0:T.pickEllipsoid)=="function"&&I){const O=I.clientWidth||I.width,D=I.clientHeight||I.height;if(!O||!D)return null;const $=T.pickEllipsoid(new Cesium.Cartesian2(O/2,D/2),k.scene.globe.ellipsoid);if(!$)return null;const x=Cesium.Cartographic.fromCartesian($),N=Cesium.Cartesian3.distance(T.positionWC,$),G=Math.max(1e3,2*N),W=Cesium.Math.toDegrees(x.latitude),V=Cesium.Math.toDegrees(x.longitude),H=G/111e3,B=H/Math.cos(x.latitude);return!Number.isFinite(H+B)||2*Math.max(H,B)>Hs||Math.abs(W)+H>90||Math.abs(V)+B>180?null:{south:W-H,west:V-B,north:W+H,east:V+B}}const R=(P=k==null?void 0:k.camera)==null?void 0:P.computeViewRectangle(k.scene.globe.ellipsoid);if(!R)return null;const S=Cesium.Math.toDegrees(R.south),A=Cesium.Math.toDegrees(R.north),L=Cesium.Math.toDegrees(R.west),F=Cesium.Math.toDegrees(R.east);return!Number.isFinite(S+A+L+F)||F<=L||A-S>Hs||F-L>Hs?null:{south:S,west:L,north:A,east:F}}function _(){var k;u.clear(),h=[],(k=e.dataSource)!=null&&k.entities&&e.dataSource.entities.removeAll(),a(qn)}function m(){var k,T;clearTimeout(e.creditTimer),e.creditTimer=null,e.credit&&((T=(k=e.viewer)==null?void 0:k.creditDisplay)==null||T.removeStaticCredit(e.credit)),i("alpr-credit")}function b(){var k;!e.enabled||e.creditPresented||!e.credit||(e.creditPresented=!0,(k=e.viewer.creditDisplay)==null||k.addStaticCredit(e.credit),e.creditTimer=setTimeout(m,P$),i("alpr-credit"))}function C(){var A,L,F;const k=r(),T=g(e.viewer),I=T?e.records.filter(P=>Hh(T,{south:P.latitude,north:P.latitude,west:P.longitude,east:P.longitude})).slice(0,vE):[];h=I,((k==null?void 0:k.layerId)!==qn||k.id!==e.selectedId||!I.some(P=>P.id===e.selectedId))&&(e.selectedId=null,o(qn)),i("alpr-render");const R=new Set(I.map(P=>P.id));for(const P of[...e.dataSource.entities.values])R.has(P.id)||e.dataSource.entities.remove(P);a(qn,{retainIds:R});for(const P of I){const O=e.dataSource.entities.getById(P.id);if((O==null?void 0:O.gevAlprRecord)===P){f(O,P.id===e.selectedId);continue}const D=p(),$=P.id===e.selectedId,x=Cesium.Cartesian3.fromDegrees(P.longitude,P.latitude),N={id:P.id,position:x,billboard:{image:$?Gh:$h,width:$?Ms:_l,height:$?Ms:_l,heightReference:Cesium.HeightReference.CLAMP_TO_GROUND,disableDepthTestDistance:Number.POSITIVE_INFINITY,scaleByDistance:new Cesium.NearFarScalar(350,1.15,4e6,.48)}},G=ME(P);G&&(N.polyline={positions:[G[1],x,G[2]],width:$?3:1.75,material:D.withAlpha(.82),clampToGround:!0},N.polygon={hierarchy:G,material:D.withAlpha(.2),height:0,heightReference:Cesium.HeightReference.CLAMP_TO_GROUND,classificationType:Cesium.ClassificationType.BOTH});let W=O;const V=W==null?void 0:W.gevAlprRecord;W?((V.latitude!==P.latitude||V.longitude!==P.longitude)&&(W.position=x,W.gevAlprCanvasPosition=null,W.gevAlprDisplayPosition=null),(V.latitude!==P.latitude||V.longitude!==P.longitude||V.directionDeg!==P.directionDeg)&&(W.polyline=N.polyline,W.polygon=N.polygon,W.gevAlprCanvasPosition=null,W.gevAlprWedge=null)):W=e.dataSource.entities.add(N),W.gevAlprRecord=P,W.gevTrackedId=P.id,W.gevAlprDisplayPosition??(W.gevAlprDisplayPosition=null),W.gevDisplayPosition=()=>W.gevAlprDisplayPosition,W.gevLabelModel={title:G$(P),details:U$(P,n),accent:D.toCssColorString(),cardStyle:"tactical",selected:!0,leaderStyle:"elbow",leaderAnimationMs:440,leaderAnimationStartedAt:$?d:0,leaderDrawRatio:.68,anchorRadiusPx:Ms/2,anchorRadiusScale:null},f(W,$),s(W,{id:P.id,layerId:qn,dataSource:e.dataSource,layerName:"ALPR Cameras",source:((A=n.attribution)==null?void 0:A.description)||n.label||"Camera source",label:"ALPR camera",latitude:P.latitude,longitude:P.longitude,properties:{operator:P.operator,manufacturer:P.manufacturer,cameraType:P.cameraType,zone:P.zone,directionDeg:P.directionDeg,ref:P.ref,lastVerified:P.lastVerified,osmId:P.osmId,sourceTag:P.source}})}const S=e.selectedId?e.dataSource.entities.getById(e.selectedId):null;S||(e.selectedId=null),w(),u.sync(I),S&&((F=(L=t.overlays)==null?void 0:L.refreshReadout)==null||F.call(L,S)),I.length&&b()}function y(){var F,P,O;const k=(F=e.viewer)==null?void 0:F.camera;if(!e.enabled||!(k!=null&&k.positionWC)||e.viewer.trackedEntity)return!1;let T=null,I=1/0;for(const D of e.dataSource.entities.values){const $=D.position.getValue(Cesium.JulianDate.now()),x=Cesium.Cartesian3.distanceSquared(k.positionWC,$);x.1)&&(T.gevAlprDisplayPosition=L,i("alpr-anchor"))}function E(k){e.clickHandler||(e.clickHandler=new Cesium.ScreenSpaceEventHandler(k.scene.canvas),e.clickHandler.setInputAction(T=>{var S,A;if(!Bt()||!e.enabled)return;const I=k.scene.pick(T.position),R=u.pick(T.position)||(typeof((S=I==null?void 0:I.id)==null?void 0:S.id)=="string"?I.id.id:null);R&&e.recordById.has(R)&&(R!==e.selectedId||((A=r())==null?void 0:A.id)!==R)?v(R):e.selectedId&&M()},Cesium.ScreenSpaceEventType.LEFT_CLICK))}return{initOverlay:()=>u.init(),destroyOverlay:()=>u.destroy(),markerColor:p,viewportBox:g,clearRendered:_,hideOnMapCredit:m,presentOnMapCredit:b,renderRecords:C,selectRecord:v,focusNearest:y,clearSelection:M,updateSelectedAnchor:w,installInteraction:E}}function W$({fetchImpl:e=(...t)=>globalThis.fetch(...t)}={}){async function t(n,i){var c;if(i==null||i.throwIfAborted(),!n||![n.south,n.west,n.north,n.east].every(Number.isFinite)||n.south<-90||n.north>90||n.west<-180||n.east>180||n.north<=n.south||n.east<=n.west||n.north-n.south>Hs+2*Bh+1e-9||n.east-n.west>Hs+2*Bh+1e-9)throw new TypeError("ALPR requires a bounded city viewport");const o=B$(n.south,n.west,n.north,n.east),r=await e(k$,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(o)}`,signal:i});if(!r.ok){try{await((c=r.body)==null?void 0:c.cancel())}catch{}const l=r.status===429?"Overpass rate-limited":r.status===504?"Overpass timed out":"Overpass temporarily unavailable";throw new Error(l)}const s=r.headers.get("x-overpass-cache")==="STALE",a=await r.json();if(i==null||i.throwIfAborted(),!Array.isArray(a==null?void 0:a.elements)||a.remark)throw new Error("Overpass returned an incomplete camera response");return{records:[...new Map(a.elements.slice(0,Oh).map(D$).filter(Boolean).map(l=>[l.id,l])).values()],stale:s,saturated:a.elements.length>=Oh}}return{fetch:t,label:"OpenStreetMap · community mapped",attribution:{name:"OpenStreetMap",description:"OpenStreetMap contributors (ODbL 1.0; community mapped)",text:"© OpenStreetMap",href:"https://www.openstreetmap.org/copyright"}}}function K$({source:e,services:t}={}){if(typeof(e==null?void 0:e.fetch)!="function")throw new TypeError("ALPR requires a camera source");const{governorRequestRender:n}=t.render,{registerPickOwner:i,unregisterPickOwner:o}=t.picking,r={viewer:null,dataSource:null,credit:null,creditTimer:null,creditPresented:!1,enabled:!1,records:[],recordById:new Map,selectedId:null,lastUpdate:null,error:null,status:"idle",stale:!1,saturated:!1,loading:!1,abort:null,pendingQueryBox:null,retryTimer:null,retryDelayMs:0,retryAt:0,retrying:!1,moveEndRemove:null,postRenderRemove:null,lastAnchorSampleAt:0,clickHandler:null,debounceTimer:null,lastQueryBox:null},{initOverlay:s,destroyOverlay:a,viewportBox:c,clearRendered:l,hideOnMapCredit:u,renderRecords:h,focusNearest:d,clearSelection:f,updateSelectedAnchor:p,installInteraction:g}=q$({state:r,services:t,source:e});function _(M,w=null){r.status===M&&r.error===w||(r.status=M,r.error=w,n("alpr-status"))}function m(){r.enabled&&(clearTimeout(r.retryTimer),r.retryDelayMs=S$(r.retryDelayMs),r.retryAt=Date.now()+r.retryDelayMs,r.retryTimer=setTimeout(()=>{r.retryTimer=null,r.retryAt=0,r.enabled&&!r.loading&&y()},r.retryDelayMs))}function b({resetBackoff:M=!0}={}){clearTimeout(r.retryTimer),r.retryTimer=null,r.retryAt=0,M&&(r.retryDelayMs=0)}function C(){r.enabled&&(b({resetBackoff:!1}),clearTimeout(r.debounceTimer),r.debounceTimer=setTimeout(()=>{r.debounceTimer=null,y()},A$))}async function y(){var k,T;if(!r.enabled||!r.viewer)return;clearTimeout(r.debounceTimer),r.debounceTimer=null,b({resetBackoff:!1});const M=c(r.viewer);if(!M){(k=r.abort)==null||k.abort(),r.abort=null,r.pendingQueryBox=null,r.loading=!1,r.retrying=!1,b(),h(),_("zoom-in");return}if(r.lastQueryBox&&Hh(r.lastQueryBox,M)&&r.lastUpdate&&Date.now()-r.lastUpdate0,_("loading"),h();try{const I=await e.fetch(w,E.signal);if(E.signal.aborted||r.abort!==E||!r.enabled)return;const{records:R,stale:S,saturated:A}=V$(I);r.records=R,r.recordById=new Map(R.map(L=>[L.id,L])),r.lastUpdate=Date.now(),r.stale=S,r.saturated=A||R.length>vE,r.lastQueryBox=w,b(),h(),_(r.dataSource.entities.values.length?S?"stale":"ready":"empty")}catch(I){if((I==null?void 0:I.name)==="AbortError"||E.signal.aborted||r.abort!==E||!r.enabled)return;r.stale=!!r.lastUpdate,_("unavailable",(I==null?void 0:I.message)||"Camera source temporarily unavailable"),m()}finally{r.abort===E&&(r.abort=null,r.pendingQueryBox=null,r.loading=!1,r.retrying=!1,n("alpr-status"))}}return{id:qn,name:"ALPR Cameras",icon:"📷",source:e.label||"Mapped camera locations",updateInterval:0,statsRefreshInterval:1e3,init(M){var E;if(r.viewer)throw new Error("ALPR layer is already initialized");r.viewer=M,r.dataSource=new Cesium.CustomDataSource("alpr-cameras");const w=H$(e.attribution);r.credit=w?new Cesium.Credit(w,!0):null,M.dataSources.add(r.dataSource),r.moveEndRemove=M.camera.moveEnd.addEventListener(C),r.postRenderRemove=(E=M.scene.postRender)==null?void 0:E.addEventListener(p),s(),g(M)},enable(){r.enabled||(r.enabled=!0,r.creditPresented=!1,i(qn,M=>r.recordById.has(M)),r.dataSource.show=!0)},disable(){var M;r.enabled=!1,u(),o(qn),b(),clearTimeout(r.debounceTimer),(M=r.abort)==null||M.abort(),r.abort=null,r.pendingQueryBox=null,r.loading=!1,r.retrying=!1,r.dataSource&&(r.dataSource.show=!1),f(),l(),_("idle")},update(){return y()},destroy(M=r.viewer){var w,E,k;this.disable(),a(),(w=r.moveEndRemove)==null||w.call(r),r.moveEndRemove=null,(E=r.postRenderRemove)==null||E.call(r),r.postRenderRemove=null,(k=r.clickHandler)==null||k.destroy(),r.clickHandler=null,l(),r.dataSource&&M&&M.dataSources.remove(r.dataSource,!0),r.dataSource=null,r.credit=null,r.creditPresented=!1,r.records=[],r.recordById=new Map,r.lastQueryBox=null,r.lastUpdate=null,r.error=null,r.status="idle",r.stale=!1,r.saturated=!1,r.viewer=null},getRowControls(){var w,E,k;const M=((w=r.dataSource)==null?void 0:w.entities.values.length)||0;return{chips:[{id:"find-camera",label:"SHOW NEAREST",title:(E=r.viewer)!=null&&E.trackedEntity?"Stop following the current object before navigating to a camera":"Move to the nearest loaded camera and show its details",disabled:!r.enabled||!M||!!((k=r.viewer)!=null&&k.trackedEntity),onClick:d}],legend:[{label:"Camera badges",color:Vh,count:M,blurb:"Cyan cameras turn coral when selected. Wedges illustrate mapped direction, not measured coverage. Nearby cameras may be outside the screen."}]}},getStats(){var M,w;return{count:((M=r.dataSource)==null?void 0:M.entities.values.length)||0,countLabel:r.enabled?`${((w=r.dataSource)==null?void 0:w.entities.values.length)||0} nearby`:"",lastUpdate:r.lastUpdate,stale:r.stale,saturated:r.saturated,error:r.error,status:r.status,loading:r.loading,retryAt:r.retryAt,retrying:r.retrying,retryInSec:r.retryAt?Math.max(0,Math.ceil((r.retryAt-Date.now())/1e3)):0,loadingLabel:r.loading?r.retrying?"retrying mapped ALPR cameras":"loading mapped ALPR cameras":r.status==="zoom-in"?"Zoom in to load mapped cameras":[r.stale?"Showing cached locations":"",r.saturated?"Coverage limited — zoom in":"",r.status==="empty"?"No mapped cameras returned — coverage is incomplete":""].filter(Boolean).join(" · ")}}}}function Y$({surface:e,source:t}){const{groundFloor:n}=e;return K$({source:t,services:{render:Pt,context:Go,picking:rn,groundFloor:n,overlays:{registerPaintLane:Yl,keyholeAlpha:si,refreshReadout:Uv,subscribeMapStack(i){return window.addEventListener("gev:map-stack-changed",i),()=>window.removeEventListener("gev:map-stack-changed",i)}}}})}const wE=["flights","military"],X$=["ais-live-vessels","military-installations"],Uh=[...wE,...X$],Q$=750,Z$=175,J$=250,e4=250,t4=1e4,Kn=3,n4=10,gc=2e4,i4=1e4,o4=2500,Db=3e3,ja={flights:"OpenSky",military:"adsb.lol","ais-live-vessels":"AISStream","military-installations":"OpenStreetMap"},yn=Object.freeze({LIVE:"live",MISSING:"missing",UNCHECKED:"unchecked"});function r4({state:e,services:t,parts:n,source:i}){const o=t.flights,r=t.military;function s(_,m=(b=>(b=globalThis.document)==null?void 0:b.body)()){var y;return!(_==="ais-live-vessels"||_==="military-installations")||!((y=m==null?void 0:m.classList)!=null&&y.contains("cockpit-mode"))}function a(_){return _?Z$:Q$}function c({nowMs:_,lastRefreshMs:m,lastPoseChangeMs:b,wasMoving:C}){const y=_-b=a(!0)&&(y||v||M>=a(!1));return{moving:y,refresh:w}}function l(_){return(_==null?void 0:_.reason)==="evicted"}function u({force:_,hasResults:m,movementM:b,sourceRevisionChanged:C}){return!!(_||!m||C||!Number.isFinite(b)||b>=e4)}function h(_){if(!(_!=null&&_.subject))return null;const m=y=>{const v=Array.isArray(_.cohorts)?_.cohorts.find(M=>(M==null?void 0:M.id)===y):null;return Number.isFinite(v==null?void 0:v.count)?v.count:"unknown"},b=m("flights"),C=m("military");return{centeredOn:_.subject.label||_.subject.id||null,radiusKm:Number.isFinite(_.radiusM)?Math.round(_.radiusM/1e3):null,aircraft:Number.isFinite(b)&&Number.isFinite(C)?b+C:"unknown",flights:b,military:C,vessels:m("ais-live-vessels")}}function d(_,m={},{subjectPresent:b=!0}={}){return _?{subject:{..._.subject},subjectPresent:b!==!1,evaluatedAt:_.evaluatedAt,radiusM:_.radiusM,cohorts:_.cohorts.map(C=>({id:C.id,label:C.label,source:C.source,coverage:C.coverage||null,relationship:C.summary.relationship,count:C.summary.count,reason:C.summary.reason,nearest:C.summary.nearest.slice()})),navigation:{...m}}:null}function f(){return{canPrevious:e.navigationIndex>0,canFocus:!!e.subject,canNext:n.navigation.canNavigateNext()}}function p({cameraMoving:_=e.cameraMoving,hasSubject:m=!!e.subject,hasLiveResults:b=n.panel.awarenessResultsAreLive(e.results)}={}){return!!(_&&m&&b)}function g(){var _,m;(_=o.stopTracking)==null||_.call(o),(m=r.stopTracking)==null||m.call(r)}return{contextTargetFlyToAllowed:s,awarenessRefreshIntervalMs:a,awarenessRefreshDecision:c,awarenessClearIsEviction:l,awarenessRefreshRequired:u,contactsWindowFromSnapshot:h,buildAwarenessContextSnapshot:d,navigationState:f,awarenessNeedsContinuousRender:p,releaseAircraftTracking:g}}const Fn=25e4,bl=16e6,ws=Object.freeze({NEARBY:"NEARBY",OUTSIDE_RANGE:"OUTSIDE_RANGE",UNKNOWN:"UNKNOWN"});function s4(e,{initialRadiusM:t=Fn,maxRadiusM:n=bl}={}){if(typeof e!="function"||!Number.isFinite(t)||t<=0||!Number.isFinite(n)||nNumber.isFinite((r==null?void 0:r.distanceM)??(r==null?void 0:r.distance))&&(r.distanceM??r.distance)>=0).map(r=>({...r,distanceM:r.distanceM??r.distance})).sort((r,s)=>r.distanceM-s.distanceM);return{relationship:o.length?ws.NEARBY:ws.UNKNOWN,count:o.length,nearest:o.slice(0,i),reason:o.length?"observed or mapped nearby context":"no observed or mapped objects in current feeds"}}function l4(e,t=null,n=[]){var r,s;const i=new Set(n),o=[];for(const a of Array.isArray(e)?e:[]){const c=a==null?void 0:a.id;if(!["flights","military","ais-live-vessels","military-installations"].includes(c))continue;const l=Array.isArray((r=a==null?void 0:a.summary)==null?void 0:r.navigationNearest)?a.summary.navigationNearest:Array.isArray((s=a==null?void 0:a.summary)==null?void 0:s.nearest)?a.summary.nearest:[];for(const u of l){const h=(u==null?void 0:u.icao24)||(u==null?void 0:u.mmsi)||(u==null?void 0:u.id);if(!h)continue;const d=`${c}:${h}`;d!==`${t==null?void 0:t.layerId}:${t==null?void 0:t.id}`&&o.push({layerId:c,id:String(h),item:u,visited:i.has(d)})}}return o.sort((a,c)=>{const l=Number(a.visited)-Number(c.visited);if(l)return l;const u=+(a.layerId!==(t==null?void 0:t.layerId))-+(c.layerId!==(t==null?void 0:t.layerId));return u||(a.item.distanceM??1/0)-(c.item.distanceM??1/0)}),o}function c4({state:e,services:t,parts:n,source:i}){const o=t.vessels,r=t.installations,s=t.flights,a=t.military;function c(w,E){return!!(w!=null&&w.layerId&&(E==null?void 0:E.layerId)===w.layerId)}function l(w,E=n.queries.collectSourceStates()){const k=w==null?void 0:w.position;if(!k)return null;const T=E.flights,I=E.military,R=E["ais-live-vessels"],S=E["military-installations"],{flights:A,military:L}=n.queries.collectAircraftProximityWindow(k,{subject:w}),F=o.getNearby(k,Fn,gc).filter(O=>!n.queries.isSame(w,O,"ais-live-vessels","mmsi")),P=r.getNearby(k,Fn,gc).filter(O=>!n.queries.isSame(w,O,"military-installations","id"));return{subject:w,evaluatedAt:Date.now(),radiusM:Fn,cohorts:[{id:"flights",label:"Flights",source:T.stats.source||ja.flights,summary:n.navigation.summarizeAwarenessCohortForNavigation(A,T)},{id:"military",label:"Military flights",source:I.stats.source||ja.military,summary:n.navigation.summarizeAwarenessCohortForNavigation(L,I)},{id:"ais-live-vessels",label:"AIS vessels",source:R.stats.source||ja["ais-live-vessels"],summary:n.navigation.summarizeAwarenessCohortForNavigation(F,R)},{id:"military-installations",label:"Mapped installations",source:S.stats.source||ja["military-installations"],coverage:"CURRENT VIEWPORT ONLY",summary:n.queries.summarizeInstallationViewport(P,S)}]}}function u(w){return w?`${w.layerId}:${w.id}`:""}function h(w){return String(w||"").trim().toLowerCase()}function d(w){return w?`${h(w.layerId)}:${h(w.id)}`:""}function f(){var k,T,I,R;const w=h((T=(k=e.viewer)==null?void 0:k.trackedEntity)==null?void 0:T.gevTrackedId);return w&&[(I=s.getTrackedSubject)==null?void 0:I.call(s),(R=a.getTrackedSubject)==null?void 0:R.call(a)].find(S=>d(S)===w)||null}function p(){var E,k,T;const w=(k=(E=e.results)==null?void 0:E.cohorts)==null?void 0:k.find(I=>{var R;return I.id===((R=e.subject)==null?void 0:R.layerId)});return((T=w==null?void 0:w.summary)==null?void 0:T.relationship)===ws.UNKNOWN&&w.summary.count===null}function g(w){if(!e.enabled||!(w!=null&&w.position))return;n.panel.startAwarenessPageRotation();const E=u(w);e.navigationVisited.add(E);const k=e.suppressedHistoryKey===E;if(e.pendingSelectionKey=null,e.suppressedHistoryKey=null,!k){const T=e.navigationHistory[e.navigationIndex];u(T)!==E&&(e.navigationHistory.splice(e.navigationIndex+1),e.navigationHistory.push({...n.history.historySubjectSnapshot(w,n.history.historySourceItem(w)),position:Cesium.Cartesian3.clone(w.position)}),e.navigationIndex=e.navigationHistory.length-1)}e.subject=w,e.subjectMissing=!1,C(!0)}function _(w,{allowCollectionMaterialization:E=!0}={}){var k,T,I,R,S;if(!(w!=null&&w.position))return null;if(w.layerId==="flights"||w.layerId==="military"){const A=(I=(T=(k=e.viewer)==null?void 0:k.trackedEntity)==null?void 0:T.gevDisplayPosition)==null?void 0:I.call(T);if(A)return{position:Cesium.Cartesian3.clone(A),presence:String(((S=(R=e.viewer)==null?void 0:R.trackedEntity)==null?void 0:S.gevTrackedId)||"")===u(w)?yn.LIVE:yn.UNCHECKED};if(!E)return{position:Cesium.Cartesian3.clone(w.position),presence:yn.UNCHECKED};const L=w.layerId==="flights"?s:a;return m(w,L.getAllPositions(1e3),L)}return w.layerId==="ais-live-vessels"?E?m(w,o.getAllPositions(12e3),o):{position:Cesium.Cartesian3.clone(w.position),presence:yn.UNCHECKED}:{position:Cesium.Cartesian3.clone(w.position),presence:yn.LIVE}}function m(w,E,k){var A;const I=(Array.isArray(E)?E:[]).find(L=>String(L.id)===String(w.id)),R=(A=k==null?void 0:k.hasContact)==null?void 0:A.call(k,w.id),S=R===!0?yn.LIVE:R===!1?yn.MISSING:yn.UNCHECKED;return{position:I!=null&&I.position?Cesium.Cartesian3.clone(I.position):Cesium.Cartesian3.clone(w.position),presence:S}}function b(w){var T;if(!n.navigation.isFlightLayer(w==null?void 0:w.layerId))return w==null?void 0:w.label;const E=w.layerId==="flights"?s:a,k=(T=E.getTrackedSubject)==null?void 0:T.call(E);return k!=null&&k.label&&String(k.id)===String(w.id)?k.label:w.label}function C(w=!1){var P,O;if(!e.enabled||!e.subject)return;const E=n.queries.collectSourceStates(),k=n.queries.sourceRevision(E),T=k!==e.sourceRevision,I=_(e.subject,{allowCollectionMaterialization:!((O=(P=document.body)==null?void 0:P.classList)!=null&&O.contains("cockpit-mode"))||T});if(!I)return;const{position:R,presence:S}=I;S===yn.LIVE?e.subjectMissing=!1:S===yn.MISSING&&(e.subjectMissing=!0);const A=b(e.subject),L=A!==e.subject.label;e.subject={...e.subject,position:R,label:A};const F=e.lastEvaluatedPosition?Cesium.Cartesian3.distance(e.lastEvaluatedPosition,R):1/0;if(!n.model.awarenessRefreshRequired({force:w,hasResults:!!e.results,movementM:F,sourceRevisionChanged:T})){e.results.subject=e.subject,n.rendering.renderVisual(e.subject),L&&n.panel.renderResults(),n.rendering.scheduleDirectionOverlayUpdate(w);return}e.results=l(e.subject,E),e.sourceRevision=k,e.lastEvaluatedPosition=Cesium.Cartesian3.clone(R,e.lastEvaluatedPosition);for(const D of e.results.cohorts){const $=Math.max(0,Math.floor(Math.max(0,D.summary.nearest.length-1)/Kn)*Kn);e.cohortPages.set(D.id,Math.min(e.cohortPages.get(D.id)||0,$))}n.rendering.renderVisual(e.subject),n.panel.renderResults(),n.rendering.scheduleDirectionOverlayUpdate(w)}function y(w){var T;if(!w||!["ais-live-vessels","military-installations"].includes(w.layerId))return null;const E=Number(w.latitude),k=Number(w.longitude);return!Number.isFinite(E)||!Number.isFinite(k)?null:{layerId:w.layerId,id:((T=w.properties)==null?void 0:T.mmsi)||w.id,label:w.label||w.id,position:Cesium.Cartesian3.fromDegrees(k,E,0)}}function v(){e.subject&&(e.subjectMissing=!0)}function M(){e.autoFocusRetryPending=!1,e.subject=null,e.subjectMissing=!1,e.results=null,e.navigationHistory=[],e.navigationVisited.clear(),e.navigationIndex=-1,e.suppressedHistoryKey=null,e.pendingSelectionKey=null,e.lastEvaluatedPosition=null,e.sourceRevision="",e.cohortPages.clear(),n.panel.stopAwarenessPageRotation(),n.rendering.clearVisual(),n.panel.hidePanel()}return{awarenessClearMatchesSubject:c,evaluateSubject:l,subjectKey:u,normalizeContextId:h,normalizedSubjectKey:d,currentTrackedFlightSubject:f,subjectCohortFeedUnknown:p,selectSubject:g,resolveSubjectPosition:_,collectionSubjectPosition:m,resolveSubjectLabel:b,refreshSelectedSubject:C,subjectFromContext:y,markSubjectEvicted:v,clearAwarenessSubject:M}}function u4({state:e,services:t,parts:n,source:i}){function o(){if(e.panel)return e.panel;const m=document.getElementById("military-awareness-panel"),b=m||document.createElement("aside");return e.panelOwned=!m,m||(b.id="military-awareness-panel"),e.panelClickListener=C=>{const y=C.target.closest("button[data-awareness-action]");if(y){C.preventDefault(),y.dataset.awarenessAction==="previous"&&n.history.navigateHistory(-1,{origin:"user"}),y.dataset.awarenessAction==="next"&&n.history.navigateHistory(1,{origin:"user"}),y.dataset.awarenessAction==="focus"&&n.focus.focusCurrentSubject({origin:"user"});return}const v=C.target.closest("button[data-awareness-layer][data-awareness-id]");v&&(C.preventDefault(),n.focus.requestFocus(v.dataset.awarenessLayer,v.dataset.awarenessId,!1,{origin:"user"}))},b.addEventListener("click",e.panelClickListener),m||document.body.appendChild(b),e.panel=b,b}function r(){if(e.panel){const m=`
+ ${e.enabled?"CONTEXT READY":"GLOBAL CONTEXT OFF"} + ${e.enabled?"SELECT A FLIGHT, VESSEL, OR MAPPED INSTALLATION":"ENABLE TO LOAD OBSERVED / MAPPED PROXIMITY"} +
`;e.panel.hidden=!1,e.panelMarkup!==m&&(e.panel.innerHTML=m,e.panelMarkup=m)}e.directionRoot&&(e.directionRoot.hidden=!0)}function s(m){const b=m.summary,C=b.count===null?"?":String(b.count),y=e.cohortPages.get(m.id)||0,v=b.nearest.slice(y,y+Kn).map(k=>{const T=au(k),I=k.icao24||k.mmsi||k.id;if(!I)return`
  • ${h(T)} ${Cl(k.distanceM)}
  • `;const R=T==="—"?"Unavailable":T;return`
  • `}).join(""),M=Math.max(1,Math.ceil(b.nearest.length/Kn)),w=M>1?` · ${Math.floor(y/Kn)+1}/${M}`:"",E=m.coverage?` · ${h(m.coverage)}`:"";return`
    +
    ${h(m.label)}${C}${w}
    + ${h(m.source)}${E} · ${h(b.reason)} + ${v?`
      ${v}
    `:""} +
    `}function a(){return`
    + + + +
    `}function c(m){var C;const b=(C=m==null?void 0:m.closest)==null?void 0:C.call(m,"button[data-awareness-action], button[data-awareness-layer][data-awareness-id]");return b?b.dataset.awarenessAction?`action:${b.dataset.awarenessAction}`:`target:${b.dataset.awarenessLayer}:${b.dataset.awarenessId}`:null}function l(m,b=document.activeElement){var y,v;if(!((y=m==null?void 0:m.contains)!=null&&y.call(m,b)))return null;if((v=b==null?void 0:b.matches)!=null&&v.call(b,"[data-awareness-focus-continuation]"))return{key:"continuation"};const C=c(b);return C?{key:C}:null}function u(m,b){var w;if(!m||!b)return null;const C=m.querySelector("[data-awareness-focus-continuation]"),y=[...m.querySelectorAll("button[data-awareness-action], button[data-awareness-layer][data-awareness-id]")].filter(E=>!E.disabled),M=(b.key==="continuation"?C:y.find(E=>c(E)===b.key))||C;return(w=M==null?void 0:M.focus)==null||w.call(M,{preventScroll:!0}),M||null}function h(m){return String(m??"").replace(/[&<>'"]/g,b=>({"&":"&","<":"<",">":">","'":"'",'"':"""})[b])}function d(){if(!e.enabled||!e.results)return r();const m=o(),{subject:b,cohorts:C}=e.results,y=`
    ${h(b.label)} · ${Cl(Fn)} FLIGHT / VESSEL WINDOW
    + ${a()} + ${C.map(s).join("")} +

    Open-source mapped/observed context. Missing broadcasts, unloaded map areas, or unmapped sites are not evidence of absence.

    `;if(m.hidden=!1,e.panelMarkup!==y){const v=l(m);m.innerHTML=y,e.panelMarkup=y,u(m,v)}}function f(){if(!e.enabled||!e.results)return;let m=!1;for(const b of e.results.cohorts){const C=Math.max(1,Math.ceil(b.summary.nearest.length/Kn));if(C<=1)continue;const y=e.cohortPages.get(b.id)||0;e.cohortPages.set(b.id,(Math.floor(y/Kn)+1)%C*Kn),m=!0}m&&(d(),n.rendering.scheduleDirectionOverlayUpdate(!0))}function p(){e.pageTimer||(e.pageTimer=window.setInterval(f,t4))}function g(){e.pageTimer&&window.clearInterval(e.pageTimer),e.pageTimer=null}function _(m){return(Array.isArray(m==null?void 0:m.cohorts)?m.cohorts:[]).some(C=>{var y;return Number((y=C==null?void 0:C.summary)==null?void 0:y.count)>0})}return{ensurePanel:o,hidePanel:r,rowHtml:s,navigationControlsHtml:a,awarenessPanelControlKey:c,captureAwarenessPanelFocus:l,restoreAwarenessPanelFocus:u,escapeHtml:h,renderResults:d,rotateAwarenessPages:f,startAwarenessPageRotation:p,stopAwarenessPageRotation:g,awarenessResultsAreLive:_}}function d4({state:e,services:t,parts:n,source:i}){const o=t.flights,r=t.military;function s(d){var y,v,M,w,E,k,T,I;const f=((v=(y=e.dataManager)==null?void 0:y.getLayerLifecycleState)==null?void 0:v.call(y,d))||null,p=(f==null?void 0:f.enabled)===!0||((M=e.dataManager)==null?void 0:M.isEnabled(d))===!0,g=(f==null?void 0:f.lifecycleState)==="enabling",_=((I=(T=(k=(E=(w=e.dataManager)==null?void 0:w.layers)==null?void 0:E.get(d))==null?void 0:k.module)==null?void 0:T.getStats)==null?void 0:I.call(T))||{},m=g?{..._,loading:!0,status:"loading"}:_,b=m.loading===!0&&!m.lastUpdate;return{available:!(g||!p||b||["unavailable","zoom-in"].includes(m.status)||!!(m.error&&m.count===0)),stale:!!m.stale,stats:m}}function a(){return Object.fromEntries(Uh.map(d=>[d,s(d)]))}function c(d){return Uh.map(f=>{const p=d[f],g=(p==null?void 0:p.stats)||{};return[f,p==null?void 0:p.available,p==null?void 0:p.stale,g.lastUpdate||null,g.count??null,g.status||null,g.error||null]}).map(f=>f.join(":")).join("|")}function l(d,f,p,g){return(d==null?void 0:d.layerId)===p&&String(d.id)===String(f==null?void 0:f[g])}function u(d,f){var g;const p=n.navigation.summarizeAwarenessCohortForNavigation(d,f);return p.count===null?(g=f.stats)!=null&&g.statusMessage?{...p,reason:f.stats.statusMessage}:p:{...p,reason:p.count?"mapped matches from the loaded viewport":"viewport feed is not a complete 250 km survey"}}function h(d,{radiusM:f=Fn,subject:p=null}={}){if(!d)return null;const g=o.getNearby(d,f,gc,{includeHidden:!0}).filter(m=>!p||!l(p,m,"flights","icao24")),_=r.getNearby(d,f,gc,{includeHidden:!0}).filter(m=>!p||!l(p,m,"military","icao24"));return{flights:g,military:_,aircraft:g.length+_.length}}return{sourceState:s,collectSourceStates:a,sourceRevision:c,isSame:l,summarizeInstallationViewport:u,collectAircraftProximityWindow:h}}function h4({state:e,services:t,parts:n,source:i}){const o=t.flights,r=t.military;function s(m,b,{displayLimit:C=n4,navigationLimit:y=i4}={}){const v=a4(m,{...b,limit:y});return v.count===null?v:{...v,nearest:v.nearest.slice(0,C),navigationNearest:v.nearest}}function a(){e.navigationVisited.clear();const m=n.subject.subjectKey(e.subject);m&&e.navigationVisited.add(m)}function c(m){return m==="flights"||m==="military"}function l(m){return String(m||"").trim().toLowerCase()}function u(m,b){const C=l(b);if(!C)return!0;const y=[m==null?void 0:m.aircraftClass,m==null?void 0:m.klass,m==null?void 0:m.type,m==null?void 0:m.typeCode,m==null?void 0:m.typeName].map(v=>l(v)).filter(Boolean);return y.length?y.some(v=>v===C||v.includes(C)):!1}function h(m,b,C,{targetLayer:y=null,aircraftClass:v=null,aircraftOnly:M=!1}={}){let w=l4(m,b,C);return M&&(w=w.filter(E=>c(E.layerId))),y&&(w=w.filter(E=>E.layerId===y)),v&&(w=w.filter(E=>u(E.item,v))),w}function d({targetLayer:m=null,aircraftClass:b=null}={}){var v,M;if(!c((v=e.subject)==null?void 0:v.layerId)||!((M=e.subject)!=null&&M.position)||m&&!c(m))return!1;const C=m==="military"?[]:o.getNearby(e.subject.position,bl,2,{includeHidden:!0}).filter(w=>u(w,b)),y=m==="flights"?[]:r.getNearby(e.subject.position,bl,2,{includeHidden:!0}).filter(w=>u(w,b));return[["flights",C],["military",y]].some(([w,E])=>E.some(k=>`${w}:${k.icao24||k.id}`!==n.subject.subjectKey(e.subject)))}function f(m,b,C,{targetLayer:y=null,aircraftClass:v=null}={}){var E;if(!((E=e.subject)!=null&&E.position))return null;const M=new Set(b);if(y&&!c(y))return null;const w=[...y==="military"?[]:o.getNearby(e.subject.position,m,25e3,{includeHidden:!0}).filter(k=>u(k,v)).map(k=>({layerId:"flights",id:String(k.icao24),item:k})),...y==="flights"?[]:r.getNearby(e.subject.position,m,5e3,{includeHidden:!0}).filter(k=>u(k,v)).map(k=>({layerId:"military",id:String(k.icao24),item:k}))].filter(k=>{const T=`${k.layerId}:${k.id}`;return T===n.subject.subjectKey(e.subject)?!1:!C||!M.has(T)});return w.sort((k,T)=>(k.item.distanceM??k.item.distance??1/0)-(T.item.distanceM??T.item.distance??1/0)),w[0]||null}function p(m={}){var v;if(!c((v=e.subject)==null?void 0:v.layerId))return null;let b=[...e.navigationVisited];const C=()=>s4(M=>f(M,b,!0,m),{initialRadiusM:Fn,maxRadiusM:bl}),y=C();return y||(a(),b=[...e.navigationVisited],C())}function g({hasForwardHistory:m=!1,hasExpandedFlightTarget:b=!1,hasNearbyTarget:C=!1,subjectCohortUnknown:y=!1}={}){return!!(m||!y&&(b||C))}function _({targetLayer:m=null,aircraftClass:b=null}={}){var C;return g({hasForwardHistory:n.history.findCompatibleHistoryIndex(e.navigationHistory,e.navigationIndex,1,{targetLayer:m,aircraftClass:b,resolveItem:n.history.historySubjectItem})!==-1,hasNearbyTarget:h((C=e.results)==null?void 0:C.cohorts,e.subject,[...e.navigationVisited],{targetLayer:m,aircraftClass:b}).length>0,hasExpandedFlightTarget:d({targetLayer:m,aircraftClass:b}),subjectCohortUnknown:n.subject.subjectCohortFeedUnknown()})}return{summarizeAwarenessCohortForNavigation:s,resetNavigationVisitedCycle:a,isFlightLayer:c,normalizeAircraftClass:l,aircraftClassMatchesFilter:u,selectNavigationTargets:h,alternativeFlightAvailable:d,closestFlightWithinRadius:f,findExpandedFlightTarget:p,canNavigateAwarenessNext:g,canNavigateNext:_}}function f4({state:e,services:t,parts:n,source:i}){const o=t.flights,r=t.military,{announceNavigationAuthority:s}=t.navigation,a=t.installations,c=t.vessels;function l(_,m,{origin:b="programmatic"}={}){var y,v;if(!_||!m)return!1;if(_==="flights")return((y=o.refocusTrackedById)==null?void 0:y.call(o,m,{origin:b}))||o.trackById(m,{origin:b});if(_==="military")return((v=r.refocusTrackedById)==null?void 0:v.call(r,m,{origin:b}))||r.trackById(m,{origin:b});if(_==="military-installations")return n.model.contextTargetFlyToAllowed(_)?(s("context-installation-focus"),a.focusById(m)):u(_,m);if(_!=="ais-live-vessels"||!c.selectById(m))return!1;const C=c.getAllPositions(12e3).find(M=>String(M.id)===String(m));return!n.model.contextTargetFlyToAllowed(_)||!(C!=null&&C.position)||!e.viewer||(s("context-vessel-focus"),e.viewer.camera.flyToBoundingSphere(new Cesium.BoundingSphere(C.position,Db),{duration:1.4})),!0}function u(_,m){var y;const b=`${_}:${m}`,C=[e.subject,...e.navigationHistory,...(((y=e.results)==null?void 0:y.cohorts)||[]).flatMap(v=>v.id===_?v.summary.navigationNearest||v.summary.nearest||[]:[])].find(v=>v&&`${v.layerId||_}:${v.id||v.mmsi}`===b);return C!=null&&C.position?(n.model.contextTargetFlyToAllowed(_)&&n.model.releaseAircraftTracking(),n.subject.selectSubject({...C,layerId:_,id:String(C.id||C.mmsi),label:C.label||C.name||C.callsign||String(m),position:Cesium.Cartesian3.clone(C.position)}),!0):!1}function h(_,m,b=!1,{origin:C="programmatic"}={}){const y=`${_}:${m}`;e.pendingSelectionKey=y,b&&(e.suppressedHistoryKey=y);const v=l(_,m,{origin:C});return e.pendingSelectionKey=null,e.suppressedHistoryKey=null,v}function d(_,m=!1,b={}){return _?h(_.layerId,_.id,m,b):!1}function f(_={}){return d(e.subject,!0,_)}function p(_){var y,v;if(!Array.isArray(_)||!_.length)return null;const m=(v=(y=e.viewer)==null?void 0:y.camera)==null?void 0:v.positionWC;if(!m)return _.find(M=>M==null?void 0:M.position)||null;let b=null,C=1/0;for(const M of _){if(!(M!=null&&M.position))continue;const w=Cesium.Cartesian3.distance(m,M.position);Number.isFinite(w)&&w({...b,layerId:"military"})),...o.getAllPositions(1e3).map(b=>({...b,layerId:"flights"}))]);if(_&&(_.layerId==="military"?r:o).trackById(_.id,{origin:"programmatic"}))return e.autoFocusAttempted=!0,!0;const m=p(c.getAllPositions(12e3));return!m||!c.selectById(m.id)?!1:(e.autoFocusAttempted=!0,n.model.contextTargetFlyToAllowed("ais-live-vessels")&&(s("context-vessel-autofocus",{cancelPendingSelection:!1}),e.viewer.camera.flyToBoundingSphere(new Cesium.BoundingSphere(m.position,Db),{duration:1.6})),!0)}return{focusNearbyTarget:l,selectKnownContextTarget:u,requestFocus:h,focusSubject:d,focusCurrentSubject:f,closestToCurrentView:p,focusAttentionTarget:g}}function m4({state:e,services:t,parts:n,source:i}){function o(){return{historyKeys:e.navigationHistory.map(n.subject.subjectKey),navigationVisitedKeys:[...e.navigationVisited],historyLength:e.navigationHistory.length,navigationIndex:e.navigationIndex,suppressedHistoryKey:e.suppressedHistoryKey,pendingSelectionKey:e.pendingSelectionKey}}return{_getAwarenessNavigationStateForTest:o}}function p4({state:e,services:t,parts:n,source:i}){const o=t.military,r=t.flights;function s(d,{targetLayer:f,aircraftClass:p,aircraftOnly:g,origin:_="programmatic"}){let m=e.navigationIndex;for(;;){const b=h(e.navigationHistory,m,d,{targetLayer:f,aircraftClass:p,aircraftOnly:g,resolveItem:c});if(b===-1)return!1;if(n.focus.focusSubject(e.navigationHistory[b],!0,{origin:_}))return e.navigationIndex=b,!0;m=b}}function a(d,{targetLayer:f=null,aircraftClass:p=null,aircraftOnly:g=!1,origin:_="programmatic"}={}){var M,w,E,k;if(s(d,{targetLayer:f,aircraftClass:p,aircraftOnly:g,origin:_}))return!0;if(d<0)return!1;let m=n.navigation.selectNavigationTargets((M=e.results)==null?void 0:M.cohorts,e.subject,[...e.navigationVisited],{targetLayer:f,aircraftClass:p,aircraftOnly:g});const b=m.length>0&&m.every(T=>T.visited),C=n.subject.subjectCohortFeedUnknown();if(b&&n.navigation.isFlightLayer((w=e.subject)==null?void 0:w.layerId)&&!C){const T=n.navigation.findExpandedFlightTarget({targetLayer:f,aircraftClass:p});if(T)return n.focus.requestFocus(T.candidate.layerId,T.candidate.id,!1,{origin:_})}b&&(n.navigation.resetNavigationVisitedCycle(),m=n.navigation.selectNavigationTargets((E=e.results)==null?void 0:E.cohorts,e.subject,[...e.navigationVisited],{targetLayer:f,aircraftClass:p,aircraftOnly:g}));const y=m.some(T=>n.navigation.isFlightLayer(T.layerId));if(n.navigation.isFlightLayer((k=e.subject)==null?void 0:k.layerId)&&!y&&!C){const T=n.navigation.findExpandedFlightTarget({targetLayer:f,aircraftClass:p});if(T)return n.focus.requestFocus(T.candidate.layerId,T.candidate.id,!1,{origin:_})}if(n.subject.subjectCohortFeedUnknown())return!1;const v=m[0];return v?n.focus.requestFocus(v.layerId,v.id,!1,{origin:_}):!1}function c(d){var g,_,m,b;if(!d)return null;const f=(_=(g=e.results)==null?void 0:g.cohorts)==null?void 0:_.find(C=>C.id===d.layerId);return(((m=f==null?void 0:f.summary)==null?void 0:m.navigationNearest)||((b=f==null?void 0:f.summary)==null?void 0:b.nearest)||[]).find(C=>String((C==null?void 0:C.icao24)||(C==null?void 0:C.mmsi)||(C==null?void 0:C.id))===String(d.id))||d}function l(d,f=null){const p=(f==null?void 0:f.aircraftClass)||(f==null?void 0:f.klass)||(f==null?void 0:f.type)||(d==null?void 0:d.aircraftClass)||null;return p?{...d,aircraftClass:p}:{...d}}function u(d){var m,b,C,y;if(!n.navigation.isFlightLayer(d==null?void 0:d.layerId)||!(d!=null&&d.position))return null;const f=(b=(m=e.results)==null?void 0:m.cohorts)==null?void 0:b.find(v=>v.id===d.layerId),g=(((C=f==null?void 0:f.summary)==null?void 0:C.navigationNearest)||((y=f==null?void 0:f.summary)==null?void 0:y.nearest)||[]).find(v=>String((v==null?void 0:v.icao24)||(v==null?void 0:v.id))===String(d.id));return g||(d.layerId==="military"?o:r).getNearby(d.position,1e3,25,{includeHidden:!0}).find(v=>String((v==null?void 0:v.icao24)||(v==null?void 0:v.id))===String(d.id))||null}function h(d,f,p,{targetLayer:g=null,aircraftClass:_=null,aircraftOnly:m=!1,resolveItem:b=C=>C}={}){const C=p<0?-1:1;for(let y=f+C;y>=0&&y=i||p.bottom<=p.top||(p.bottom<=l?u=Math.max(u,p.bottom+a):p.top>=l&&(h=Math.min(h,p.top-a))));h=Math.max(u,h);const d=Math.max(0,h-u),f=Math.min(Math.max(0,t),d);return{top:c==="start"?u:u+Math.max(0,(d-f)*.5),maxHeight:d,safeTop:u,safeBottom:h,constrained:t>d}}function _4({hudVariant:e,hasExpandedPanel:t}){return e==="tactical"&&!!t}function jt(e){return Number.isFinite(e)?(e%360+360)%360:0}function b4(e,t,n){const i=jt(e),o=jt(t);if(!Number.isFinite(n)||n<=0)return i;const r=(o-i+540)%360-180,s=Math.max(-n,Math.min(n,r));return jt(i+s)}function C4(e,t,n){if(!Number.isFinite(e)||e<=0||!Number.isFinite(n)||n<=0)return 0;const i=Math.min(.1,n),o=Number.isFinite(t)?Math.max(0,t):0,r=e*(1-Math.exp(-1.25*i)),s=Math.max(.75,o*.22);return Math.min(e,r,s*i)}function Es(e,t,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<0?!1:!Number.isFinite(t)||t<=0||e=n}function y4(e,t,n=5e3){return![e,t,n].every(Number.isFinite)||n<0?!0:e-t>=n}function Ob(e,t,n){if(!Number.isFinite(e)||!Number.isFinite(t))return e;const i=Number.isFinite(n)?Math.max(0,n):0;return Math.max(e,t+i)}function v4(e,t){return t===!0?0:Number.isFinite(e)?e*3.28084:null}function M4(e,t,n=null){const i=typeof e=="string"?e.trim()||"—":Number.isFinite(e)?String(e):"—",o=Number.isFinite(t)&&t>=0?String(Math.round(t/1e3)):"—",r=typeof n=="string"?n.trim():"",s=`${i} · ${o} KM AIR/SEA WINDOW`;return r?`${s} · INSTALLATIONS ${r}`:s}function w4(e){const t=Math.round(jt(e)/30)*30;return[-90,-60,-30,0,30,60,90].map(n=>jt(t+n))}function E4(e){const t=jt(e);return new Map([[0,"N"],[45,"NE"],[90,"E"],[135,"SE"],[180,"S"],[225,"SW"],[270,"W"],[315,"NW"]]).get(t)||String(Math.round(t)).padStart(3,"0")}function T4(e){if(!Number.isFinite(e))return 500;const t=Math.max(0,e);return t<5e3?100:t<15e3?250:500}function k4(e,t=9){if(!Number.isFinite(e))return[];const n=Math.max(3,Math.floor(t)|1),i=Math.max(0,e),o=T4(i),r=i/o,s=Math.floor(r),a=Math.floor(n/2);return Array.from({length:n},(c,l)=>{const u=s+l-a,h=u-r;return{valueFt:Math.max(0,u*o),slot:h,depth:Math.abs(h),major:u%2===0,stepFt:o}})}function Bb(e){if(!Number.isFinite(e))return 0;const t=Math.min(.92,Math.abs(e)*.16);return 1-Math.sqrt(1-t**2)}function Vb(e){return Number.isFinite(e)?String(Math.max(0,Math.round(e))).padStart(5,"0"):"-----"}function A4(e){if(!Number.isFinite(e))return 25;const t=Math.max(0,e);return t<100?10:t<300?20:25}function I4(e,t=9){if(!Number.isFinite(e))return[];const n=Math.max(3,Math.floor(t)|1),i=Math.max(0,e),o=A4(i),r=i/o,s=Math.floor(r),a=Math.floor(n/2);return Array.from({length:n},(c,l)=>{const u=s+l-a,h=u-r;return{valueKt:Math.max(0,u*o),slot:h,depth:Math.abs(h),major:u%2===0,stepKt:o}})}function ad(e){return Number.isFinite(e)?String(Math.max(0,Math.round(e))).padStart(3,"0"):"---"}function Gm(e,t,n,i){if(![e,t,n,i].every(Number.isFinite))return null;const o=e*Math.PI/180,r=n*Math.PI/180,s=(i-t)*Math.PI/180,a=Math.sin(s)*Math.cos(r),c=Math.cos(o)*Math.sin(r)-Math.sin(o)*Math.cos(r)*Math.cos(s);return Math.abs(c)<1e-12&&Math.abs(a)<1e-12?null:jt(Math.atan2(a,c)*180/Math.PI)}function EE(e,t){return!Number.isFinite(e)||!Number.isFinite(t)?null:(jt(e)-jt(t)+540)%360-180}function R4({civilian:e=null,military:t=null,trackedId:n=""}={}){const i=[];if(e&&i.push({...e,layerId:"flights"}),t&&i.push({...t,layerId:"military"}),!i.length)return null;const o=String(n||"").trim().toLowerCase();if(o){const r=i.find(s=>`${s.layerId}:${s.icao24}`.toLowerCase()===o);if(r)return r}return i[0]}function L4({snapshot:e=null,info:t=null}={}){var r,s;if(!e)return{visible:!1,mode:"standby",subjectMatchesTracked:!1,aircraftRelative:!1,contactLost:!1};const n=(t==null?void 0:t.icao24)??(t==null?void 0:t.id),i=((r=e.subject)==null?void 0:r.layerId)===(t==null?void 0:t.layerId)&&String((s=e.subject)==null?void 0:s.id)===String(n),o=e.subjectPresent===!1;return{visible:!0,mode:o?"lost":i?"tracked":"foreign",subjectMatchesTracked:i,aircraftRelative:i,contactLost:o}}function P4({state:e,services:t,parts:n,source:i}){const{getKeyholeGeometry:o,celestialScreenAngle:r}=t.geometry,{governorRequestRender:s}=t.render;function a(){if(e.directionRoot||!e.viewer)return e.directionRoot;const f=document.createElement("div");f.id="military-awareness-direction-overlay",f.hidden=!0,f.setAttribute("aria-hidden","true");const p=document.createElement("div");p.className="military-awareness-compass-ring";const g=[["N",0],["E",90],["S",180],["W",270]];e.compassLabels=g.map(([m,b])=>{const C=document.createElement("span");return C.className=`military-awareness-compass-label cardinal-${m.toLowerCase()}`,C.textContent=m,C.dataset.bearing=String(b),f.appendChild(C),C});const _=document.createElement("span");return _.className="military-awareness-compass-heading",f.append(p,_),e.directionMarkers=Array.from({length:3},()=>{const m=document.createElement("div");m.className="military-awareness-direction-marker";const b=document.createElement("span");b.className="military-awareness-direction-arrow",b.textContent="➜";const C=document.createElement("span");return C.className="military-awareness-direction-label",m.append(b,C),m._arrow=b,m._label=C,m._lastAngle=0,f.appendChild(m),m}),e.compassRing=p,e.compassHeading=_,e.viewer.container.appendChild(f),e.directionRoot=f,f}function c(f=!1){if(e.directionFrame!==null||!e.enabled)return;const p=Date.now();!f&&p-e.lastDirectionUpdateMs{e.directionFrame=null,e.lastDirectionUpdateMs=Date.now(),u()}))}function l(){e.directionFrame!==null&&window.cancelAnimationFrame(e.directionFrame),e.directionFrame=null,e.lastDirectionUpdateMs=0}function u(){var E;const f=a();if(!f||!e.enabled||!((E=e.subject)!=null&&E.position)||!e.results){f&&(f.hidden=!0);return}const p=e.viewer.scene.canvas,g=p.clientWidth||p.width,_=p.clientHeight||p.height,m=o(g,_);if(!(m.radius>0)){f.hidden=!0;return}f.hidden=!1;const b=Math.max(120,Math.min(m.radius-48,m.radius*.66));e.compassRing.style.left=`${m.centerX-b}px`,e.compassRing.style.top=`${m.centerY-b}px`,e.compassRing.style.width=`${b*2}px`,e.compassRing.style.height=`${b*2}px`;const C=e.viewer.camera.heading||0,y=(Math.round(Cesium.Math.toDegrees(C))+360)%360;e.compassRing.style.setProperty("--compass-rotation",`${-y}deg`),e.compassHeading.textContent=`HDG ${String(y).padStart(3,"0")}°`,e.compassHeading.style.left=`${m.centerX}px`,e.compassHeading.style.top=`${m.centerY-b+39}px`;for(const k of e.compassLabels){const I=Cesium.Math.toRadians(Number(k.dataset.bearing))-C-Cesium.Math.PI_OVER_TWO,R=b-17;k.style.left=`${m.centerX+Math.cos(I)*R}px`,k.style.top=`${m.centerY+Math.sin(I)*R}px`}const v=e.results.cohorts.find(k=>k.id===e.subject.layerId)||e.results.cohorts.find(k=>k.id==="military"),M=e.cohortPages.get(v==null?void 0:v.id)||0,w=(v==null?void 0:v.summary.nearest.slice(M,M+Kn))||[];for(let k=0;k=250){for(const C of e.visual.entities)C.position.setValue(g);Cesium.Cartesian3.clone(g,e.visual.center),s("awareness-visual")}return}h();const m=[];m.push(e.viewer.entities.add({position:g,ellipse:{semiMajorAxis:Fn,semiMinorAxis:Fn,fill:!1,outline:!0,outlineColor:Cesium.Color.fromCssColorString("#62b5ff").withAlpha(.72),height:o4}})),e.visual={key:_,entities:m,center:Cesium.Cartesian3.clone(g)},s("awareness-visual")}return{ensureDirectionOverlay:a,scheduleDirectionOverlayUpdate:c,cancelDirectionOverlayUpdate:l,updateDirectionOverlay:u,clearVisual:h,renderVisual:d}}function x4({state:e,services:t,parts:n,source:i}){const{holdContinuousRender:o,releaseContinuousRender:r}=t.render;function s(h){return!(h!=null&&h.positionWC)||!Number.isFinite(h.heading)?"":qc(h)}function a(){e.enabled&&n.model.awarenessNeedsContinuousRender()?o("military-awareness"):r("military-awareness")}function c(){e.runtimeListenersAttached||!e.viewer||(window.addEventListener("gev:awareness-subject-selected",e.subjectListener),window.addEventListener("gev:entity-selected",e.contextListener),window.addEventListener("gev:entity-selection-cleared",e.clearListener),window.addEventListener("gev:awareness-subject-cleared",e.subjectClearListener),e.preRenderRemover=e.viewer.scene.preRender.addEventListener(()=>{if(!e.enabled)return;const h=Date.now(),d=s(e.viewer.camera);d!==e.lastCameraPoseSig&&(e.lastCameraPoseSig=d,e.lastCameraPoseChangeMs=h);const f=n.model.awarenessRefreshDecision({nowMs:h,lastRefreshMs:e.lastSubjectRefreshMs,lastPoseChangeMs:e.lastCameraPoseChangeMs,wasMoving:e.cameraMoving});e.cameraMoving=f.moving,a(),f.refresh&&(e.lastSubjectRefreshMs=h,e.subject&&["flights","military","ais-live-vessels"].includes(e.subject.layerId)?n.subject.refreshSelectedSubject():!e.passive&&e.autoFocusRetryPending?(e.autoFocusRetryPending=!1,n.focus.focusAttentionTarget()):n.rendering.scheduleDirectionOverlayUpdate())}),e.runtimeListenersAttached=!0)}function l(){var h;e.runtimeListenersAttached&&(window.removeEventListener("gev:awareness-subject-selected",e.subjectListener),window.removeEventListener("gev:entity-selected",e.contextListener),window.removeEventListener("gev:entity-selection-cleared",e.clearListener),window.removeEventListener("gev:awareness-subject-cleared",e.subjectClearListener)),(h=e.preRenderRemover)==null||h.call(e),e.preRenderRemover=null,e.lastCameraPoseSig="",e.lastCameraPoseChangeMs=0,e.cameraMoving=!1,r("military-awareness"),n.rendering.cancelDirectionOverlayUpdate(),e.runtimeListenersAttached=!1}return{cameraMotionSignature:s,syncAwarenessRenderHold:a,attachRuntimeListeners:c,detachRuntimeListeners:l,methods:{init(h){l(),e.viewer=h,e.subjectListener=d=>{e.enabled&&n.subject.selectSubject(d.detail)},e.contextListener=d=>{if(!e.enabled)return;const f=n.subject.subjectFromContext(d.detail);f&&(n.model.contextTargetFlyToAllowed(f.layerId)&&n.model.releaseAircraftTracking(),n.subject.selectSubject(f))},e.clearListener=d=>{if(!(!e.enabled||e.pendingSelectionKey)&&n.subject.awarenessClearMatchesSubject(e.subject,d.detail)){if(n.model.awarenessClearIsEviction(d.detail)){n.subject.markSubjectEvicted();return}n.subject.clearAwarenessSubject()}},e.subjectClearListener=d=>{var p;if(!e.enabled)return;const f=d.detail;if(!e.pendingSelectionKey&&n.subject.awarenessClearMatchesSubject(e.subject,f)&&String((p=e.subject)==null?void 0:p.id)===String(f==null?void 0:f.id)){if(n.model.awarenessClearIsEviction(f)){n.subject.markSubjectEvicted();return}e.autoFocusAttempted=!0,n.subject.clearAwarenessSubject()}}},enable(){return e.enabled=!0,c(),n.panel.startAwarenessPageRotation(),e.autoFocusAttempted=!1,e.autoFocusRetryPending=!1,n.panel.ensurePanel(),n.panel.hidePanel(),e.passive?!0:n.dependencies.activateOperationalContext()},disable(){e.enabled=!1,r("military-awareness"),l(),n.panel.stopAwarenessPageRotation(),e.cohortPages.clear();const h=++e.activationId;return e.autoFocusAttempted=!1,e.autoFocusRetryPending=!1,e.subject=null,e.results=null,e.lastSubjectRefreshMs=0,e.lastEvaluatedPosition=null,e.sourceRevision="",e.navigationHistory=[],e.navigationVisited.clear(),e.navigationIndex=-1,e.suppressedHistoryKey=null,e.pendingSelectionKey=null,n.rendering.clearVisual(),n.panel.hidePanel(),e.passive=!0,n.dependencies.releaseOwnedDependencies(h)},destroy(){var h,d,f;this.disable(),l(),(h=e.panel)==null||h.removeEventListener("click",e.panelClickListener),e.panelClickListener=null,e.panelOwned?(d=e.panel)==null||d.remove():e.panel&&e.panel.replaceChildren(),e.panel=null,e.panelOwned=!1,(f=e.directionRoot)==null||f.remove(),e.directionRoot=null,e.compassRing=null,e.compassLabels=[],e.compassHeading=null,e.directionMarkers=[],e.panelMarkup="",e.subjectListener=null,e.contextListener=null,e.clearListener=null,e.subjectClearListener=null,e.viewer=null,e.dataManager=null}}}}function F4({state:e,services:t,parts:n,source:i}){function o(c){if(!(!e.enabled||e.passive||c!==e.activationId)){if(e.subject){n.subject.refreshSelectedSubject(!0);return}e.autoFocusRetryPending&&(e.autoFocusRetryPending=!n.focus.focusAttentionTarget())}}async function r(c=e.activationId){var u,h;const l=[];for(const d of Uh){if(!e.enabled)return;if(!e.dataManager||(((h=(u=e.dataManager).isEffectivelyEnabled)==null?void 0:h.call(u,d))??e.dataManager.isEnabled(d)))continue;e.ownedDependencies.add(d);let p;try{p=Promise.resolve(e.dataManager.setEnabled(d,!0))}catch(g){p=Promise.reject(g)}wE.includes(d)?l.push(p):p.then(()=>o(c),()=>o(c))}await Promise.allSettled(l)}function s(c){const l=[...e.ownedDependencies];return e.ownedDependencies.clear(),!e.dataManager||!l.length?Promise.resolve():Promise.allSettled(l.map(u=>e.dataManager.setEnabled(u,!1))).then(()=>e.enabled&&e.activationId!==c?r(e.activationId):null)}function a(){const c=++e.activationId;e.autoFocusRetryPending=!1;const l=n.subject.currentTrackedFlightSubject();return l&&n.subject.selectSubject(l),r(c).then(()=>{if(!e.enabled||e.passive||c!==e.activationId)return;const u=n.subject.currentTrackedFlightSubject();if(u){n.subject.selectSubject(u);return}if(e.subject){n.subject.selectSubject(e.subject);return}e.autoFocusAttempted||(e.autoFocusRetryPending=!n.focus.focusAttentionTarget())}).catch(u=>console.warn("[Global Context] dependency enable failed",u))}return{refreshAfterDeferredDependency:o,enableDependencies:r,releaseOwnedDependencies:s,activateOperationalContext:a}}function S4({state:e,services:t,parts:n,source:i}){const o=t.flights,r=t.military,s=t.vessels;return{methods:{id:"military-awareness",name:"Global Context",icon:"◎",source:"Open-source proximity context",showInTogglePanel:!1,updateInterval:0,statsRefreshInterval:1e3,attachDataManager(c){e.dataManager=c},setParams(c={}){if(typeof c.passive!="boolean")return;const l=e.passive;e.passive=c.passive,e.enabled&&l&&!e.passive&&n.dependencies.activateOperationalContext()},getParams(){return{passive:e.passive}},getStats(){var c;return{count:e.results?1:0,lastUpdate:((c=e.results)==null?void 0:c.evaluatedAt)||null,stale:!1,error:null,status:e.enabled?"ready":"idle"}},getContextSnapshot(){return!e.enabled||!e.subject?null:e.results?n.model.buildAwarenessContextSnapshot(e.results,n.model.navigationState(),{subjectPresent:!e.subjectMissing}):n.model.buildAwarenessContextSnapshot({subject:{...e.subject},evaluatedAt:null,radiusM:Fn,cohorts:[]},n.model.navigationState(),{subjectPresent:!e.subjectMissing})},releaseCameraOwnership({preserveVesselSelection:c=!1,origin:l="programmatic"}={}){var h,d,f;++e.activationId,e.autoFocusAttempted=!0,e.autoFocusRetryPending=!1;const u=n.subject.subjectKey(e.subject)||"camera-release";e.pendingSelectionKey=u;try{(h=o.stopTracking)==null||h.call(o,{origin:l}),(d=r.stopTracking)==null||d.call(r,{origin:l}),c||(f=s.clearSelection)==null||f.call(s)}finally{e.pendingSelectionKey===u&&(e.pendingSelectionKey=null)}return!!e.subject},navigatePrevious(c={}){return n.history.navigateHistory(-1,c)},focusCurrent(c={}){return n.focus.focusCurrentSubject(c)},navigateNext(c={}){return n.history.navigateHistory(1,c)},focusTarget(c,l,u={}){return n.focus.requestFocus(c,l,!1,u)}}}}function N4({state:e,services:t,parts:n,source:i}){return{methods:{update(){return n.subject.refreshSelectedSubject(),Promise.resolve()}}}}function D4({services:e}){const t={};return t.DIRECTION_SCRATCH=Array.from({length:3},()=>new Cesium.Cartesian3),t.SUBJECT_CARTOGRAPHIC_SCRATCH=new Cesium.Cartographic,t.TARGET_CARTOGRAPHIC_SCRATCH=Array.from({length:3},()=>new Cesium.Cartographic),Object.assign(t,{viewer:null,dataManager:null,enabled:!1,subjectMissing:!1,passive:!0,ownedDependencies:new Set,subject:null,results:null,visual:null,panel:null,panelOwned:!1,subjectListener:null,contextListener:null,clearListener:null,subjectClearListener:null,runtimeListenersAttached:!1,preRenderRemover:null,panelClickListener:null,directionRoot:null,compassRing:null,compassLabels:[],compassHeading:null,directionMarkers:[],navigationHistory:[],navigationVisited:new Set,navigationIndex:-1,suppressedHistoryKey:null,pendingSelectionKey:null,lastSubjectRefreshMs:0,lastCameraPoseSig:"",lastCameraPoseChangeMs:0,cameraMoving:!1,lastEvaluatedPosition:null,sourceRevision:"",panelMarkup:"",directionFrame:null,lastDirectionUpdateMs:0,activationId:0,autoFocusAttempted:!1,autoFocusRetryPending:!1,pageTimer:null,cohortPages:new Map}),t}function O4({services:e,source:t}){var r;const n=D4({services:e}),i={},o={state:n,services:e,parts:i,source:t};return i.model=r4(o),i.subject=c4(o),i.panel=u4(o),i.queries=d4(o),i.navigation=h4(o),i.focus=f4(o),i.testing=m4(o),i.history=p4(o),i.rendering=P4(o),i.lifecycle=x4(o),i.dependencies=F4(o),i.controls=S4(o),i.ingestion=N4(o),Object.assign({},i.controls.methods,i.lifecycle.methods,(r=i.ingestion)==null?void 0:r.methods,{contextTargetFlyToAllowed:i.model.contextTargetFlyToAllowed,awarenessClearMatchesSubject:i.subject.awarenessClearMatchesSubject,awarenessRefreshIntervalMs:i.model.awarenessRefreshIntervalMs,awarenessRefreshDecision:i.model.awarenessRefreshDecision,awarenessClearIsEviction:i.model.awarenessClearIsEviction,awarenessRefreshRequired:i.model.awarenessRefreshRequired,summarizeInstallationViewport:i.queries.summarizeInstallationViewport,contactsWindowFromSnapshot:i.model.contactsWindowFromSnapshot,buildAwarenessContextSnapshot:i.model.buildAwarenessContextSnapshot,collectAircraftProximityWindow:i.queries.collectAircraftProximityWindow,_getAwarenessNavigationStateForTest:i.testing._getAwarenessNavigationStateForTest,canNavigateAwarenessNext:i.navigation.canNavigateAwarenessNext,historySubjectSnapshot:i.history.historySubjectSnapshot,findCompatibleHistoryIndex:i.history.findCompatibleHistoryIndex,awarenessPanelControlKey:i.panel.awarenessPanelControlKey,captureAwarenessPanelFocus:i.panel.captureAwarenessPanelFocus,restoreAwarenessPanelFocus:i.panel.restoreAwarenessPanelFocus,awarenessResultsAreLive:i.panel.awarenessResultsAreLive,awarenessNeedsContinuousRender:i.model.awarenessNeedsContinuousRender})}const _c="gev:navigation-authority-taken";function B4(e,{eventTarget:t=globalThis.window,cancelPendingSelection:n=!0}={}){return typeof(t==null?void 0:t.dispatchEvent)!="function"?!1:(t.dispatchEvent(new CustomEvent(_c,{detail:{reason:String(e||"layer-focus"),cancelPendingSelection:!!n}})),!0)}function TE(e,t){if(!(e!=null&&e.addEventListener)||!(e!=null&&e.removeEventListener)||typeof t!="function")return()=>{};e.addEventListener(_c,t);let n=!1;return()=>{n||(n=!0,e.removeEventListener(_c,t))}}function kE(e){return e==null?void 0:e({cancelPendingSelection:!0})}function zh({disposed:e=!1,cockpitActive:t=!1,noun:n="target",showToast:i,stamp:o,release:r,navigate:s}={}){if(e)return!1;if(t)return i==null||i(`Exit cockpit to fly to a ${n}`),!1;const a=o==null?void 0:o();return r==null||r(),s==null?void 0:s(a)}function AE({disposed:e=!1,cockpitActive:t=!1,noun:n="location",showToast:i,stamp:o}={}){return e?!1:t?(i==null||i(`Exit cockpit to fly to a ${n}`),!1):o==null?void 0:o()}function IE({generation:e,currentGeneration:t,cockpitActive:n=!1,disposed:i=!1,showToast:o,release:r}={}){return i||e!==t?!1:n?(o==null||o("Exit cockpit to fly to a location"),!1):(r==null||r(),!0)}const V4=Object.freeze(Object.defineProperty({__proto__:null,NAVIGATION_AUTHORITY_EVENT:_c,announceNavigationAuthority:B4,beginDeferredNavigation:AE,reassertNavigationHandoff:IE,registerNavigationAuthorityListener:TE,runExplicitNavigation:zh,stampInitialShareGesture:kE},Symbol.toStringTag,{value:"Module"}));function H4({flights:e,military:t,vessels:n,installations:i}){return O4({services:{flights:e,military:t,vessels:n,installations:i,navigation:V4,geometry:Gf,render:Pt}})}const jh=18,kn="firms";function xi(e){const t=Number.isFinite(e==null?void 0:e.lat)?e.lat.toFixed(4):"x",n=Number.isFinite(e==null?void 0:e.lon)?e.lon.toFixed(4):"x",i=Number.isFinite(e==null?void 0:e.acqMs)&&e.acqMs>0?String(e.acqMs):"0",o=qh(e==null?void 0:e.satellite)||String((e==null?void 0:e.sensor)||"").trim().toUpperCase()||"x";return`firms:${t}:${n}:${i}:${o}`}const Hb=Object.freeze({red:"224, 82, 82",orange:"240, 178, 62",yellow:"244, 227, 108"});function er(e){return Hb[e]||Hb.yellow}function qh(e){const t=String(e||"").trim().toUpperCase();return t==="N20"||t==="NOAA-20"?"N20":t==="N21"||t==="NOAA-21"?"N21":t==="N"||t==="NPP"||t==="SUOMI NPP"?"SNPP":t?t.slice(0,6):""}const $4=6e5,pr=[{id:"global",minHeight:9e6,mode:"cells",gridDegrees:2,maxCells:1800,labelDistance:12e6},{id:"regional",minHeight:3e6,mode:"cells",gridDegrees:1,maxCells:3600,labelDistance:85e5},{id:"local",minHeight:75e4,mode:"detections",maxDetections:2500,labelDistance:45e5},{id:"close",minHeight:0,mode:"detections",maxDetections:3e3,labelDistance:18e5}],$b=650,Gb=.1,bc=.3,RE=50,G4=jh,Ub=150,qa=16,U4=10,zb=12,ld=[{name:"red",color:Cesium.Color.RED},{name:"orange",color:Cesium.Color.ORANGE},{name:"yellow",color:Cesium.Color.YELLOW}];function z4({layerState:e,services:t,components:n,config:i,feed:o}){const{fireAnchorHeight:r}=t.anchors;function s(L){const F=O=>Number.isFinite(O)?O:null,P=O=>String(O??"").trim()||null;return{id:`FIRE-${String((L==null?void 0:L.index)??0).padStart(5,"0")}`,lat:F(L==null?void 0:L.lat),lon:F(L==null?void 0:L.lon),frp:F(L==null?void 0:L.frp),confidence:F(L==null?void 0:L.confidence),satellite:P(L==null?void 0:L.satellite)||P(L==null?void 0:L.sensor),acqTime:Number.isFinite(L==null?void 0:L.acqMs)&&L.acqMs>0?L.acqMs:null}}function a(L){const F=Cesium.Rectangle.computeWidth(L),P=Cesium.Rectangle.computeHeight(L);if(F>=Math.PI*1.85)return null;const O=F*bc,D=P*bc,$=Math.max(-Cesium.Math.PI_OVER_TWO,L.south-D),x=Math.min(Cesium.Math.PI_OVER_TWO,L.north+D);let N=L.west-O,G=L.east+O,W;return F+O*2>=Cesium.Math.TWO_PI?(N=-Math.PI,G=Math.PI,W=!1):(N=Cesium.Math.negativePiToPi(N),G=Cesium.Math.negativePiToPi(G),W=N>G),{west:Cesium.Math.toDegrees(N),south:Cesium.Math.toDegrees($),east:Cesium.Math.toDegrees(G),north:Cesium.Math.toDegrees(x),wraps:W}}function c(L,F,P){return FL.north?!1:L.wraps?P>=L.west||P<=L.east:P>=L.west&&P<=L.east}function l(L,F,P){if(L.latCell+FP.north)return!1;const O=L.lonCell,D=L.lonCell+F;return P.wraps?D>=P.west||O<=P.east:D>=P.west&&O<=P.east}function u(L){return L.intensity+L.count*.8+L.night*.6+L.maxFrp*.12}function h(L,F){return L>.72?Cesium.Color.RED.withAlpha(F):L>.42?Cesium.Color.ORANGE.withAlpha(F):Cesium.Color.YELLOW.withAlpha(F)}function d(L){const F=Math.min(1,Math.sqrt(Math.max(0,L.frp)/150)*.85+L.confidence*.15);return F>.72?ld[0]:F>.42?ld[1]:ld[2]}function f(L){return Math.max(8,Math.min(28,Math.round(8+Math.sqrt(Math.max(0,L))*2)))}function p(L){return Math.max(8,Math.min(28,Math.round(L/2)*2))}function g(L,F){const P=`${L.name}:${F}`,O=e.glowSpriteCache.get(P);if(O)return O;const D=F*2,$=document.createElement("canvas");$.width=D,$.height=D;const x=$.getContext("2d");if(!x)return"";const N=D/2,G=[Math.round(L.color.red*255),Math.round(L.color.green*255),Math.round(L.color.blue*255)].join(","),W=x.createRadialGradient(N,N,0,N,N,N);W.addColorStop(0,"rgba(255,255,235,0.95)"),W.addColorStop(.25,`rgba(${G},0.9)`),W.addColorStop(.55,`rgba(${G},0.35)`),W.addColorStop(1,`rgba(${G},0)`),x.fillStyle=W,x.fillRect(0,0,D,D);const V=$.toDataURL("image/png");return e.glowSpriteCache.set(P,V),V}function _(L){const F=r(L.lat,L.lon);return(!L.position||L.positionHeight!==F)&&(L.position=Cesium.Cartesian3.fromDegrees(L.lon,L.lat,F),L.positionHeight=F),L.position}function m(L){const F=_(L);return L.positionHeight>=U4?F:(L.cullPosition||(L.cullPosition=Cesium.Cartesian3.fromDegrees(L.lon,L.lat,zb)),L.cullPosition)}function b(L,F){return Cesium.Cartesian3.fromDegrees(L,F,zb)}function C(L,F,P=null){if(!L||typeof L.get!="function"||typeof(F==null?void 0:F.isPointVisible)!="function")return 0;const O=Number(L.length)||0;let D=0;for(let $=0;$0){const D=R(F-L.acqMs);D&&P.push(`${D} ago`)}const O=qh(L.satellite);return P.push(O?`${L.sensor||"VIIRS"} ${O}`:L.sensor||"sensor n/a"),{id:`selected-fire:${xi(L)}`,actionable:!0,position:_(L),cullPosition:m(L),gapPx:f(L.frp),accent:er(d(L).name),title:`FIRE · ${I(L.frp)} MW`,details:[P.join(" · "),T(L.lat,L.lon)+(L.night?" · NIGHT":"")],selected:!0,priority:Number.MAX_SAFE_INTEGER}}function M(L,F){const P=L.fire,O=[A(P.confidence)];if(P.acqMs>0){const $=R(F-P.acqMs);$&&O.push($)}const D=qh(P.satellite)||P.sensor;return D&&O.push(D),{id:`fire:${xi(P)}`,actionable:!0,position:L.position,cullPosition:L.cullPosition||L.position,gapPx:f(P.frp),accent:er(d(P).name),title:`▲ ${I(P.frp)} MW`,details:[O.join(" · ")],selected:!1,priority:Number(P.frp)||0}}function w(L,F){const P=L.cell,O=P.count===1?"FIRE":"FIRES",D=[`max ${I(P.maxFrp)} MW`];if(P.newestAcqMs>0){const $=R(F-P.newestAcqMs);$&&D.push(`new ${$}`)}return{id:`cell:${P.latCell??"x"}:${P.lonCell??"x"}`,position:L.position,cullPosition:L.cullPosition||L.position,gapPx:10,accent:L.accent||er("yellow"),title:`${P.count} ${O}`,details:[D.join(" · ")],selected:!1,priority:Number(P.maxFrp)||0}}function E(L,F){const P=(L==null?void 0:L.selected)===!0,O=Number(L==null?void 0:L.gapPx)||10,D=Math.max(12,O+8);return{...L,variant:P?"selected":"card",protected:P,collisionGroup:"ambient-card",cardStyle:"tactical",gapPx:D,leaderOffsetPx:Math.max(2,D-6),verticalOnly:!0,viewportMargin:4,maxDistance:P?Number.POSITIVE_INFINITY:F,distanceFadeStartRatio:.7,edgeFade:"keyhole",horizonCull:!0,terrainOcclusion:!1,interactive:(L==null?void 0:L.actionable)===!0}}function k(L){return L>.72?er("red"):L>.42?er("orange"):er("yellow")}function T(L,F){const P=`${Math.abs(L).toFixed(3)}°${L>=0?"N":"S"}`,O=`${Math.abs(F).toFixed(3)}°${F>=0?"E":"W"}`;return`${P} ${O}`}function I(L){return L>=10?L.toFixed(0):L.toFixed(1)}function R(L){if(!Number.isFinite(L)||L<0)return"";const F=L/36e5;return F<1?"<1h":F<48?`${Math.round(F)}h`:`${Math.round(F/24)}d`}function S(L){if(!Number.isFinite(L)||L<0)return"just now";const F=Math.floor(L/6e4);return F<1?"<1m ago":F<90?`${F}m ago`:`${Math.round(F/60)}h ago`}function A(L){return L>=.75?"high":L>=.45?"nominal":"low"}return{mapAnalystRecord:s,paddedDegreeBounds:a,boundsContainPoint:c,cellIntersectsBounds:l,heatScore:u,heatColor:h,detectionColorStop:d,frpPixelSize:f,sizeBucket:p,glowSprite:g,firePosition:_,fireCullPosition:m,cellCullPosition:b,applyHorizonCull:C,screenSeparated:y,buildSelectedFireCard:v,buildFireCard:M,buildCellCard:w,applyFirmsOverlayPolicy:E,cellAccent:k,formatLatLon:T,formatFrp:I,formatAge:R,formatAgoMinutes:S,confidenceBucket:A}}function j4(e){const t=[];if(!Array.isArray(e))return t;const n=new Map;for(const i of e){const o=Number(i==null?void 0:i.lat),r=Number(i==null?void 0:i.lon);!Number.isFinite(o)||!Number.isFinite(r)||t.push({index:t.length,lat:o,lon:r,frp:qb(i.frp),confidence:q4(i.confidence),brightness:qb(i.brightness),night:i.daynight==="N",acqMs:W4(i.acqDate,i.acqTime,n),sensor:K4(i.instrument),satellite:typeof i.satellite=="string"?i.satellite:"",contextEntity:null,position:null})}return t}function q4(e){if(typeof e=="string"){const n=e.trim().toLowerCase();if(n==="low"||n==="l")return .3;if(n==="nominal"||n==="n")return .6;if(n==="high"||n==="h")return .9;const i=Number(n);return Number.isFinite(i)?jb(i/100):0}const t=Number(e);return Number.isFinite(t)?jb(t/100):0}function W4(e,t,n=new Map){if(typeof e!="string"||e.length<10)return 0;const i=`${e}:${t??""}`,o=n.get(i);if(o!==void 0)return o;const r=Number(e.slice(0,4)),s=Number(e.slice(5,7)),a=Number(e.slice(8,10)),c=String(t??"0000").padStart(4,"0"),l=Number(c.slice(0,2)),u=Number(c.slice(2,4)),d=Number.isFinite(r)&&Number.isFinite(s)&&Number.isFinite(a)&&Number.isFinite(l)&&Number.isFinite(u)?Date.UTC(r,s-1,a,l,u):0;return n.set(i,d),d}function K4(e){const t=String(e||"").toUpperCase();return t.includes("VIIRS")?"VIIRS":t.includes("MODIS")?"MODIS":t?t.slice(0,12):""}function jb(e){return Math.max(0,Math.min(1,e))}function qb(e){const t=Number(e);return Number.isFinite(t)?t:0}function Y4({layerState:e,services:t,components:n,config:i,feed:o}){const{clearSelectedEntityContextForLayer:r}=t.context,{id:s}=i;async function a(){var h;if(!e._dataSource||!e._enabled)return;(h=e.request)==null||h.abort();const u=new AbortController;e.request=u,e._loading=!0;try{const d=await o.getSnapshot({signal:u.signal});if(u.signal.aborted||e.request!==u||!e._enabled)return;if(d.keyRequired){e._keyRequired=!0,e._error=null,e._stale=!1;return}e._keyRequired=!1,e._error=null,e._stale=!!(d!=null&&d.stale);const f=e._selectedFire;e._selectedFire=null,e._fires=j4(d==null?void 0:d.fires),e._cellCacheByGrid.clear(),e._firesByFrp=[...e._fires].sort((g,_)=>_.frp-g.frp),e._count=e._fires.length,e._lastUpdate=Number.isFinite(d==null?void 0:d.fetchedAt)?d.fetchedAt:Date.now();const p=c(f);!p&&f&&r(s,{evicted:!0}),n.rendering.renderCurrentLod(!0),p&&n.selection.selectFire(p,!1)}catch(d){if(u.signal.aborted||e.request!==u||!e._enabled)return;console.warn(`[Data:${s}] FIRMS live load failed:`,d),e._error="live feed unavailable"}finally{e.request===u&&(e.request=null,e._loading=!1)}}function c(u){if(!u)return null;const h=xi(u);return e._fires.find(d=>xi(d)===h)||null}return{loadHeatmap:a,findMatchingFire:c,methods:{async update(){e._destroyed||!e._enabled||e._loading||await a()}}}}function X4({layerState:e,services:t,components:n,config:i,feed:o}){const{warmFireAnchorFloors:r}=t.anchors,{registerSpriteCollection:s,restoreSpriteOrder:a}=t.sprites,{overlayHost:c}=i;function l(m=!1){if(!e._dataSource||!e._fires.length||!e._viewer)return!1;const b=n.viewport.selectLodIndex(n.viewport.cameraHeight()),C=pr[b],y=n.viewport.computeViewRect();if(!m&&b===e._currentLodIndex&&!n.viewport.viewChangedEnough(y))return!1;e._currentLodIndex=b,e._currentLodId=C.id,e._lastViewRect=y?Cesium.Rectangle.clone(y):null;const v=y?n.model.paddedDegreeBounds(y):null;return C.mode==="detections"?d(C,v):h(u(C,v),C,v),!0}function u(m,b){const C=m.gridDegrees;let y=e._cellCacheByGrid.get(C);if(!y){const M=new Map;for(const w of e._fires){const E=Math.floor(w.lat/C)*C,k=Math.floor(w.lon/C)*C,T=`${E.toFixed(3)}:${k.toFixed(3)}`,I=Math.max(1,w.frp*.18+w.confidence*4+w.brightness*.01),R=M.get(T)||{latCell:E,lonCell:k,count:0,intensity:0,maxFrp:0,night:0,newestAcqMs:0};R.count+=1,R.intensity+=I,R.maxFrp=Math.max(R.maxFrp,w.frp),R.newestAcqMs=Math.max(R.newestAcqMs,w.acqMs),w.night&&(R.night+=1),M.set(T,R)}y=[...M.values()].sort((w,E)=>n.model.heatScore(E)-n.model.heatScore(w)),e._cellCacheByGrid.set(C,y)}if(!b)return y.slice(0,m.maxCells);const v=[];for(const M of y)if(n.model.cellIntersectsBounds(M,C,b)&&(v.push(M),v.length>=m.maxCells))break;return v}function h(m,b,C){f(),e._dataSource.entities.removeAll(),e._billboards&&e._billboards.removeAll(),e._pickIndexById.clear(),e._cullPositions.length=0,e._cellCount=m.length;const y=Math.max(1,...m.map(n.model.heatScore));e._labelCandidates=[],e._labelLodDistance=b.labelDistance;for(const v of m){const M=n.model.heatScore(v),w=Math.min(1,Math.sqrt(M/y)),E=.16+w*.5,k=n.model.heatColor(w,E),T=v.lonCell+b.gridDegrees/2,I=v.latCell+b.gridDegrees/2,R=Cesium.Cartesian3.fromDegrees(T,I,0);e._dataSource.entities.add({rectangle:{coordinates:Cesium.Rectangle.fromDegrees(v.lonCell,v.latCell,v.lonCell+b.gridDegrees,v.latCell+b.gridDegrees),material:new Cesium.ColorMaterialProperty(k),heightReference:Cesium.HeightReference.CLAMP_TO_GROUND},position:R,properties:{count:v.count,intensity:M,maxFrp:v.maxFrp,night:v.night}}),e._labelCandidates.push({position:R,cullPosition:n.model.cellCullPosition(T,I),fire:null,cell:v,accent:n.model.cellAccent(w)})}n.cards.rebuildAmbientLabels(),n.selection.refreshContextRegistrations(n.selection.topFiresWithinBounds(C))}function d(m,b){if(f(),e._dataSource.entities.removeAll(),!e._billboards)return;e._billboards.removeAll(),e._pickIndexById.clear(),e._cullPositions.length=0;let C;if(b){C=[];for(const y of e._firesByFrp)if(n.model.boundsContainPoint(b,y.lat,y.lon)&&(C.push(y),C.length>=m.maxDetections))break}else C=e._firesByFrp.slice(0,m.maxDetections);e._cellCount=C.length,e._labelCandidates=[],e._labelLodDistance=m.labelDistance;for(const y of C){const v=n.model.frpPixelSize(y.frp),M=n.model.firePosition(y),w=n.model.fireCullPosition(y),E=`firms-${y.index}`;e._pickIndexById.set(E,y),e._cullPositions.push(w),e._billboards.add({id:E,position:M,image:n.model.glowSprite(n.model.detectionColorStop(y),n.model.sizeBucket(v)),verticalOrigin:Cesium.VerticalOrigin.CENTER,horizontalOrigin:Cesium.HorizontalOrigin.CENTER,disableDepthTestDistance:Number.POSITIVE_INFINITY}),e._labelCandidates.push({position:M,cullPosition:w,fire:y,cell:null})}_(),n.cards.rebuildAmbientLabels(),n.selection.refreshContextRegistrations(C.slice(0,RE)),m.id==="close"&&r(C).then(y=>{if(!y||!e._enabled||!e._viewer)return;const v=pr[e._currentLodIndex];!v||v.mode!=="detections"||l(!0)})}function f(){!e._viewer||e._billboards||(e._billboards=new Cesium.BillboardCollection({scene:e._viewer.scene,blendOption:Cesium.BlendOption.TRANSLUCENT}),e._billboards.show=e._enabled,e._viewer.scene.primitives.add(e._billboards),s("firms",e._billboards),a(e._viewer),c.setVisible(kn,e._enabled))}function p(m){var C,y;const b=(m==null?void 0:m.scene)||((C=e._viewer)==null?void 0:C.scene);if(b&&!((y=b.isDestroyed)!=null&&y.call(b)))try{e._billboards&&b.primitives.remove(e._billboards)}catch{}e._billboards=null,c.clearSource(kn),c.setVisible(kn,!1)}function g(){var b,C,y,v;const m=(C=(b=e._viewer)==null?void 0:b.camera)!=null&&C.positionWC?e._viewer.camera:(v=(y=e._viewer)==null?void 0:y.scene)==null?void 0:v.camera;return m!=null&&m.positionWC?Vo(m):null}function _(){!e._billboards||!e._billboards.length||n.model.applyHorizonCull(e._billboards,g(),e._cullPositions)}return{renderCurrentLod:l,aggregateFires:u,renderCells:h,renderDetections:d,ensureDetectionCollections:f,removeDetectionCollections:p,fireHorizonOccluder:g,refreshHorizonCulling:_}}function Q4({layerState:e,services:t,components:n,config:i,feed:o}){const{overlayHost:r}=i;function s(){if(!e._viewer)return;const a=e._viewer.scene,c=Date.now(),l=[],u=[],h=n.rendering.fireHorizonOccluder(),d=_=>h?h.isPointVisible(_)!==!0:!1;if(e._fireByCardId.clear(),e._selectedFire){const _=n.model.buildSelectedFireCard(e._selectedFire,c);e._fireByCardId.set(_.id,e._selectedFire),l.push(_);const m=Cesium.SceneTransforms.worldToWindowCoordinates(a,n.model.firePosition(e._selectedFire),e.scratchWindowCoord);m&&!d(n.model.fireCullPosition(e._selectedFire))&&u.push({x:m.x,y:m.y})}const f=a.canvas.clientWidth,p=a.canvas.clientHeight;let g=0;for(const _ of e._labelCandidates){if(g>=G4)break;if(_.fire&&_.fire===e._selectedFire||d(_.cullPosition||_.position))continue;const m=Cesium.SceneTransforms.worldToWindowCoordinates(a,_.position,e.scratchWindowCoord);if(!m||m.x<-qa||m.x>f+qa||m.y<-qa||m.y>p+qa||!n.model.screenSeparated(u,m))continue;u.push({x:m.x,y:m.y}),g+=1;const b=_.fire?n.model.buildFireCard(_,c):n.model.buildCellCard(_,c);_.fire&&e._fireByCardId.set(b.id,_.fire),l.push(b)}r.setEntries(kn,l.map(_=>{const m=n.model.applyFirmsOverlayPolicy(_,e._labelLodDistance);return m.interactive?{...m,accessibilityLabel:`Focus fire detection ${m.title}, ${m.details.join(", ")}`,activate:()=>{const b=e._fireByCardId.get(m.id);return b?(n.selection.selectAndFocusFire(b),!0):!1}}:m}),{cohortLimit:jh,collisionCapacity:jh,moving:!1})}return{rebuildAmbientLabels:s}}function Z4({layerState:e,services:t,components:n,config:i,feed:o}){const{resolvePickId:r,isOwnedByOtherLayer:s}=t.picking,{requestWorldFocus:a}=t.focus,{selectEntityContext:c,clearSelectedEntityContextForLayer:l,getContextStore:u,registerEntityContext:h}=t.context,{id:d,name:f,overlayHost:p,screenSpaceEventHandlerFactory:g}=i;function _(){e._clickHandler||!e._viewer||(e._clickHandler=g(e._viewer),e._clickHandler.setInputAction(T=>{var A,L,F;if(!Bt())return;const I=e._viewer.scene.pick(T.position),R=C(I);if(R){b(R);return}if(I){const P=r(I);if(P&&s(d,P))return}const S=(F=p.hitTest)==null?void 0:F.call(p,(A=T.position)==null?void 0:A.x,(L=T.position)==null?void 0:L.y,{sourceId:kn});if(S){const P=e._fireByCardId.get(S.entryId);P&&b(P);return}v()},Cesium.ScreenSpaceEventType.LEFT_CLICK))}function m(){e._clickHandler&&(e._clickHandler.destroy(),e._clickHandler=null)}function b(T){y(T),a({kind:"fire",id:xi(T),label:"FIRE",position:n.model.firePosition(T)})}function C(T){var R;if(!T)return null;const I=(R=T.primitive)==null?void 0:R.id;return typeof I=="string"&&e._pickIndexById.has(I)?e._pickIndexById.get(I):typeof T.id=="string"&&e._pickIndexById.has(T.id)?e._pickIndexById.get(T.id):null}function y(T,I=!0){e._selectedFire=T;try{w(T),e._contextIds.add(xi(T)),I&&c(T.contextEntity)}catch{}n.cards.rebuildAmbientLabels()}function v(){e._selectedFire&&(e._selectedFire=null,l(d),n.cards.rebuildAmbientLabels())}function M(T){let I=null;try{I=u()}catch{return}const R=new Set;for(const S of T)R.add(w(S));e._selectedFire&&R.add(w(e._selectedFire));for(const S of e._contextIds)R.has(S)||I.entities.delete(S);e._contextIds=R}function w(T){const I=xi(T);return T.contextEntity||(T.contextEntity={show:!0}),T.contextEntity.__localBaseCartesian=n.model.firePosition(T),h(T.contextEntity,{id:I,layerId:d,layerName:f,source:"NASA FIRMS",dataSource:e._dataSource,label:`Fire · FRP ${n.model.formatFrp(T.frp)} MW`,latitude:T.lat,longitude:T.lon,properties:{frp:T.frp,confidence:n.model.confidenceBucket(T.confidence),age:T.acqMs>0?n.model.formatAge(Date.now()-T.acqMs):"unknown",sensor:T.sensor||"unknown"}}),I}function E(){if(e._contextIds.size){try{const T=u();for(const I of e._contextIds)T.entities.delete(I)}catch{}e._contextIds=new Set}}function k(T,I=RE){if(!T)return e._firesByFrp.slice(0,I);const R=[];for(const S of e._firesByFrp)if(n.model.boundsContainPoint(T,S.lat,S.lon)&&(R.push(S),R.length>=I))break;return R}return{installClickHandler:_,removeClickHandler:m,selectAndFocusFire:b,pickedFire:C,selectFire:y,clearFireSelection:v,refreshContextRegistrations:M,registerFireContext:w,clearContextRegistrations:E,topFiresWithinBounds:k}}function J4({layerState:e,services:t,components:n,config:i,feed:o}){const{governorRequestRender:r}=t.render;function s(){e._moveEndRemover||!e._viewer||(e._moveEndRemover=e._viewer.camera.moveEnd.addEventListener(()=>{e._enabled&&(n.rendering.refreshHorizonCulling(),!e._loading&&n.cards.rebuildAmbientLabels())}))}function a(){e._moveEndRemover&&(e._moveEndRemover(),e._moveEndRemover=null)}function c(){var g,_,m;return((m=(_=(g=e._viewer)==null?void 0:g.camera)==null?void 0:_.positionCartographic)==null?void 0:m.height)??Number.POSITIVE_INFINITY}function l(g){const _=pr.findIndex(m=>g>=m.minHeight);return _===-1?pr.length-1:_}function u(g){const _=l(g);if(e._currentLodIndex<0||_===e._currentLodIndex)return _;let m=e._currentLodIndex;for(;m>_&&g>=pr[m-1].minHeight*(1+Gb);)m-=1;for(;m<_&&g<=pr[m].minHeight*(1-Gb);)m+=1;return m}function h(){var g,_,m,b,C;try{return((C=(g=e._viewer)==null?void 0:g.camera)==null?void 0:C.computeViewRectangle((b=(m=(_=e._viewer)==null?void 0:_.scene)==null?void 0:m.globe)==null?void 0:b.ellipsoid,e.scratchViewRect))||null}catch{return null}}function d(g){if(!g)return!1;if(!e._lastViewRect)return!0;const _=Cesium.Rectangle.computeWidth(e._lastViewRect),m=Cesium.Rectangle.computeHeight(e._lastViewRect),b=Cesium.Rectangle.computeWidth(g),C=Cesium.Rectangle.computeHeight(g);if(b>_*1.3||b<_*.75||C>m*1.3||CMath.PI&&(w=Cesium.Math.TWO_PI-w),M>m*bc*.6||w>_*bc*.6}function f(){e._preRenderRemover||!e._viewer||(e._moveEndSettleRemover||(e._moveEndSettleRemover=e._viewer.camera.moveEnd.addEventListener(()=>{e._enabled&&setTimeout(()=>r("firms-lod-settle"),$b+40)})),e._preRenderRemover=e._viewer.scene.preRender.addEventListener(()=>{if(!e._enabled)return;const g=performance.now();if(g-e._lastLodCheck<$b)return;e._lastLodCheck=g;const _=e._viewer.camera;if(e._camSnapValid&&Cesium.Cartesian3.equalsEpsilon(_.positionWC,e._camPos,0,.5)&&Cesium.Cartesian3.equalsEpsilon(_.directionWC,e._camDir,0,1e-7))return;Cesium.Cartesian3.clone(_.positionWC,e._camPos),Cesium.Cartesian3.clone(_.directionWC,e._camDir),e._camSnapValid=!0,(e._fires.length&&!e._loading?n.rendering.renderCurrentLod(!1):!1)||n.rendering.refreshHorizonCulling()}))}function p(){e._preRenderRemover&&(e._preRenderRemover(),e._preRenderRemover=null),e._moveEndSettleRemover&&(e._moveEndSettleRemover(),e._moveEndSettleRemover=null)}return{installMoveEndWatcher:s,removeMoveEndWatcher:a,cameraHeight:c,rawLodIndex:l,selectLodIndex:u,computeViewRect:h,viewChangedEnough:d,installLodWatcher:f,removeLodWatcher:p}}function eG({layerState:e,services:t,components:n,config:i,feed:o}){const{registerPickOwner:r,unregisterPickOwner:s}=t.picking,{restoreSpriteOrderOnEnable:a}=t.sprites,{clearSelectedEntityContextForLayer:c}=t.context,{id:l,overlayHost:u}=i;return{methods:{init(d){e._destroyed||(e._viewer=d,e._dataSource=new Cesium.CustomDataSource(l),e._dataSource.show=!1,d.dataSources.add(e._dataSource))},async enable(d){e._destroyed||(e._enabled=!0,e._viewer=d,e._dataSource||this.init(d),e._dataSource&&(e._dataSource.show=!0),e._billboards&&(n.rendering.refreshHorizonCulling(),e._billboards.show=!0),u.setVisible(kn,!0),n.viewport.installLodWatcher(),n.viewport.installMoveEndWatcher(),n.selection.installClickHandler(),r(l,f=>e._pickIndexById.has(f)),!e._fires.length&&!e._loading&&await n.ingestion.loadHeatmap(),e._enabled&&!e._destroyed&&e._viewer===d&&a("firms",d))},disable(){var d;(d=e.request)==null||d.abort(),e.request=null,e._loading=!1,e._enabled=!1,n.selection.clearFireSelection(),e._dataSource&&(e._dataSource.show=!1),e._billboards&&(e._billboards.show=!1),u.clearSource(kn),u.setVisible(kn,!1),c(l),n.selection.removeClickHandler(),n.viewport.removeMoveEndWatcher(),s(l),n.viewport.removeLodWatcher()},destroy(d=e._viewer){var f;(f=e.request)==null||f.abort(),e.request=null,e._loading=!1,!e._destroyed&&(e._destroyed=!0,e._enabled=!1,n.viewport.removeLodWatcher(),n.viewport.removeMoveEndWatcher(),n.selection.removeClickHandler(),s(l),e._dataSource&&d&&d.dataSources.remove(e._dataSource,!0),e._dataSource=null,n.rendering.removeDetectionCollections(d),n.selection.clearContextRegistrations(),c(l),e._fires=[],e._firesByFrp=[],e._cellCacheByGrid.clear(),e._count=0,e._cellCount=0,e._lastUpdate=null,e._keyRequired=!1,e._stale=!1,e._error=null,e._currentLodId=null,u.clearSource(kn),u.setVisible(kn,!1),e._currentLodIndex=-1,e._lastViewRect=null,e._selectedFire=null,e._labelCandidates=[],e._labelLodDistance=0,e._pickIndexById.clear(),e._fireByCardId.clear(),e._cullPositions.length=0,e._camSnapValid=!1)}}}}function tG({layerState:e,services:t,components:n,config:i,feed:o}){const{id:r,name:s,icon:a,source:c}=i;return{methods:{getSelectedInfo(){const u=e._selectedFire;return u?{id:xi(u),label:`Fire · FRP ${n.model.formatFrp(u.frp)} MW`,latitude:u.lat,longitude:u.lon,frp:u.frp,confidencePct:Number.isFinite(u.confidence)?u.confidence*100:null,observedAt:Number.isFinite(u.acqMs)&&u.acqMs>0?u.acqMs:null,source:u.sensor||u.satellite||null}:null},id:r,name:s,icon:a,source:c,requiresKeyId:"firms",updateInterval:$4,getStats(){const u=Date.now(),h=e._lastUpdate?`STALE · cached ${n.model.formatAge(u-e._lastUpdate)||"<1h"}`:"STALE";let d="";return e._loading?d=e._fires.length?"refreshing...":"loading...":e._keyRequired?d="KEY REQUIRED":e._stale?d=h:e._error?d=e._error:e._lastUpdate&&(d=`LIVE · updated ${n.model.formatAgoMinutes(u-e._lastUpdate)}`),{count:e._count,cells:e._cellCount,lastUpdate:e._lastUpdate,loading:e._loading,stale:e._stale,keyRequired:e._keyRequired,error:e._keyRequired?"KEY REQUIRED":e._stale?h:e._error,loadingLabel:d}},getStrongestFire(){const u=e._firesByFrp.length?e._firesByFrp[0]:null;return u?{latitude:u.lat,longitude:u.lon,frp:u.frp,label:`Fire · FRP ${n.model.formatFrp(u.frp)} MW`}:null},getDetectableObjects(u={}){if(!e._enabled||!e._firesByFrp.length)return[];const h=Number.isFinite(u.maxCount)?Math.max(1,Math.floor(u.maxCount)):250,d=[];for(const f of e._firesByFrp)if(d.push({position:n.model.firePosition(f),id:`FIRE-${String(f.index).padStart(5,"0")}`,type:"FIRE"}),d.length>=h)break;return d},getAnalystRecords(u=2e3){if(!e._enabled||!e._firesByFrp.length)return[];const h=Number.isFinite(u)?Math.max(1,Math.floor(u)):2e3,d=[];for(const f of e._firesByFrp)if(d.push(n.model.mapAnalystRecord(f)),d.length>=h)break;return d},_bindInteractionForTest(u,h=[]){return e._viewer=u,e._enabled=!0,e._fires=h,e._firesByFrp=[...h],e._pickIndexById.clear(),e._labelLodDistance=1e7,e._labelCandidates=h.map(d=>(e._pickIndexById.set(`firms-${d.index}`,d),{fire:d,position:n.model.firePosition(d)})),n.cards.rebuildAmbientLabels(),n.selection.installClickHandler(),e._clickHandler}}}}function nG({services:e,config:t}){const n={};return n.glowSpriteCache=new Map,n.scratchViewRect=new Cesium.Rectangle,n.scratchCenterA=new Cesium.Cartographic,n.scratchCenterB=new Cesium.Cartographic,n.scratchWindowCoord=new Cesium.Cartesian2,n._viewer=null,n._dataSource=null,n._billboards=null,n._enabled=!1,n._destroyed=!1,n._loading=!1,n._keyRequired=!1,n._stale=!1,n._error=null,n._fires=[],n._firesByFrp=[],n._count=0,n._cellCount=0,n._lastUpdate=null,n._currentLodId=null,n._currentLodIndex=-1,n._lastViewRect=null,n._preRenderRemover=null,n._moveEndSettleRemover=null,n._lastLodCheck=0,n._contextIds=new Set,n._clickHandler=null,n._moveEndRemover=null,n._selectedFire=null,n._labelCandidates=[],n._labelLodDistance=0,n._pickIndexById=new Map,n._fireByCardId=new Map,n._cullPositions=[],n._cellCacheByGrid=new Map,n._camSnapValid=!1,n._camPos=new Cesium.Cartesian3,n._camDir=new Cesium.Cartesian3,n.request=null,n}function iG({fetchImpl:e=(...t)=>globalThis.fetch(...t)}={}){return{async getSnapshot({signal:t}={}){t==null||t.throwIfAborted();const n=await e("/api/firms",{signal:t,cache:"no-store"});let i;try{i=await n.json()}catch{}if(t==null||t.throwIfAborted(),!n.ok){if(n.status===503&&(i==null?void 0:i.error)==="no_key")return{keyRequired:!0};throw new Error(`FIRMS HTTP ${n.status}`)}if(!Array.isArray(i==null?void 0:i.fires))throw new Error("Malformed fire snapshot");return i}}}function oG({services:e,feed:t,...n}){if(typeof(t==null?void 0:t.getSnapshot)!="function")throw new TypeError("Fires require a snapshot source");const i=nG({services:e,config:n}),o={},r={layerState:i,services:e,config:n,components:o,feed:t};return o.model=z4(r),o.ingestion=Y4(r),o.rendering=X4(r),o.cards=Q4(r),o.selection=Z4(r),o.viewport=J4(r),o.lifecycle=eG(r),o.queries=tG(r),Object.assign({},o.queries.methods,o.lifecycle.methods,o.ingestion.methods)}const rG={render:Pt,sprites:Ki,context:Go,picking:rn,overlays:ui,focus:mM};function sG({surface:e,...t}){return oG({...t,icon:t.icon??"▲",source:t.source??"NASA FIRMS",feed:t.feed,services:{...rG,anchors:e.anchors},overlayHost:t.overlayHost??{setEntries:Ca,setVisible:va,clearSource:ya,hitTest:Rv},screenSpaceEventHandlerFactory:t.screenSpaceEventHandlerFactory??(n=>new Cesium.ScreenSpaceEventHandler(n.scene.canvas))})}function aG(e){var i;if(!Array.isArray(e==null?void 0:e.features))return null;const t=[],n=new Set;for(const[o,r]of e.features.entries()){const s=(i=r==null?void 0:r.geometry)==null?void 0:i.coordinates,a=r==null?void 0:r.properties;if(!Array.isArray(s)||s.length<2||!a||typeof a!="object"||Array.isArray(a)||r.geometry.type!=null&&r.geometry.type!=="Point")return null;const[c,l,u]=s,h=a.mag;if(!Number.isFinite(c)||Math.abs(c)>180||!Number.isFinite(l)||Math.abs(l)>90||u!=null&&!Number.isFinite(u)||h!=null&&(!Number.isFinite(h)||h>10))return null;if(h==null||h<2.5)continue;const d=r.id==null||r.id===""?`event-${o+1}`:String(r.id);if(n.has(d))return null;n.add(d),t.push({stableId:d,usgsId:r.id??null,lon:c,lat:l,depthKm:u??null,mag:h,place:typeof a.place=="string"?a.place:null,time:Number.isFinite(a.time)?a.time:null})}return t}const Qi="earthquakes",Wh=96,lG=48;function cG(e){return e<70?Cesium.Color.RED:e<300?Cesium.Color.ORANGE:Cesium.Color.YELLOW}function uG({id:e,position:t,magnitude:n,accent:i}){const o=Number(n);return{id:String(e),position:t,variant:"label",title:`M${o.toFixed(1)}`,accent:i,priority:Math.round(o*1e3),collisionGroup:"ambient-label",paintLane:"ambient-label",interactive:!1,edgeFade:"keyhole",horizonCull:!0,terrainOcclusion:!1,gapPx:15,verticalOnly:!0,placement:"above"}}function dG(e,t=Wh){const n=Math.max(0,Math.min(Wh,Math.floor(Number(t)||0)));return!Array.isArray(e)||n===0?[]:e.slice().sort((i,o)=>o.priority-i.priority||String(i.id).localeCompare(String(o.id))).slice(0,n)}function hG(e,t=0){const n=o=>Number.isFinite(o)?o:null,i=o=>String(o??"").trim()||null;return{id:i(e==null?void 0:e.id)||`QUAKE-${String(t).padStart(4,"0")}`,magnitude:n(e==null?void 0:e.mag),depthKm:n(e==null?void 0:e.depth),lat:n(e==null?void 0:e.lat),lon:n(e==null?void 0:e.lon),timeMs:n(e==null?void 0:e.time),place:i(e==null?void 0:e.place)}}const fG="https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson";function mG({fetchImpl:e=(...t)=>globalThis.fetch(...t)}={}){return{async getSnapshot({signal:t}={}){t==null||t.throwIfAborted();const n=await e(fG,{signal:t});if(!n.ok)throw new Error(`USGS HTTP ${n.status}`);const i=await n.json();t==null||t.throwIfAborted();const o=aG(i);if(!o)throw new Error("Malformed USGS response");return o}}}function pG({source:e,overlayHost:t}={}){if(typeof(e==null?void 0:e.getSnapshot)!="function")throw new TypeError("Earthquakes require a snapshot source");if(!t)throw new TypeError("Earthquakes require an overlay host");let n=null,i=null,o=null,r=0,s=null,a=null,c=!1;return{id:"earthquakes",name:"Earthquakes (24h)",icon:"🌋",source:"USGS",updateInterval:6e4,init(u){if(n)throw new Error("Earthquake layer is already initialized");n=u,o=new Cesium.CustomDataSource("earthquakes"),o.show=!1,u.dataSources.add(o),r=0,s=null,a=null,c=!1,t.setVisible(Qi,!1),console.log("[Data:Earthquakes] Initialized")},enable(u){c=!0,o&&(o.show=!0),t.setVisible(Qi,!0)},disable(u){i==null||i.abort(),i=null,c=!1,o&&(o.show=!1),t.clearSource(Qi),t.setVisible(Qi,!1)},async update(u){if(!c||!o)return!1;i==null||i.abort();const h=new AbortController;i=h;try{const d=await e.getSnapshot({signal:h.signal});if(h.signal.aborted||i!==h||!c)return!1;const f=[];let p=0;const g=[];for(const{stableId:_,usgsId:m,lon:b,lat:C,depthKm:y,mag:v,place:M,time:w}of d){p++;const E=Math.pow(2,v)*1e3,k=cG(y||0),T=v>=5,I=T?.4:.3,R=T?1:.8,S=Cesium.Cartesian3.fromDegrees(b,C);f.push(new Cesium.Entity({id:`earthquake:${_}`,position:S,ellipse:{semiMajorAxis:E,semiMinorAxis:E,material:new Cesium.ColorMaterialProperty(k.withAlpha(I)),outline:!0,outlineColor:k.withAlpha(R),outlineWidth:T?3:2,heightReference:Cesium.HeightReference.CLAMP_TO_GROUND},properties:{usgsId:m,mag:v,place:M,time:w,depth:y}})),g.push(uG({id:String(_),position:S,magnitude:v,accent:k.toCssColorString()}))}o.entities.removeAll();for(const _ of f)o.entities.add(_);return c&&t.setEntries(Qi,dG(g),{cohortLimit:Wh,collisionCapacity:lG,moving:!1}),r=p,s=Date.now(),a=null,console.log(`[Data:Earthquakes] Updated: ${r} events (M2.5+)`),!0}catch(d){return h.signal.aborted||i!==h||!c||(console.warn("[Data:Earthquakes] Fetch error:",d),a=(d==null?void 0:d.message)||"Earthquake source unavailable"),!1}finally{i===h&&(i=null)}},destroy(u=n){i==null||i.abort(),i=null,n=null,c=!1,t.clearSource(Qi),t.setVisible(Qi,!1),o&&(u.dataSources.remove(o,!0),o=null),r=0,s=null,a=null},getAnalystRecords(u=2e3){var g,_,m,b,C;if(!o||!o.show)return[];const h=o.entities.values;if(!h.length)return[];const d=Number.isFinite(u)?Math.max(1,Math.floor(u)):2e3,f=Cesium.JulianDate.now(),p=[];for(const y of h){if(p.length>=d)break;const v=y.position?y.position.getValue(f):null,M=v?Cesium.Cartographic.fromCartesian(v):null,w=y.properties;p.push(hG({id:((g=w==null?void 0:w.usgsId)==null?void 0:g.getValue(f))??null,mag:(_=w==null?void 0:w.mag)==null?void 0:_.getValue(f),place:(m=w==null?void 0:w.place)==null?void 0:m.getValue(f),time:(b=w==null?void 0:w.time)==null?void 0:b.getValue(f),depth:(C=w==null?void 0:w.depth)==null?void 0:C.getValue(f),lat:M?Cesium.Math.toDegrees(M.latitude):null,lon:M?Cesium.Math.toDegrees(M.longitude):null},p.length))}return p},getStats(){return{count:r,lastUpdate:s,error:a}}}}const LE=Object.freeze({clearSource:ya,setEntries:Ca,setVisible:va});function gG(e){return pG({overlayHost:LE,...e})}const PE="#39d5ff",xE="#8fffd2",_G=66,Um=9e6,Kh=160,bG="telegeography-submarine-cables",CG=96,yG=.5,vG=yG**2,MG=2e3,wG=250,EG=Object.freeze(new Set(["bing-aerial","bing-labels","esri-imagery","osm"])),TG=Object.freeze([Object.freeze({key:"_billboardCollection",type:Cesium.BillboardCollection}),Object.freeze({key:"_pointCollection",type:Cesium.PointPrimitiveCollection})]);function FE(){return typeof performance=="object"&&typeof performance.now=="function"?performance.now():Date.now()}function kG(e,t=Kh){const n=Math.max(0,Math.min(Kh,Math.floor(Number(t)||0)));return!Array.isArray(e)||n===0?[]:e.filter(i=>(i==null?void 0:i.visible)===!0&&i.label&&Number.isFinite(i.distanceM)&&i.distanceM<=Um).sort((i,o)=>{var r,s;return i.distanceM-o.distanceM||String(((r=i.entity)==null?void 0:r.id)||"").localeCompare(String(((s=o.entity)==null?void 0:s.id)||""))}).slice(0,n)}function SE(e){const t=Number.isFinite(e)?Math.max(0,e):Um;return 1e3-Math.round(t/5e4)}function AG(e){const t=(e==null?void 0:e.kind)==="landing-point"?"landing-point":"cable";return{id:String((e==null?void 0:e.id)||""),position:e==null?void 0:e.tip,variant:"label",title:String((e==null?void 0:e.label)||""),accent:t==="cable"?PE:xE,priority:SE(e==null?void 0:e.distanceM),collisionGroup:"ambient-label",paintLane:"ambient-label",interactive:!1,minDistance:0,maxDistance:Um,distanceFadeStartRatio:.7,distanceScale:{near:25e4,nearValue:1,far:9e6,farValue:.62},edgeFade:"keyhole",horizonCull:!0,terrainOcclusion:!1,gapPx:14,verticalOnly:!0,placement:"above"}}function IG({sourceId:e=bG,host:t}={}){let n=!1,i=!1;const o={cohortLimit:Kh,collisionCapacity:CG,moving:!1};return{show(){n||(n=!0,t.setVisible(e,!0))},publish(r){n&&(t.setEntries(e,r,o),i=r.length>0)},hide(){i&&t.clearSource(e),n&&t.setVisible(e,!1),n=!1,i=!1}}}function RG({now:e=FE,probeIntervalMs:t=MG,motionEpsilonM:n=wG}={}){const i=n**2,o=new Cesium.Cartesian3;let r=!1,s=!0,a=-1/0;function c(l,u){a=u;const h=l==null?void 0:l.positionWC;return r=!!h,h&&Cesium.Cartesian3.clone(h,o),!0}return{markDirty(){s=!0},shouldRun(l){if(s)return s=!1,c(l,e());if(!l)return!1;const u=e();if(u-a{var s,a;t.rendering.applyCableClassification((s=r==null?void 0:r.detail)!=null&&s.activeId?FG(r.detail.activeId):Wb((a=e._viewer)==null?void 0:a.scene))},i.addEventListener("gev:map-stack-changed",e._mapStackListener)),t.interaction.beginInteraction(o),e._preRenderRemover||(e._preRenderRemover=o.scene.preRender.addEventListener(()=>{!e._enabled||!e._loaded||!e._referenceSweepGate.shouldRun(o.camera)||t.rendering.updateReferenceVisibility()})),e._moveEndRemover||(e._moveEndRemover=o.camera.moveEnd.addEventListener(()=>{var r,s;e._enabled&&(e._referenceSweepGate.markDirty(),(s=(r=o.scene).requestRender)==null||s.call(r))}))},enable(o){var r,s,a;e._enabled=!0,t.rendering.updateVisibility(),e._overlayPublisher.show(),t.rendering.resetPublishSignature(),e._referenceSweepGate.markDirty(),(a=(s=(r=o||e._viewer)==null?void 0:r.scene)==null?void 0:s.requestRender)==null||a.call(s),t.ingestion.load(o||e._viewer)},disable(){e._enabled=!1,e._overlayPublisher.hide(),t.rendering.resetPublishSignature(),e._loading&&e._abort&&(e._abort.abort(),e._loading=!1,e._loadingLabel=""),t.rendering.releaseDataSources(e._viewer)},update(o){return t.ingestion.load(o||e._viewer)},destroy(o){e._abort&&e._abort.abort(),t.rendering.releaseDataSources(o||e._viewer),e._cachedCableJson=null,e._cachedLandingJson=null,e._overlayPublisher.hide(),e._clickHandler&&(e._clickHandler.destroy(),e._clickHandler=null),e._preRenderRemover&&(e._preRenderRemover(),e._preRenderRemover=null),e._moveEndRemover&&(e._moveEndRemover(),e._moveEndRemover=null),e._mapStackListener&&(i!=null&&i.removeEventListener)&&(i.removeEventListener("gev:map-stack-changed",e._mapStackListener),e._mapStackListener=null),e._viewer=null,e._enabled=!1,e._loading=!1,e._loaded=!1,e._count=0,e._error=null,e._lastUpdate=null,e._loadingLabel="",e._cableDataSource=null,e._landingDataSource=null,e._referenceDataSource=null,e._referenceRecords=[],e._surfaceRecords=[],e._pickByEntity=new WeakMap,e._referenceLabelCount=0,e._publishScratch.length=0,e._markerBlendDone=!1,e._markerBlendInvariantWarned=!1,t.rendering.resetPublishSignature(),e._referenceSweepGate.reset()},getStats(){return{count:e._count,lastUpdate:e._lastUpdate,loading:e._loading,loadingLabel:e._loadingLabel,error:e._error,referenceLabelCount:e._referenceLabelCount}}}}function NG({state:e}){function t(){e._lastPublishedIds.length=0,e._lastPublishedPriorities.length=0,e._lastPublishedCount=-1}function n(u){var d;const h=[e._cableDataSource,e._landingDataSource,e._referenceDataSource];e._cableDataSource=null,e._landingDataSource=null,e._referenceDataSource=null,e._referenceRecords=[],e._surfaceRecords=[],e._pickByEntity=new WeakMap,e._referenceLabelCount=0,e._publishScratch.length=0,e._markerBlendDone=!1,e._loaded=!1,e._referenceSweepGate.reset();for(const f of h)if(f)try{(d=u==null?void 0:u.dataSources)==null||d.remove(f,!0)}catch{}}function i(){e._cableDataSource&&(e._cableDataSource.show=e._enabled),e._landingDataSource&&(e._landingDataSource.show=e._enabled),e._referenceDataSource&&(e._referenceDataSource.show=e._enabled)}function o(u,h){var f;if(!(u!=null&&u.polyline))return;const d=(f=h==null?void 0:h.properties)!=null&&f.color?Cesium.Color.fromCssColorString(String(h.properties.color)):e.cableColor;u.polyline.material=d.withAlpha(.92),u.polyline.width=2.5,u.polyline.clampToGround=!0,u.polyline.classificationType=e._classificationType,u.show=!0}function r(){const u=Kb(e._landingDataSource),h=Kb(e._referenceDataSource);if(u.invariantFailed||h.invariantFailed){e._markerBlendDone=!0,e._markerBlendInvariantWarned;return}const d=Yb(u),f=Yb(h);d.applied>0&&f.applied>0&&(e._markerBlendDone=!0)}function s(u){var d,f,p;if(u===void 0||u===e._classificationType||(e._classificationType=u,!e._cableDataSource))return;const h=e._cableDataSource.entities.values;for(let g=0;g{var s;const r=((s=i==null?void 0:i.properties)==null?void 0:s.id)||(i==null?void 0:i.id)||`${t}-${o}`;return{...i,id:String(r)}})}function BG({state:e,parts:t,source:n}){async function i(o){var c,l;if(e._loading||e._loaded)return;e._loading=!0,e._error=null,e._loadingLabel="loading...";const r=++e._loadGeneration,s=new AbortController;e._abort=s;const a=()=>r===e._loadGeneration&&!s.signal.aborted;try{let u=e._cachedCableJson,h=e._cachedLandingJson;if(!u||!h){if({cables:u,landingPoints:h}=await n.fetch(s.signal),!a())return;if(!Array.isArray(u==null?void 0:u.features)||!Array.isArray(h==null?void 0:h.features))throw new TypeError("A cable source must return cables and landingPoints GeoJSON collections");e._cachedCableJson=u,e._cachedLandingJson=h}const d=Qb(u,"cable"),f=Qb(h,"landing"),p=await Cesium.GeoJsonDataSource.load({type:"FeatureCollection",features:d},{clampToGround:!0,stroke:e.cableColor.withAlpha(.95),fill:e.cableColor.withAlpha(.18),strokeWidth:2,markerColor:e.cableColor,markerSize:6});if(!a())return;const g=await Cesium.GeoJsonDataSource.load({type:"FeatureCollection",features:f},{clampToGround:!0,stroke:e.landingColor.withAlpha(.9),fill:e.landingColor.withAlpha(.35),strokeWidth:2,markerColor:e.landingColor,markerSize:6});if(!a())return;p.name=`${n.label} Submarine Cables`,g.name=`${n.label} Landing Points`;const _=new Cesium.CustomDataSource(`${n.label} Cable References`),m=[p,g,_],C=(await Promise.allSettled([o.dataSources.add(p),o.dataSources.add(g),o.dataSources.add(_)])).find(M=>M.status==="rejected");if(!a()||C){for(const M of m)try{o.dataSources.remove(M,!0)}catch{}if(a()&&C)throw C.reason;return}e._cableDataSource=p,e._landingDataSource=g,e._referenceDataSource=_;const y=e._cableDataSource.entities.values,v=e._landingDataSource.entities.values;e._pickByEntity=new WeakMap,e._referenceRecords=[],e._surfaceRecords=[],y.forEach((M,w)=>{const E=d[w],k=Xb(E);k&&(t.rendering.styleCableEntity(M,E),t.interaction.registerPickEntity(M,{kind:"cable",reference:k,label:Wa(E)}),e._surfaceRecords.push({entity:M,base:Cesium.Cartesian3.fromDegrees(k.lon,k.lat,0)}),t.rendering.addReferenceStem({reference:k,label:Wa(E),kind:"cable",color:e.cableColor,feature:E}))}),v.forEach((M,w)=>{const E=f[w],k=Xb(E);k&&(t.rendering.styleLandingEntity(M,E),t.interaction.registerPickEntity(M,{kind:"landing-point",reference:k,label:Wa(E)}),e._surfaceRecords.push({entity:M,base:Cesium.Cartesian3.fromDegrees(k.lon,k.lat,0)}),t.rendering.addReferenceStem({reference:k,label:Wa(E),kind:"landing-point",color:e.landingColor,feature:E}))}),e._count=d.length+f.length,e._loaded=!0,e._lastUpdate=Date.now(),e._loadingLabel="",t.rendering.updateVisibility(),e._referenceSweepGate.markDirty(),(l=(c=o.scene).requestRender)==null||l.call(c)}catch(u){a()&&(u==null?void 0:u.name)!=="AbortError"&&(e._error=(u==null?void 0:u.message)||"TeleGeography load failed",console.warn("[Data:telegeography-submarine-cables]",e._error,u))}finally{r===e._loadGeneration&&(e._loading=!1,e._abort===s&&(e._abort=null))}}return{load:i}}function VG({state:e,screenSpaceEventHandlerFactory:t}){function n(s,a){s.__gevTeleGeography=a,e._pickByEntity.set(s,a)}function i(s){e._clickHandler||(e._clickHandler=t(s.scene.canvas),e._clickHandler.setInputAction(a=>{if(!Bt()||!e._enabled)return;const c=s.scene.pick(a.position),l=o(c);l!=null&&l.reference&&r(s,l.reference)},Cesium.ScreenSpaceEventType.LEFT_CLICK))}function o(s){if(!s)return null;const a=s.primitive;if(a){const l=e._pickByEntity.get(a);if(l)return l;if(a.__gevTeleGeography)return a.__gevTeleGeography;if(a.id&&typeof a.id=="object"&&a.id.reference)return a.id}const c=s.id;if(c){const l=e._pickByEntity.get(c);if(l)return l;if(c.__gevTeleGeography)return c.__gevTeleGeography;if(c.id&&typeof c.id=="object"&&c.id.reference)return c.id}return null}function r(s,a){if(!s||!a)return;const c=Cesium.Cartesian3.fromDegrees(a.lon,a.lat,6500);s.camera.cancelFlight(),s.camera.flyTo({destination:c,orientation:{heading:s.camera.heading||0,pitch:Cesium.Math.toRadians(-52),roll:0},duration:1.35,easingFunction:Cesium.EasingFunction.CUBIC_IN_OUT})}return{registerPickEntity:n,beginInteraction:i,resolvePickRecord:o,flyToReference:r}}function HG({source:e,overlayHost:t,screenSpaceEventHandlerFactory:n,mapStackEventTarget:i=null,sweepClock:o=FE}){if(!(e!=null&&e.fetch)||!e.label)throw new TypeError("A cable source with a label and fetch(signal) is required");const r=xG({overlayHost:t,sweepClock:o}),s={},a={state:r,parts:s,source:e,screenSpaceEventHandlerFactory:n,mapStackEventTarget:i};return s.rendering=NG(a),s.ingestion=BG(a),s.interaction=VG(a),SG(a)}function $G(e){return HG({overlayHost:LE,screenSpaceEventHandlerFactory:t=>new Cesium.ScreenSpaceEventHandler(t),mapStackEventTarget:typeof window<"u"?window:null,...e})}const GG=80,UG=200,Yh=420,Zb=3e6,zG=2e5;function jG(e){const t=Number.isFinite(e)?Math.max(0,e):Zb;return t>=Zb?{activeLimit:GG}:t>=zG?{activeLimit:UG}:{activeLimit:Yh}}const qG=250,Jb=12e6,e0=200;function WG(e,t,n,{incumbentBonus:i=qG,farM:o=Jb,maxDistancePenalty:r=e0}={}){const s=Number.isFinite(e)?e:0,a=Number.isFinite(o)&&o>0?o:Jb,c=Number.isFinite(t)&&t>=0?t:a,l=Number.isFinite(r)&&r>=0?r:e0,u=n&&Number.isFinite(i)?i:0;return s+u-l*Math.min(1,c/a)}function t0(e){return Number.isFinite(e)&&e>=0?e:Number.MAX_VALUE}function KG(e,{cameraHeightM:t,incumbentIds:n}={}){const i=jG(t),o=n instanceof Set?n:new Set(n||[]),r=new Map;for(const a of Array.isArray(e)?e:[]){if(!a||typeof a.id!="string"||!a.id||a.inView!==!0)continue;const c=Number.isFinite(a.distanceM)&&a.distanceM>=0?a.distanceM:Number.POSITIVE_INFINITY,l={id:a.id,distanceM:c,score:WG(a.priority,a.distanceM,o.has(a.id))},u=r.get(l.id);(!u||l.score>u.score||l.score===u.score&&l.distanceMc.score-a.score||t0(a.distanceM)-t0(c.distanceM)||a.id.localeCompare(c.id)).slice(0,i.activeLimit).map(a=>a.id),budget:i}}const YG=2,XG=4e3;function QG({selectedIds:e=[],builtIds:t=[],graceState:n=new Map,nowMs:i=0,activeLimit:o=Yh,gracePasses:r=YG,graceMs:s=XG}={}){const a=new Set((Array.isArray(e)?e:[]).filter(g=>typeof g=="string"&&g)),c=[...a],l=[],u=new Map,h=[];for(const g of Array.isArray(t)?t:[]){if(typeof g!="string"||!g||a.has(g))continue;const _=n instanceof Map?n.get(g):void 0,m=((_==null?void 0:_.misses)||0)+1,b=Number.isFinite(_==null?void 0:_.since)?_.since:i;m>r||i-b>=s?l.push(g):h.push({id:g,misses:m,since:b})}h.sort((g,_)=>g.since-_.since||_.misses-g.misses||g.id.localeCompare(_.id));const d=Number.isFinite(o)?Math.max(0,Math.floor(o)):Yh,f=Math.max(0,d-c.length),p=Math.max(0,h.length-f);for(let g=0;g=0?n:o0,o=Number.isFinite(t)&&t>=0?t:i0,r=Number.isFinite(e)&&e>0?e:0;return Math.max(i,r*o)}function JG({nowMs:e=0,lastProbeMs:t=Number.NEGATIVE_INFINITY,movedSqM:n=0,cameraHeightM:i,probeIntervalMs:o=n0,motionEpsilonM:r}={}){const s=Number.isFinite(e)?e:0,a=Number.isFinite(t)?t:Number.NEGATIVE_INFINITY,c=Number.isFinite(o)&&o>=0?o:n0;if(s-a0?n:0,u=Number.isFinite(r)&&r>=0?r:ZG(i);return{recompute:l>u*u,lastProbeMs:s}}const eU=900,tU=132,nU=450,DE=160,iU=96,r0=2,OE=14e6,oU=25e4,rU=oU/OE,Cc=75e3,Xh=2e3,Qh=9e3,sU=30,aU=.5,lU=aU**2;function cU(e,t){const n=$s(e)||{},i=n.tags||{},o=HE(n,t),r=[];if(t==="local-datacenters"){const s=cd([i.operator,n.operator,i["operator:short"]]),a=cd([i["capacity:it_load"],i.it_load,i.capacity,n.capacity]),c=[s,a].filter((l,u,h)=>l&&h.indexOf(l)===u).filter(l=>l.toLocaleLowerCase()!==o.toLocaleLowerCase()).join(" · ");c&&r.push(l0(c))}else if(t==="local-dams"){const s=cd([i.associated_river,n.associated_river,i.river,n.river,i["river:name"]]);s&&s.toLocaleLowerCase()!==o.toLocaleLowerCase()&&r.push(l0(s))}return{title:o,details:r}}function uU({id:e,layerId:t,position:n,properties:i,priority:o,accent:r}){const s=cU(i,t);return{id:String(e),source:t,position:n,variant:"card",title:s.title,details:s.details,accent:r,priority:o,collisionGroup:"ambient-card",zIndex:30,interactive:!1,minDistance:0,maxDistance:OE,distanceFadeStartRatio:rU,distanceScale:{near:25e4,nearValue:1,far:9e6,farValue:.62},edgeFade:"keyhole",horizonCull:!0,terrainOcclusion:!1,gapPx:15,placement:"above"}}function dU(e,{maxEntries:t,gridPx:n,width:i,height:o,project:r,cohortLimit:s=Number.POSITIVE_INFINITY}){const a=Math.max(0,Math.floor(Number(t)||0)),c=Number.isFinite(Number(s))?Math.max(0,Math.floor(Number(s))):Number.POSITIVE_INFINITY,l=Math.min(a,c),u=Math.max(1,Number(n)||1);if(!Array.isArray(e)||e.length===0||l===0||typeof r!="function")return[];const h=new Map,d=u;for(const _ of e){const m=r(_);if(!Number.isFinite(m==null?void 0:m.x)||!Number.isFinite(m==null?void 0:m.y)||m.x<-d||m.x>i+d||m.y<-d||m.y>o+d)continue;const b=`${Math.floor(m.x/u)}:${Math.floor(m.y/u)}`;let C=h.get(b);C||(C=[],h.set(b,C)),mU(C,_)}const f=[],p=[];for(const _ of h.values())_[0]&&f.push(_[0]),_[1]&&p.push(_[1]);return f.sort(Zh),p.sort(Zh),f.length>=l?f.slice(0,l).map(_=>_.entry):f.concat(p.slice(0,l-f.length)).map(_=>_.entry)}function hU({sourceId:e,host:t}){let n=!1,i=!1,o=!1,r=null;const s={cohortLimit:DE,collisionCapacity:iU,moving:!1};return{show(){o||n||(n=!0,t.setVisible(e,!0))},publish(a){o||!n||r&&a.length===r.length&&a.every((c,l)=>{var h,d,f;const u=r[l];return c===u.entry&&((h=c.position)==null?void 0:h.x)===u.x&&((d=c.position)==null?void 0:d.y)===u.y&&((f=c.position)==null?void 0:f.z)===u.z})||(t.setEntries(e,a,s),r=a.map(c=>{var l,u,h;return{entry:c,x:(l=c.position)==null?void 0:l.x,y:(u=c.position)==null?void 0:u.y,z:(h=c.position)==null?void 0:h.z}}),i=a.length>0)},hide(){o||(i&&t.clearSource(e),n&&t.setVisible(e,!1),n=!1,i=!1,r=null)},destroy(){o||(i&&t.clearSource(e),n&&t.setVisible(e,!1),n=!1,i=!1,r=null,o=!0)}}}function fU(e){if((e==null?void 0:e.name)==="SyntaxError")return"dataset is malformed";const t=String((e==null?void 0:e.message)||"").trim();return t?`dataset unavailable (${t})`:"dataset unavailable"}function s0({id:e,url:t,name:n,color:i,icon:o="📍",source:r="Local JSONL",labels:s=!0,labelMax:a=eU,labelGridPx:c=tU,screenSpaceEventHandlerFactory:l=m=>new Cesium.ScreenSpaceEventHandler(m),projectToWindow:u=(m,b)=>Cesium.SceneTransforms.worldToWindowCoordinates(m,b)},{overlayHost:h,registerEntityContext:d,selectEntityContext:f,clearSelectedEntityContextForLayer:p,removeEntityContextsForLayer:g,governorRequestRender:_}){let m=null,b=!1,C=null,y=0,v=null,M=null,w=null,E=null,k=[],T=!0,I=0,R=!1,S=null,A=null,L=null,F=new Set,P=new Map,O=0,D=!1;const $=new Cesium.Cartesian3;let x=Number.NEGATIVE_INFINITY,N=null,G=0,W=null;function V(j){var ne;N||!b||(ne=j==null?void 0:j.scene)!=null&&ne.sampleHeightSupported&&(G>=sU||(G+=1,N=setTimeout(()=>{N=null,!(!b||R)&&_(`local-ground-retry:${e}`)},Xh)))}function H(){G=0,W=null,N&&(clearTimeout(N),N=null)}const B=hU({sourceId:e,host:h}),q=j=>{var ee;if(!m)return;const ne=m;m=null,k=[],T=!0,I=Number.NEGATIVE_INFINITY,g(e);try{(ee=j==null?void 0:j.dataSources)==null||ee.remove(ne,!0)}catch{}},z=j=>{var ne;b=!1,H(),F=new Set,P=new Map,O=0,D=!1,x=Number.NEGATIVE_INFINITY,q(j),B.hide(),p(e),((ne=j==null?void 0:j.selectedEntity)==null?void 0:ne.__localLayerId)===e&&(j.selectedEntity=void 0),w&&(w(),w=null),E&&(E(),E=null)};return{id:e,name:n,icon:o,source:r,updateInterval:0,statsRefreshInterval:1e3,init:async j=>{},update:async j=>{},getStats:()=>({count:y,lastUpdate:v,error:M}),getLodDiagnostics:()=>({total:k.length,active:F.size,budgetLimit:O,computed:D}),enable:async j=>{var ne,ee;if(!R){if(b=!0,T=!0,I=Number.NEGATIVE_INFINITY,G=0,W=null,F=new Set,P=new Map,O=0,D=!1,x=Number.NEGATIVE_INFINITY,B.show(),!m){S||(S=(async()=>{var be,J,Z;A=new AbortController;const re=Cesium.Color.fromCssColorString(i);M=null;let se=null,me=!1;try{let ae=L;if(!ae){const Y=await fetch(t,{signal:A.signal});if(R)return;if(!Y.ok)throw new Error(`HTTP ${Y.status??"?"}`);const K=await Y.text();if(R)return;ae=K.split(` +`).filter(he=>he.trim().length>0).map(he=>JSON.parse(he)),L=ae}const oe={type:"FeatureCollection",features:ae};if(se=await Cesium.GeoJsonDataSource.load(oe,{clampToGround:!0,stroke:re,fill:re.withAlpha(.3),strokeWidth:2,markerSize:8,markerColor:re}),R)return;if(se.name=n,se.show=!1,await j.dataSources.add(se),me=!0,R){j.dataSources.remove(se,!0);return}const le=se.entities.values;y=le.length,k=[],T=!0;for(let Y=0;Y0&&(_e=Cesium.BoundingSphere.fromPoints(ke.positions).center)}if(!_e)continue;const he=Cesium.Cartographic.fromCartesian(_e),Ce=0,ye=2e3,ve=Cesium.Cartesian3.fromRadians(he.longitude,he.latitude,Ce),pe=Cesium.Cartesian3.fromRadians(he.longitude,he.latitude,ye),te=_U(K),de=String(K.id??Y);K.__localBaseCarto=he,K.__localBaseCartesian=ve,d(K,{id:`${e}:${de}`,layerId:e,layerName:n,source:r,dataSource:se,label:HE(te,e),properties:te,latitude:Number(Cesium.Math.toDegrees(he.latitude).toFixed(6)),longitude:Number(Cesium.Math.toDegrees(he.longitude).toFixed(6))}),K.position=pe;const U=[[ve,pe],[ve,pe]];K.polyline=new Cesium.PolylineGraphics({positions:U[0],width:3.5,material:new Cesium.ColorMaterialProperty(re)}),K.point=new Cesium.PointGraphics({pixelSize:10,color:re,outlineColor:Cesium.Color.BLACK,outlineWidth:2,disableDepthTestDistance:Number.POSITIVE_INFINITY});const Le=gU(te,e);k.push({id:de,entity:K,carto:he,base:ve,tip:pe,nextTip:Cesium.Cartesian3.clone(pe),stemPositionBuffers:U,stemPositionBufferIndex:0,groundHeight:Ce,groundSampled:!1,lastGroundSampleMs:0,priority:Le,entry:s?uU({id:de,layerId:e,position:pe,properties:te,priority:Le,accent:i}):null})}m=se,v=Date.now()}catch(ae){if(R||(M=fU(ae)),me)try{(Z=j==null?void 0:j.dataSources)==null||Z.remove(se,!0)}catch{}if(R)return;g(e),y=0,k=[],console.error(`Failed to load ${e}:`,ae)}R||C||(C=l(j.scene.canvas),C.setInputAction(ae=>{if(!Bt()||!b)return;const oe=j.scene.pick(ae.position);if(oe&&oe.id&&oe.id.__localLayerId===e){const le=oe.id;j.selectedEntity=le,f(le);let Y=null;if(le.polyline){const K=le.polyline.positions.getValue(Cesium.JulianDate.now());K&&K.length>0&&(Y=K[0])}else if(le.polygon&&le.polygon.hierarchy){const K=le.polygon.hierarchy.getValue(Cesium.JulianDate.now());K&&K.positions.length>0&&(Y=Cesium.BoundingSphere.fromPoints(K.positions).center)}if(Y){const K=Cesium.Cartographic.fromCartesian(Y);j.scene.screenSpaceCameraController.enableInputs=!1,j.camera.flyTo({destination:Cesium.Cartesian3.fromRadians(K.longitude,K.latitude,5e3),duration:1.5,complete:()=>{j.scene.screenSpaceCameraController.enableInputs=!0},cancel:()=>{j.scene.screenSpaceCameraController.enableInputs=!0}})}}},Cesium.ScreenSpaceEventType.LEFT_CLICK))})());try{await S}finally{S=null,A=null}}if(!R){if(b&&!w&&(w=j.scene.preRender.addEventListener(()=>{var K,_e;if(!b||!m)return;const re=performance.now();if(re-I0){const he=JG({nowMs:re,lastProbeMs:x,movedSqM:Cesium.Cartesian3.distanceSquared(se,$),cameraHeightM:(K=j.camera.positionCartographic)==null?void 0:K.height});x=he.lastProbeMs,he.recompute&&(T=!0)}const me=new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84,se),be=[],J=T,Z=j.scene.sampleHeightSupported===!0;Z&&W===!1&&(G=0),W=Z;let ae=!1,oe=!1;if(J&&k.length>0){const he=(_e=j.camera.positionCartographic)==null?void 0:_e.height,Ce=new Array(k.length);for(let pe=0;pe=Xh){const de=Cesium.Cartesian3.distance(j.camera.positionWC,Ce.base);deu(j.scene,he.tip)});B.publish(Y)})),b&&!E&&(E=j.camera.moveEnd.addEventListener(()=>{var re,se;b&&(T=!0,I=Number.NEGATIVE_INFINITY,G=0,(se=(re=j.scene).requestRender)==null||se.call(re))})),!b){q(j);return}m&&(m.show=!0),(ee=(ne=j.scene).requestRender)==null||ee.call(ne)}}},disable:z,destroy:j=>{R||(R=!0,A==null||A.abort(),z(j),g(e),C&&(C.destroy(),C=null),m&&j&&j.dataSources.remove(m,!0),B.destroy(),m=null,L=null,k=[],y=0,v=null,M=null)}}}function Zh(e,t){return t.priority-e.priority||String(e.id).localeCompare(String(t.id))}function mU(e,t){let n=0;for(;nr0&&(e.length=r0)}function pU(e,t){var o;const n=e.scene.globe;if(!t.groundSampled||!(n!=null&&n.show)||n.tilesLoaded===!1||Cesium.Cartesian3.distance(e.camera.positionWC,t.base)>=Cc)return!1;const i=(o=n.getHeight)==null?void 0:o.call(n,t.carto);return!Number.isFinite(i)||Math.abs(i)>Qh||i<=t.groundHeight?!1:(VE(t,i),!0)}function BE(e,t,n){var s;if(t.groundSampled||!e.scene.sampleHeightSupported||n-t.lastGroundSampleMsQh)return!1;const r=i!=null&&i.show?(s=i.getHeight)==null?void 0:s.call(i,t.carto):void 0;return Number.isFinite(r)&&Math.abs(r)<=Qh&&(o=Math.max(o,r)),t.groundSampled=!0,VE(t,o),!0}function VE(e,t){e.groundHeight=t,Cesium.Cartesian3.fromRadians(e.carto.longitude,e.carto.latitude,e.groundHeight,Cesium.Ellipsoid.WGS84,e.base),e.entity.__localBaseCartesian=e.base}function a0(e,t,n,i=null){const o=Number.isFinite(i)?i:Cesium.Cartesian3.distance(e.camera.positionWC,t.base);o34?`${t.slice(0,31)}...`:t}function l0(e){const t=Qn(e);return t.length>48?`${t.slice(0,45)}...`:t}function ud(e){return e==="local-datacenters"?"Datacenter":e==="local-dams"?"Dam":"Feature"}const CU=new URL("/assets/datacenters-CtzejECr.geojsonl",import.meta.url).href,yU=new URL("/assets/dams-B2lCjFgp.geojsonl",import.meta.url).href;function vU(e){const t=s0({id:"local-datacenters",url:CU,name:"Datacenters",color:"#00ffff",icon:"▣",source:"Local",labels:!0,labelMax:700,labelGridPx:138},e),n=s0({id:"local-dams",url:yU,name:"Dams",color:"#0088ff",icon:"▰",source:"USACE",labels:!0,labelMax:900,labelGridPx:132},e);return[t,n]}const MU=Object.freeze({overlayHost:Object.freeze({clearSource:ya,setEntries:Ca,setVisible:va}),clearSelectedEntityContextForLayer:Wv,registerEntityContext:tu,removeEntityContextsForLayer:Kv,selectEntityContext:qv,governorRequestRender:qt}),wU=Object.freeze({flights:["getSnapshot"],military:["getSnapshot"],vessels:["getSnapshot"],cctv:["getCatalog","getHealth","getFrameUrl","getMediaUrl"],radio:["getDirectory","recordClick"],traffic:["requestRoads","getStatus","fetchFlowForBounds","getFlowSessionStats","resetFlowTileCache"],bikeshare:["getStations"],installations:["getMappedSites","searchNearby"],satellites:["readGroup"],launches:["getLaunches","getActiveTle"],alpr:["fetch"],firms:["getSnapshot"],earthquakes:["getSnapshot"],cables:["fetch"]});function EU({surface:e,sources:t,signal:n,metadata:i=pn,vesselOptions:o,resolveAsset:r}){if(!(n!=null&&n.addEventListener))throw new TypeError("An application lifetime signal is required");if(n.throwIfAborted(),!(e!=null&&e.groundFloor)||!(e!=null&&e.terrain))throw new TypeError("Application surface services are required");for(const[c,l]of Object.entries(wU))if(l.some(u=>{var h;return typeof((h=t==null?void 0:t[c])==null?void 0:h[u])!="function"}))throw new TypeError(`Invalid catalog source: ${c}`);const s=Xk(),a=()=>{n.removeEventListener("abort",a),s.dispose()};n.addEventListener("abort",a,{once:!0});try{s.configureSource(t.military,{signal:n});const c=H1({surface:e,source:t.flights,militaryRegistry:s,resolveAsset:r}),l=kP({surface:e,source:t.military,militaryRegistry:s,resolveAsset:r}),u=ax({source:t.vessels,options:o}),h=UV({surface:e,source:t.installations}),d=HH({source:t.satellites}),f=Sk([c,l,gG({source:t.earthquakes}),Y$({surface:e,source:t.alpr}),d,T$({source:t.launches,satellites:d}),M2({source:t.traffic}),fD({surface:e,source:t.cctv}),eO({surface:e,source:t.radio}),Y2({source:t.bikeshare}),JB(),vV({surface:e}),u,h,H4({flights:c,military:l,vessels:u,installations:h}),...vU(MU),$G({source:t.cables}),sG({surface:e,id:"local-firms",name:"FIRMS Active Fires",icon:"▲",source:"NASA FIRMS · LIVE",feed:t.firms})],i);return Object.freeze({...f,militaryRegistry:s,surface:e})}catch(c){throw a(),c}}class $r extends Error{constructor(t,n,{status:i=null,retryAfterMs:o=2e4,source:r=null}={}){super(n),this.name="LiveSourceError",this.code=t,this.status=i,this.retryAfterMs=o,this.source=r}}function Ye(e){if(e==null||e===""||typeof e=="boolean")return null;const t=Number(e);return Number.isFinite(t)?t:null}function Dn(e,t=1){const n=Ye(e),i=n==null?null:n*t;return i!=null&&i>0&&i<=864e13?i:null}function hn(e){return typeof e=="string"?e.trim():""}function Ta(e,t){return Number.isFinite(e)&&Math.abs(e)<=90&&Number.isFinite(t)&&Math.abs(t)<=180}function zm(e,t,n){if(!Array.isArray(e))throw new $r("malformed",`Malformed ${n} response`);const i=[],o=new Set;for(const r of e){const s=t(r);s&&!o.has(s.id)&&(i.push(s),o.add(s.id))}if(e.length&&!i.length)throw new $r("malformed",`Malformed ${n} aircraft rows`);return{records:i,complete:i.length===e.length,rejectedCount:e.length-i.length}}async function Fi(e,t,{signal:n,...i}={},o="Live source"){n==null||n.throwIfAborted();let r;try{r=await e(t,{...i,signal:n}),n==null||n.throwIfAborted()}catch(a){throw n==null||n.throwIfAborted(),(a==null?void 0:a.name)==="AbortError"?a:new $r("unavailable",`${o} network error`,{source:o})}let s=null;try{s=await r.json()}catch{}return n==null||n.throwIfAborted(),{response:r,payload:s}}function Si(e,t){const n=e.status,i=n===429?"limited":n===401||n===403?"denied":"unavailable";return new $r(i,n===429?`${t} rate limited`:`${t} HTTP ${n}`,{status:n,source:t,retryAfterMs:i==="limited"||i==="denied"?45e3:2e4})}function TU(e){if(!Array.isArray(e))return null;const t=hn(e[0]).toLowerCase();return!t||!Ta(e[6],e[5])?null:{id:t,reference:t,latitude:e[6],longitude:e[5],callsign:hn(e[1]),originCountry:hn(e[2]),positionTimeMs:Dn(e[3],1e3),contactTimeMs:Dn(e[4],1e3),baroAltitudeM:Ye(e[7]),ellipsoidAltitudeM:Ye(e[13]),onGround:e[8]===!0,speedMps:Ye(e[9]),courseDeg:Ye(e[10]),verticalRateMps:Ye(e[11]),category:Ye(e[17]),typeCode:null,registration:null,operator:null}}function kU(e,t){const n=hn(e==null?void 0:e.hex).toLowerCase(),i=Ye(e==null?void 0:e.lat),o=Ye(e==null?void 0:e.lon);if(!n||!Ta(i,o))return null;const r=Ye(e.alt_baro),s=Ye(e.alt_geom),a=Ye(e.gs),c=Ye(e.baro_rate),l=Ye(e.seen),u=Ye(e.seen_pos);return{id:n,reference:n,latitude:i,longitude:o,callsign:hn(e.flight),originCountry:null,positionTimeMs:t==null?null:t-(u??0)*1e3,contactTimeMs:t==null||l==null?null:t-l*1e3,baroAltitudeM:r==null?null:r*.3048,ellipsoidAltitudeM:s==null?null:s*.3048,onGround:hn(e.alt_baro).toLowerCase()==="ground",speedMps:a==null?null:a*.514444,courseDeg:Ye(e.track),verticalRateMps:c==null?null:c*.00508,category:e.category??null,typeCode:hn(e.t),registration:hn(e.r),operator:hn(e.ownOp)}}function AU(e,{source:t="OpenSky Network",coverage:n="worldwide upstream snapshot",now:i=Date.now(),stale:o=!1}={}){const r=zm(e==null?void 0:e.states,TU,"OpenSky"),s=Dn(e==null?void 0:e.time,1e3),a=s==null?null:Math.max(0,i-s);return{...r,source:t,coverage:n,observedAtMs:s,ageMs:a,stale:o||a!=null&&a>12e4,freshness:s==null?"unknown":o||a>12e4?"stale":"current"}}function IU(e,{observedAtMs:t,source:n="adsb.lol",coverage:i="military upstream snapshot",now:o=Date.now(),stale:r=!1}={}){const s=zm(e==null?void 0:e.ac,c=>kU(c,t),"adsb.lol"),a=t==null?null:Math.max(0,o-t);return{...s,source:n,coverage:i,observedAtMs:t,ageMs:a,stale:r,freshness:t==null?"unknown":r?"stale":"current"}}function $E(e,{baseTimeMs:t=0,readsb:n=!1}={}){return Array.isArray(e)?e.flatMap(i=>{if(!Array.isArray(i))return[];const o=Ye(i[1]),r=Ye(i[2]),s=Ye(i[0]),a=s==null?null:Dn(t+s*1e3);if(!Ta(o,r)||a==null||a<=0)return[];const c=Ye(i[3]);return[{latitude:o,longitude:r,observedAtMs:a,baroAltitudeM:c==null?null:c*(n?.3048:1),ellipsoidAltitudeM:null,onGround:n?hn(i[3]).toLowerCase()==="ground":i[5]===!0}]}):[]}function RU(e){return zm(e==null?void 0:e.ac,n=>{const i=hn(n==null?void 0:n.hex).toLowerCase();return i?{id:i}:null},"aircraft identities").records.map(n=>n.id)}function LU(e,t=null){const n=String((e==null?void 0:e.mmsi)||(e==null?void 0:e.input_identifier)||"").trim(),i=Ye(e==null?void 0:e.lat),o=Ye(e==null?void 0:e.lon);if(!n||!Ta(i,o))return null;const r=Ye(e.speed);return{id:n,reference:t??n,latitude:i,longitude:o,name:String(e.name||e.input_name||n),imo:String(e.imo||""),type:String(e.type_specific||e.type||""),destination:String(e.destination||""),speedMps:r==null?null:r*.514444,courseDeg:Ye(e.course),headingDeg:Ye(e.heading),observedAtMs:Dn(e.last_position_epoch,1e3)??Dn(Date.parse(e.last_position_UTC)),altitudeDatum:"sea-surface"}}function PU(e,{source:t="AISStream",coverage:n="received AIS positions",referenceFor:i=o=>String(o.mmsi||o.input_identifier||"")}={}){if(!Array.isArray(e==null?void 0:e.rows))throw new $r("malformed","Malformed vessel response");const o=e.rows,r=[],s=new Set;for(const c of o){const l=LU(c);l&&(l.reference=i(c)),l&&!s.has(l.id)&&(r.push(l),s.add(l.id))}const a=Dn(e==null?void 0:e.newestPositionAt)??Dn(Date.parse(e==null?void 0:e.newestPositionAt))??r.reduce((c,l)=>Math.max(c||0,l.observedAtMs||0)||null,null);return{records:r,source:t,coverage:n,complete:r.length===o.length&&!(e!=null&&e.refreshing),rejectedCount:o.length-r.length,observedAtMs:a,freshness:e!=null&&e.refreshing?"stale":a==null?"unknown":"current",stale:!!(e!=null&&e.refreshing),transportStatus:typeof(e==null?void 0:e.status)=="string"?e.status:null,lastMessageAt:(e==null?void 0:e.lastMessageAt)??null,nextAttemptAt:Ye(e==null?void 0:e.nextAttemptAt),silentForMs:Ye(e==null?void 0:e.silentForMs),reconnectAttempt:Ye(e==null?void 0:e.reconnectAttempt),rawRowCount:o.length}}function xU(e){return Array.isArray(e)?e.flatMap(t=>{const n=Ye(t==null?void 0:t.lat),i=Ye(t==null?void 0:t.lon);return Ta(n,i)?[{latitude:n,longitude:i,observedAtMs:Dn(t==null?void 0:t.t,1e3),altitudeDatum:"sea-surface"}]:[]}):[]}const jm=(...e)=>globalThis.fetch(...e),Ao=(e,t)=>{var n,i;return(i=(n=e.headers)==null?void 0:n.get)==null?void 0:i.call(n,t)};function FU(e){const t=Si(e,"OpenSky"),n=String(Ao(e,"x-opensky-auth-mode-used")||Ao(e,"x-opensky-auth")||"").toLowerCase(),i=String(Ao(e,"x-opensky-auth-reason")||"").toLowerCase();if(e.status===429&&(!n||n==="anon")&&(t.message="OpenSky rate limited (anonymous)"),e.status===401||e.status===403){const o={oauth_invalid_or_missing:"OpenSky OAuth client missing/invalid",oauth_invalid_credentials:"OpenSky OAuth rejected credentials",basic_invalid_credentials:"OpenSky username/password rejected",missing_basic_creds:"OpenSky auth missing",missing_oauth_and_basic_creds:"OpenSky auth missing",auth_required:"OpenSky auth required",forced_anonymous:"OpenSky auth required"};t.message=o[i]||(/^(oauth_|basic_)/.test(i)?"OpenSky auth invalid":n==="anon"?"OpenSky auth required":"OpenSky auth failed")}return t}function SU({fetchImpl:e=jm,now:t=()=>Date.now()}={}){return{label:"OpenSky Network",async getSnapshot(n={},{signal:i}={}){const o=new URLSearchParams;Number.isFinite(n.latitude)&&Number.isFinite(n.longitude)&&(o.set("lat",n.latitude.toFixed(4)),o.set("lon",n.longitude.toFixed(4)));const{response:r,payload:s}=await Fi(e,`/api/opensky${o.size?"?"+o:""}`,{signal:i},"OpenSky");if(!r.ok)throw FU(r);return{...AU(s,{source:Ao(r,"x-flight-source")||"OpenSky Network",coverage:Ao(r,"x-flight-coverage")||"worldwide upstream snapshot",now:t()}),status:r.status}},async getTrack(n,{signal:i}={}){const{response:o,payload:r}=await Fi(e,"/api/opensky-track?icao24="+encodeURIComponent(n),{signal:i},"OpenSky");if(!o.ok)throw Si(o,"OpenSky");return{records:$E(r==null?void 0:r.path),complete:!1}},async getEnrichment(n,{signal:i}={}){if(!["type","route"].includes(n.kind))throw new $r("unsupported","Enrichment unavailable");const{response:o,payload:r}=await Fi(e,`/api/adsbdb/${n.kind}/${encodeURIComponent(n.id)}`,{signal:i},"adsbdb");if(!o.ok)throw Si(o,"adsbdb");return r}}}function NU({fetchImpl:e=jm,now:t=()=>Date.now()}={}){return{label:"adsb.lol",async getIdentities(n={},{signal:i}={}){const{response:o,payload:r}=await Fi(e,"/api/adsblol/mil",{signal:i},"adsb.lol");if(!o.ok)throw Si(o,"adsb.lol");return RU(r)},async getSnapshot(n={},{signal:i}={}){const{response:o,payload:r}=await Fi(e,"/api/adsblol/mil",{signal:i},"adsb.lol");if(!o.ok)throw Si(o,"adsb.lol");const s=Ye(Ao(o,"x-ads-b-cache-age-ms"));return{...IU(r,{observedAtMs:t()-(s!=null&&s>0?s:0),now:t(),stale:Ao(o,"x-ads-b-cache")==="STALE"}),status:o.status}},async getTrack(n,{signal:i}={}){const{response:o,payload:r}=await Fi(e,"/api/adsblol/trace?hex="+encodeURIComponent(n),{signal:i},"adsb.lol");if(!o.ok)throw Si(o,"adsb.lol");const s=Dn(r==null?void 0:r.timestamp,1e3);return{records:s==null?[]:$E(r==null?void 0:r.trace,{baseTimeMs:s,readsb:!0}),complete:!1}}}}function DU({fetchImpl:e=jm,apiUrl:t="/api/ais-live",origin:n=()=>{var i;return((i=globalThis.location)==null?void 0:i.origin)||"http://localhost"}}={}){return{label:"AISStream",async getSnapshot({maxRows:i=12e3}={},{signal:o}={}){const r=new URL(t,n());r.searchParams.set("maxRows",String(i));const{response:s,payload:a}=await Fi(e,r.toString(),{signal:o,cache:"no-store"},"AIS live");if(!s.ok){const c=Si(s,"AIS live"),l={"missing-key":"AISSTREAM_API_KEY not set","auth-failed":"API key rejected — check AISSTREAM_API_KEY",unsupported:"live feed unsupported",error:"feed down",closed:"feed disconnected"};throw c.message=l[a==null?void 0:a.status]||c.message,c}return{...PU(a),status:s.status}},async getTrack(i,{signal:o}={}){const{response:r,payload:s}=await Fi(e,"/api/ais-live/track?mmsi="+encodeURIComponent(i),{signal:o},"AIS live");if(!r.ok)throw Si(r,"AIS live");return{records:xU(s==null?void 0:s.samples),complete:!1}}}}const OU=new URL("/assets/cable-geo-i2PzBJi6.json",import.meta.url).href,BU=new URL("/assets/landing-point-geo-CiAWPhfe.json",import.meta.url).href;function VU({fetchImpl:e=(...t)=>fetch(...t)}={}){async function t(n,i){var s;i==null||i.throwIfAborted();const o=await e(n,{signal:i,cache:"force-cache"});if(!o.ok){try{await((s=o.body)==null?void 0:s.cancel())}catch{}throw new Error(`HTTP ${o.status} for ${n}`)}const r=await o.json();return i==null||i.throwIfAborted(),r}return{label:"TeleGeography",async fetch(n){const[i,o]=await Promise.all([t(OU,n),t(BU,n)]);return{cables:i,landingPoints:o}}}}function HU(){return{earthquakes:mG(),cables:VU()}}const dd={};function $U(){return{...HU(),flights:SU(),military:NU(),vessels:DU({apiUrl:(dd==null?void 0:dd.VITE_AIS_LIVE_API_URL)||"/api/ais-live"}),cctv:PS(),radio:YD(),traffic:y2(),bikeshare:W2(),installations:$V(),satellites:BH(),launches:w$(),alpr:W$(),firms:iG()}}const tr={};function GE({signal:e=new AbortController().signal,surface:t=zC({terrainSource:Ef().terrain,signal:e})}={}){return EU({surface:t,sources:$U(),signal:e,vesselOptions:{maxRows:tr==null?void 0:tr.VITE_AIS_LIVE_MAX_ROWS,maxLabels:tr==null?void 0:tr.VITE_AIS_LIVE_LABEL_MAX_ROWS}})}let GU;function UE(){return GU||(GU=GE())}const hd=["scene","controls","data","tools"],UU=["tools","controls","data","scene"];function zU({createScene:e,createControls:t,createData:n,createTools:i}){const o={scene:e,controls:t,data:n,tools:i};for(const _ of hd)if(typeof o[_]!="function")throw new TypeError(`Missing ${_} constructor`);const r=new AbortController,s=Object.fromEntries(hd.map(_=>[_,[]])),a={},c=new Set;let l=Object.freeze({status:"created",phase:null}),u,h,d;function f(_,m=null){l=Object.freeze({status:_,phase:m});for(const b of[...c])try{b(l)}catch{console.error("Application state listener failed")}}function p(){return d||(d=Promise.resolve().then(async()=>{const _=[];for(const m of UU){for(;s[m].length;)try{await s[m].pop()()}catch(b){_.push(b)}delete a[m]}if(_.length)throw new AggregateError(_,"Application cleanup failed")})),d}async function g(){try{for(const _ of hd){r.signal.throwIfAborted(),f("starting",_),r.signal.throwIfAborted();let m=!0;try{a[_]=await o[_]({...a,signal:r.signal,defer(b){if(!m||typeof b!="function")throw new TypeError("Register cleanup during component construction");s[_].push(b)}})}finally{m=!1}r.signal.throwIfAborted()}return f("ready"),r.signal.throwIfAborted(),Object.freeze({...a})}catch(_){r.abort();let m=_;try{await p()}catch(b){m=new AggregateError([_,b],"Application startup and cleanup failed")}throw h||f("failed"),m}}return Object.freeze({start(){return h?Promise.reject(new Error("Application has been destroyed")):(u||(u=Promise.resolve().then(g)),u)},destroy(){return h||(h=Promise.resolve().then(async()=>{try{await(u==null?void 0:u.catch(()=>{})),await p(),f("destroyed")}catch(_){throw f("failed"),_}finally{c.clear()}}),r.abort(),f("destroying"),h)},getState:()=>l,getComponents:()=>Object.freeze({...a}),subscribe(_){if(typeof _!="function")throw new TypeError("Expected a state listener");if(l.status==="destroyed")return()=>{};c.add(_);try{_(l)}catch{console.error("Application state listener failed")}return()=>c.delete(_)}})}function jU({requests:e,signal:t,eventTarget:n}){var r;for(const[s,a]of Object.entries({boundaries:"query",terrain:"getHeights",regional:"getBrief",weather:"getConditions",summary:"summarize"}))if(typeof((r=e==null?void 0:e[s])==null?void 0:r[a])!="function")throw new TypeError(`Missing application request service: ${s}`);const i=zC({terrainSource:e.terrain,signal:t,eventTarget:n}),o=$M({boundarySource:e.boundaries,signal:t});return Object.freeze({requests:e,surface:i,annotationResolver:o,searchAndFlyTo:(s,a,c={})=>wa(s,a,{...c,boundaries:e.boundaries,recoverNearView:o.placesNearViewRecovery})})}function qU({container:e,creditContainer:t}){if(!t)throw new TypeError("Viewer and credit containers are required");const n=new Cesium.Viewer(e,{timeline:!1,animation:!1,baseLayerPicker:!1,geocoder:!1,homeButton:!1,sceneModePicker:!1,navigationHelpButton:!1,fullscreenButton:!1,vrButton:!1,selectionIndicator:!1,infoBox:!1,baseLayer:!1,creditContainer:t,msaaSamples:4,contextOptions:{webgl:{preserveDrawingBuffer:!0}}});try{return n.targetFrameRate=60,n.scene.globe.show=!1,n.scene.skyAtmosphere.show=!0,n.scene.skyAtmosphere.atmosphereLightIntensity=18,n.scene.skyAtmosphere.saturationShift=-.12,n.scene.skyAtmosphere.brightnessShift=-.08,n}catch(i){throw n.destroy(),i}}function WU(e=document){var a,c,l,u;const t=(a=e==null?void 0:e.querySelector)==null?void 0:a.call(e,"#cesium-credits .cesium-credit-expand-link"),n=(c=e==null?void 0:e.querySelector)==null?void 0:c.call(e,".cesium-credit-lightbox"),i=(l=n==null?void 0:n.querySelector)==null?void 0:l.call(n,".cesium-credit-lightbox-close");if(!t||!n||!i)return!1;const o=n.parentElement;if(n.id||(n.id="cesium-credit-lightbox"),t.setAttribute("role","button"),t.setAttribute("tabindex","0"),t.setAttribute("aria-haspopup","dialog"),t.setAttribute("aria-controls",n.id),t.setAttribute("aria-expanded","false"),i.setAttribute("role","button"),i.setAttribute("tabindex","0"),i.setAttribute("aria-label","Close data attribution"),t.dataset.gevKeyboardReady==="true")return!0;t.dataset.gevKeyboardReady="true";const r=h=>{let d=!1;h.addEventListener("keydown",f=>{if(f.key==="Enter"){f.preventDefault(),f.repeat||h.click();return}f.key===" "&&(f.preventDefault(),f.repeat||(d=!0))}),h.addEventListener("keyup",f=>{f.key===" "&&(f.preventDefault(),d&&(d=!1,h.click()))}),h.addEventListener("blur",()=>{d=!1})},s=()=>{t.setAttribute("aria-expanded","false"),t.focus()};return r(t),r(i),n.addEventListener("keydown",h=>{h.key!=="Escape"||h.defaultPrevented||(h.preventDefault(),h.stopPropagation(),i.click())}),t.addEventListener("click",()=>{t.setAttribute("aria-expanded","true"),i.focus()}),i.addEventListener("click",s),(u=o==null?void 0:o.addEventListener)==null||u.call(o,"click",h=>{n.contains(h.target)||s()}),!0}function KU(e){var n,i;const t=new Map;for(const o of e){const r=(n=o==null?void 0:o.descriptor)==null?void 0:n.id;if(typeof r!="string"||!r||t.has(r))throw new TypeError("Map source IDs must be nonempty and unique");t.set(r,o)}for(const o of t.keys()){const r=new Set;let s=o;for(;s;){if(r.has(s))throw new TypeError("Map source fallback cycle");if(!t.has(s))throw new TypeError("Unknown map fallback source");r.add(s),s=(i=t.get(s).constructionFallback)==null?void 0:i.id}}return t}function YU(e){let t=null,n=null;return{show(i){var r,s;if(i===n)return;const o=(s=(r=e==null?void 0:e.scene)==null?void 0:r.frameState)==null?void 0:s.creditDisplay;if(o)try{t&&o.removeStaticCredit(t),t=i?new Cesium.Credit(i,!0):null,n=i,t&&o.addStaticCredit(t)}catch{}},destroy(){this.show(null)}}}class XU{constructor(t,{registry:n,initialStack:i,onChange:o=null,onError:r=null,requestRender:s=()=>{var c,l;return(l=(c=t==null?void 0:t.scene)==null?void 0:c.requestRender)==null?void 0:l.call(c)},createImageryLayer:a=c=>new Cesium.ImageryLayer(c)}){this.viewer=t,this._registry=n,this._sources=KU(n.sources),this._activeId=this.isStackAvailable(i)?i:n.defaultId,this._onChange=o,this._onError=r,this._requestRender=s,this._createImageryLayer=a,this._credits=YU(t),this._abort=new AbortController,this._imageryProviders=new Map,this._terrainProviders=new Map,this._tilesets=new Map,this._ownedTilesets=new Set,this._disposed=new WeakSet,this._switchGen=0,this._isSwitching=!1,this._lastError=null,this._imageryLayer=null,this._activeImageryProvider=null,this._removeImageryErrorListener=null,this._terrainMode=null,this._destroyed=!1}getStack(t){var n;return((n=this._sources.get(t))==null?void 0:n.descriptor)||null}getStacks(){return[...this._sources.values()].map(({descriptor:t})=>{const n=t,i=this.isStackAvailable(n.id);return{...n,available:i,unavailableReason:i?null:this._unavailableReason(n)}})}isStackAvailable(t){const n=this._sources.get(t);return!!(n&&n.available!==!1)}_unavailableReason(t){var n;return((n=this._sources.get(t==null?void 0:t.id))==null?void 0:n.unavailableReason)||`${(t==null?void 0:t.label)||"This map stack"} is unavailable`}getActiveId(){return this._activeId}getActiveStack(){return this.getStack(this._activeId)}getSwitchGeneration(){return this._switchGen}getState(t=this._isSwitching?"switching":"ready"){return{activeId:this._activeId,activeStack:this.getActiveStack(),stacks:this.getStacks(),status:t,lastError:this._lastError,...this._registry.state}}_emitChange(t){var n;(n=this._onChange)==null||n.call(this,this.getState(t))}async setStack(t,{silent:n=!1}={}){var r,s,a,c;if(this._destroyed)return this.getState();const i=this.getStack(t)||this.getStack(this._registry.unknownId);if(!i)return null;if(!this.isStackAvailable(i.id)){const l=this._unavailableReason(i);return this._lastError=l,(r=this._onError)==null||r.call(this,l,i),this.getState()}const o=++this._switchGen;this._isSwitching=!0,this._lastError=null,n||this._emitChange("switching");try{const l=await this._activate(i,o);if(o!==this._switchGen)return this.getState();this._activeId=(l==null?void 0:l.effectiveStackId)||i.id,l!=null&&l.fallbackMessage&&(this._lastError=l.fallbackMessage,(s=this._onError)==null||s.call(this,l.fallbackMessage,i)),this._requestRender("map-stack"),n||this._emitChange("ready")}catch(l){if(o!==this._switchGen)return this.getState();const u=(l==null?void 0:l.message)||String(l);this._lastError=u,(a=this._onError)==null||a.call(this,u,i);const h=this.getStack(this._registry.recoveryId);if(h&&h.id!==i.id&&this.isStackAvailable(h.id))try{const d=await this._activate(h,o);if(o!==this._switchGen)return this.getState();this._activeId=(d==null?void 0:d.effectiveStackId)||h.id}catch(d){if(o!==this._switchGen)return this.getState();this._lastError=(d==null?void 0:d.message)||String(d),(c=this._onError)==null||c.call(this,this._lastError,h)}n||this._emitChange("error")}finally{o===this._switchGen&&(this._isSwitching=!1)}return this.getState()}_activate(t,n){const i=this._sources.get(t.id);return i.imagery?this._activateGlobeStack(t,n):this._activateTileset(i,n)}async _activateTileset(t,n){let i=t.tileset;if(!i){if(!t.createTileset)throw new Error(`Missing 3D source: ${t.descriptor.id}`);i=await this._cached(this._tilesets,t.descriptor.id,()=>t.createTileset({signal:this._abort.signal}))}n===this._switchGen&&(!t.tileset&&!this._ownedTilesets.has(i)&&(i.show=!1,this.viewer.scene.primitives.add(i),this._ownedTilesets.add(i)),this._removeImageryLayer(),this._credits.show(t.credit||null),this._showTileset(i),this.viewer.scene.globe.show=!1)}_showTileset(t){for(const n of this._sources.values())n.tileset&&(n.tileset.show=n.tileset===t);for(const n of this._ownedTilesets)n.show=n===t}async _activateGlobeStack(t,n){const i=await this._getImageryProvider(t);if(n!==this._switchGen)return;this._removeImageryLayer(),this._imageryLayer=this._createImageryLayer(i.provider),this._activeImageryProvider=i.provider,this.viewer.imageryLayers.add(this._imageryLayer,0);const o=this._sources.get(i.effectiveStackId);if(this._credits.show((o==null?void 0:o.credit)||null),this._watchProvider(i,n),this._showTileset(null),this.viewer.scene.globe.show=!0,this._activeId=i.effectiveStackId,o!=null&&o.terrain&&o.terrain.id!==this._terrainMode){const r=o.terrain,s=await this._cached(this._terrainProviders,r.id,()=>r.create({signal:this._abort.signal}));if(n!==this._switchGen)return;s.terrain?this.viewer.scene.setTerrain(s.terrain):this.viewer.terrainProvider=s.provider,this._terrainMode=r.id}return i}_cached(t,n,i){if(t.has(n))return t.get(n);const o=Promise.resolve().then(()=>(this._abort.signal.throwIfAborted(),i())).catch(r=>{throw t.get(n)===o&&t.delete(n),r});return t.set(n,o),o}_getImageryProvider(t,n=new Set){return n.has(t.id)?Promise.reject(new Error("Map source fallback cycle")):this._cached(this._imageryProviders,t.id,async()=>{const i=this._sources.get(t.id);try{const o=await i.imagery({signal:this._abort.signal});return this._destroyed&&this._dispose(o),{provider:o,effectiveStackId:t.id,fallbackMessage:null}}catch(o){const r=i.constructionFallback;if(this._destroyed||!r||!this.isStackAvailable(r.id))throw o;const s=new Set(n).add(t.id);return{...await this._getImageryProvider(this.getStack(r.id),s),fallbackMessage:r.message}}})}_watchProvider(t,n){var a,c;const i=(a=this._sources.get(t.effectiveStackId))==null?void 0:a.tileFailureFallback,o=(c=t.provider)==null?void 0:c.errorEvent;if(!i||!(o!=null&&o.addEventListener))return;let r=0,s=!1;this._removeImageryErrorListener=o.addEventListener(l=>{var d;if(n!==this._switchGen||this._activeImageryProvider!==t.provider)return;const u=Number(l==null?void 0:l.timesRetried);if(r=Number.isInteger(u)&&u>=0?Math.max(r+1,u+1):r+1,r{!this._destroyed&&this._switchGen===h&&(f==null?void 0:f.activeId)===i.id&&(this._lastError=i.message,this._emitChange("error"))}).finally(()=>{s=!1})})}_removeImageryLayer(){var t;(t=this._removeImageryErrorListener)==null||t.call(this),this._removeImageryErrorListener=null,this._imageryLayer&&this.viewer.imageryLayers.remove(this._imageryLayer,!0),this._imageryLayer=null,this._activeImageryProvider=null}_dispose(t){var n;!t||this._disposed.has(t)||(this._disposed.add(t),typeof t.destroy=="function"&&!((n=t.isDestroyed)!=null&&n.call(t))&&t.destroy())}destroy(){if(!this._destroyed){this._destroyed=!0,this._switchGen++,this._abort.abort(),this._isSwitching=!1,this._removeImageryLayer(),this._credits.destroy();for(const t of this._imageryProviders.values())Promise.resolve(t).then(n=>this._dispose(n.provider),()=>{});for(const t of this._terrainProviders.values())Promise.resolve(t).then(n=>this._dispose(n.provider),()=>{});for(const t of this._ownedTilesets)this.viewer.scene.primitives.remove(t),this._dispose(t);for(const t of this._tilesets.values())Promise.resolve(t).then(n=>this._dispose(n),()=>{});this._imageryProviders.clear(),this._terrainProviders.clear(),this._tilesets.clear(),this._ownedTilesets.clear(),this._onChange=null,this._onError=null}}}const QU=[{id:"photoreal",label:"Google 3D",shortLabel:"3D",kind:"photoreal",requiresIon:!1},{id:"bing-aerial",label:"Bing Aerial",shortLabel:"Aerial",kind:"ion",style:Cesium.IonWorldImageryStyle.AERIAL,requiresIon:!0},{id:"bing-labels",label:"Bing Labels",shortLabel:"Labels",kind:"ion",style:Cesium.IonWorldImageryStyle.AERIAL_WITH_LABELS,requiresIon:!0},{id:"esri-imagery",label:"Esri Satellite",shortLabel:"SAT",kind:"esri-imagery",requiresIon:!1},{id:"osm",label:"OSM",shortLabel:"OSM",kind:"osm",requiresIon:!1}],ZU=Object.freeze([Object.freeze({id:"google-maps",title:"GOOGLE MAPS",unlocks:"The photorealistic 3D planet + place search",getUrl:"https://developers.google.com/maps/documentation/tile/get-api-key",envVars:Object.freeze(["GOOGLE_MAPS_API_KEY"]),tier:"metered",clientExposed:!0}),Object.freeze({id:"google-maps-server",title:"GOOGLE MAPS — SERVER",unlocks:"Places context + Street View fallback; optional separate key",getUrl:"https://developers.google.com/maps/documentation/places/web-service/get-api-key",envVars:Object.freeze(["GOOGLE_MAPS_SERVER_API_KEY"]),tier:"metered",hidden:!0}),Object.freeze({id:"openai",title:"OPENAI",unlocks:"Voice control — talk to the planet",getUrl:"https://platform.openai.com/api-keys",envVars:Object.freeze(["OPENAI_API_KEY"]),tier:"metered"}),Object.freeze({id:"aisstream",title:"AISSTREAM",unlocks:"Live ships, worldwide",getUrl:"https://aisstream.io",envVars:Object.freeze(["AISSTREAM_API_KEY"]),tier:"free"}),Object.freeze({id:"firms",title:"NASA FIRMS",unlocks:"Live active-fire detections",getUrl:"https://firms.modaps.eosdis.nasa.gov/api/map_key/",envVars:Object.freeze(["FIRMS_MAP_KEY"]),tier:"free"}),Object.freeze({id:"tomtom",title:"TOMTOM",unlocks:"Real live traffic (keyless runs a simulation)",getUrl:"https://developer.tomtom.com",envVars:Object.freeze(["TOMTOM_API_KEY"]),tier:"free"}),Object.freeze({id:"cesium-ion",title:"CESIUM ION",unlocks:"Bing imagery map stacks + world terrain",getUrl:"https://ion.cesium.com/tokens",envVars:Object.freeze(["CESIUM_ION_TOKEN"]),tier:"free",clientExposed:!0}),Object.freeze({id:"opensky",title:"OPENSKY",unlocks:"More flight-polling credits (anonymous works without)",getUrl:"https://opensky-network.org",envVars:Object.freeze(["OPENSKY_CLIENT_ID","OPENSKY_CLIENT_SECRET"]),tier:"free"}),Object.freeze({id:"launch-library",title:"LAUNCH LIBRARY",unlocks:"Higher space-missions request allowance",getUrl:"https://thespacedevs.com",envVars:Object.freeze(["LL2_API_TOKEN"]),tier:"free"})]);function lu(e){const t=ZU.find(n=>n.id===e);return!t||t.hidden?"":`Needs ${t.envVars.join(" + ")} — add it in Provider Settings`}function JU(e){return e?"Google 3D tiles unavailable — check the key's API restrictions, quota, or network":`${lu("google-maps")} — or a Cesium ion token for the ion-hosted route`}const ez='Powered by Esri';function tz(){return new Cesium.OpenStreetMapImageryProvider({url:"https://tile.openstreetmap.org/",credit:"© OpenStreetMap contributors"})}function nz(){return Cesium.ArcGisMapServerImageryProvider.fromUrl("https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer",{credit:"Powered by Esri — Source: Esri, Maxar, Earthstar Geographics, and the GIS User Community",enablePickFeatures:!1})}function iz(e,t){if(t=String(t||"").trim(),!t)throw new Error("Ion imagery requires an explicit token");return Cesium.IonImageryProvider.fromAssetId(e,{accessToken:t})}async function oz(e,{signal:t}={}){if(e=String(e||"").trim(),!e)throw new Error("World terrain requires an explicit ion token");t==null||t.throwIfAborted();const n=await Cesium.IonResource.fromAssetId(1,{accessToken:e});return t==null||t.throwIfAborted(),{provider:await Cesium.CesiumTerrainProvider.fromUrl(n,{requestVertexNormals:!0,requestWaterMask:!1,ellipsoid:Cesium.Ellipsoid.WGS84})}}async function rz(){try{return{provider:await Cesium.CesiumTerrainProvider.fromUrl("https://terrain.reearth.land/cesium-mesh/ellipsoid")}}catch(e){return console.warn("[MapStack] Re:Earth terrain unavailable, falling back to flat ellipsoid terrain:",e),{provider:new Cesium.EllipsoidTerrainProvider}}}function sz({googleTileset:e=null,cesiumToken:t="",googleApiKey:n=""}={}){const i=String(t||"").trim(),o=!!i,r=!!String(n||"").trim(),s={id:o?"world":"keyless",create:o?a=>oz(i,a):rz};return{defaultId:e?"photoreal":"esri-imagery",unknownId:"photoreal",recoveryId:e?"photoreal":null,state:{hasCesiumIonToken:o},sources:QU.map(a=>{const c={descriptor:a,available:!a.requiresIon||o,unavailableReason:a.requiresIon?lu("cesium-ion"):null};if(a.kind==="photoreal")return{...c,available:!!e,unavailableReason:JU(o||r),tileset:e};const l=a.kind==="ion"?()=>iz(a.style,i):a.id==="osm"?tz:nz;return{...c,imagery:l,terrain:s,...a.id==="esri-imagery"?{credit:ez,constructionFallback:{id:"osm",message:"Esri Satellite is unavailable; using OSM"},tileFailureFallback:{id:"osm",threshold:2,message:"Esri Satellite tile requests failed; using OSM"}}:{}}})}}class az extends XU{constructor(t,n={}){const i=typeof window<"u"?window.__GOOGLE_MAPS_API_KEY__:"",o=sz({...n,googleApiKey:i});super(t,{registry:o,initialStack:n.googleTileset?n.initialStack||"photoreal":o.defaultId,...n,requestRender:qt}),this.googleTileset=n.googleTileset||null,this.cesiumToken=String(n.cesiumToken||"").trim()}_hasPhotorealCredentials(){const t=typeof window<"u"?window.__GOOGLE_MAPS_API_KEY__:"";return!!String(t||"").trim()||!!String(this.cesiumToken||"").trim()}}const yc=e=>String(e||"").trim();async function lz(e,{googleApiKey:t="",cesiumToken:n=""}={}){const i=yc(t),o=yc(n),r=[],s=[];i&&s.push({route:"google-direct",googleKey:i}),o&&s.push({route:"google-ion",googleKey:void 0});for(const a of s)try{return{tileset:a.googleKey?await cz(e,a.googleKey):await uz(e,o),route:a.route,errors:r}}catch(c){r.push(c instanceof Error?c:new Error(String(c)))}return{tileset:null,route:"osm",errors:r}}function cz(e,t){if(t=yc(t),!t)throw new Error("Google 3D requires an explicit browser key");return e.createGooglePhotorealistic3DTileset({key:t,onlyUsingWithGoogleGeocoder:!0})}async function uz(e,t,{signal:n}={}){if(t=yc(t),!t)throw new Error("Google 3D through ion requires an explicit token");n==null||n.throwIfAborted();const i=await e.IonResource.fromAssetId(2275207,{accessToken:t});return n==null||n.throwIfAborted(),e.Cesium3DTileset.fromUrl(i,{cacheBytes:1536*1024*1024,maximumCacheOverflowBytes:1024*1024*1024,enableCollision:!0})}const dz=34,hz=320,c0=.2,u0=.08;function fz(e,t,n,i=dz){if(![e,t,n==null?void 0:n.left,n==null?void 0:n.top,n==null?void 0:n.width,n==null?void 0:n.height,i].every(Number.isFinite)||n.width<=0||n.height<=0||i<0)return{x:0,y:0};const r=e-(n.left+n.width/2),s=t-(n.top+n.height/2),a=Math.hypot(r,s);if(a===0)return{x:0,y:0};const c=Math.min(a/hz,1),l=i*c/a;return{x:r*l,y:s*l}}function mz(e=document){var d;if(typeof window>"u"||!(e!=null&&e.querySelectorAll))return()=>{};const t=[...e.querySelectorAll("[data-logo-gaze]")];if(!t.length)return()=>{};const n=(d=window.matchMedia)==null?void 0:d.call(window,"(prefers-reduced-motion: reduce)").matches,i=t.map(f=>({element:f,parts:[],currentX:0,currentY:0,targetX:0,targetY:0}));let o=0,r=!1;const s=f=>{const p=`translate(${f.currentX.toFixed(2)} ${f.currentY.toFixed(2)})`;for(const g of f.parts)g.setAttribute("transform",p)},a=()=>{o=0;let f=!1;for(const p of i){const g=p.targetX-p.currentX,_=p.targetY-p.currentY;Math.abs(g)<=u0&&Math.abs(_)<=u0?(p.currentX=p.targetX,p.currentY=p.targetY):(p.currentX+=g*c0,p.currentY+=_*c0,f=!0),s(p)}f&&(o=window.requestAnimationFrame(a))},c=()=>{o||(o=window.requestAnimationFrame(a))};n||(async()=>{var f;try{const p=t[0].dataset.logoSrc||"/logo.svg",g=await window.fetch(p);if(!g.ok)return;const _=await g.text();if(r)return;const m=new DOMParser().parseFromString(_,"image/svg+xml");if(m.querySelector("parsererror"))return;const b=m.documentElement;for(const C of i){const y=b.cloneNode(!0);y.removeAttribute("role"),y.removeAttribute("aria-labelledby"),y.setAttribute("aria-hidden","true"),y.setAttribute("focusable","false"),(f=y.querySelector("title"))==null||f.remove(),C.element.replaceChildren(y),C.parts=[y.querySelector("#globe"),y.querySelector("#globe_cage")].filter(Boolean),s(C)}}catch{}})();const u=f=>{if(!(n||f.pointerType==="touch")){for(const p of i){const g=fz(f.clientX,f.clientY,p.element.getBoundingClientRect());p.targetX=g.x,p.targetY=g.y}c()}},h=()=>{for(const f of i)f.targetX=0,f.targetY=0;c()};return window.addEventListener("pointermove",u,{passive:!0}),window.addEventListener("blur",h),document.documentElement.addEventListener("pointerleave",h),()=>{r=!0,window.removeEventListener("pointermove",u),window.removeEventListener("blur",h),document.documentElement.removeEventListener("pointerleave",h),o&&window.cancelAnimationFrame(o)}}function zE(e){if(!e)return"Unknown initialization error";if(e instanceof Error)return e.message&&e.message.trim()?e.message.trim():e.name||"Initialization error";if(typeof e=="string"&&e.trim())return e.trim();if(typeof e=="object"){const t=String(e.message||e.error||"").trim();if(t)return t;try{const n=JSON.stringify(e);if(n&&n!=="{}")return n}catch{}}return String(e)}async function pz({requestServices:e,googleApiKey:t,cesiumToken:n,credits:i,MapController:o=az,mapOptions:r={},loaderStatus:s,signal:a,defer:c}){const l=jU({requests:e,signal:a});c(mz());const u=window.__GOOGLE_MAPS_API_KEY__;t&&(window.__GOOGLE_MAPS_API_KEY__=t,c(()=>{window.__GOOGLE_MAPS_API_KEY__===t&&(u===void 0?delete window.__GOOGLE_MAPS_API_KEY__:window.__GOOGLE_MAPS_API_KEY__=u)})),s.textContent="Configuring viewer...";const h=document.createElement("div");h.id="cesium-credits",document.body.appendChild(h),c(()=>h.remove());const d=qU({container:"cesiumContainer",creditContainer:h});c(()=>{Yy(d),d.isDestroyed()||d.destroy()}),HM(d,i),WU(document),s.textContent=t||n?"Loading Google 3D Tiles...":"Loading the keyless globe...";const f=await lz(Cesium,{googleApiKey:t,cesiumToken:n}),p=f.tileset;if(c(()=>{p&&!p.isDestroyed()&&(d.scene.primitives.remove(p)||p.destroy())}),a.throwIfAborted(),p)d.scene.primitives.add(p),d.scene.globe.show=!1,console.info(`[Init] Google 3D Tiles loaded via ${f.route}.`);else{if(f.errors.length){const _=f.errors.at(-1);console.warn("[Init] Google 3D Tiles unavailable, using the keyless globe:",_);const m=zE(_);s.textContent=`Google 3D Tiles unavailable (${m}). Loading the keyless globe...`}d.scene.globe.show=!0}s.textContent="Initializing systems...";const g=new o(d,{requestRender:qt,...r,googleTileset:p,cesiumToken:n,initialStack:p?"photoreal":"esri-imagery",onChange:_=>{window.dispatchEvent(new CustomEvent("gev:map-stack-changed",{detail:_}))},onError:_=>console.warn("[MapStack]",_)});return c(()=>g.destroy()),await g.setStack(p?"photoreal":"esri-imagery",{silent:!0}),a.throwIfAborted(),{viewer:d,tileset:p,mapStackController:g,operations:l}}function gz(e){return pz({requestServices:Ef(),...e})}const _z={name:"retro",uniforms:{pixelation:{default:5,min:1,max:10,label:"Pixelation"},distortion:{default:0,min:0,max:1,label:"Distortion"},instability:{default:.4,min:0,max:1,label:"Instability"}},fragmentShader:` + uniform sampler2D colorTexture; + uniform vec2 colorTextureDimensions; + uniform float intensity; + uniform float pixelation; + uniform float distortion; + uniform float instability; + uniform float time; + in vec2 v_textureCoordinates; + + // ── Hash for noise/randomness ────────────���──────────── + float hash(vec2 p) { + vec3 p3 = fract(vec3(p.xyx) * 0.1031); + p3 += dot(p3, p3.yzx + 33.33); + return fract((p3.x + p3.y) * p3.z); + } + + // 8x8 Bayer dithering matrix (normalized 0-1) + float bayer8(vec2 pos) { + ivec2 p = ivec2(mod(pos, 8.0)); + int index = p.x + p.y * 8; + int bayer[64] = int[64]( + 0, 32, 8, 40, 2, 34, 10, 42, + 48, 16, 56, 24, 50, 18, 58, 26, + 12, 44, 4, 36, 14, 46, 6, 38, + 60, 28, 52, 20, 62, 30, 54, 22, + 3, 35, 11, 43, 1, 33, 9, 41, + 51, 19, 59, 27, 49, 17, 57, 25, + 15, 47, 7, 39, 13, 45, 5, 37, + 63, 31, 55, 23, 61, 29, 53, 21 + ); + return float(bayer[index]) / 64.0; + } + + // CRT barrel distortion + vec2 barrelDistort(vec2 uv, float strength) { + vec2 centered = uv * 2.0 - 1.0; + float r2 = dot(centered, centered); + float distort = 1.0 + r2 * strength * 0.4; + centered *= distort; + return centered * 0.5 + 0.5; + } + + void main() { + vec2 uv = v_textureCoordinates; + vec2 dims = colorTextureDimensions; + vec2 texel = 1.0 / dims; + + // ── Barrel distortion (CRT monitor bulge) ─────────── + float dist = distortion * intensity; + vec2 distUV = barrelDistort(uv, dist); + + // Black outside the distorted area + if (distUV.x < 0.0 || distUV.x > 1.0 || distUV.y < 0.0 || distUV.y > 1.0) { + out_FragColor = vec4(0.0, 0.0, 0.0, 1.0); + return; + } + + // ── Horizontal jitter (random scanline displacement) ── + float lineY = floor(distUV.y * dims.y); + float jitterSeed = hash(vec2(lineY, floor(time * 8.0))); + // Only jitter a few lines at a time (sparse) + float jitterActive = step(0.97 - instability * 0.04, jitterSeed); + float jitterAmount = (hash(vec2(lineY * 7.0, floor(time * 12.0))) - 0.5) * + 0.008 * instability * jitterActive * intensity; + vec2 jitteredUV = distUV + vec2(jitterAmount, 0.0); + + // ── Chromatic aberration — slight RGB channel offset ── + vec2 centered = jitteredUV - 0.5; + float caStrength = length(centered) * 0.008 * intensity; + float r = texture(colorTexture, jitteredUV + centered * caStrength).r; + float g = texture(colorTexture, jitteredUV).g; + float b = texture(colorTexture, jitteredUV - centered * caStrength).b; + vec4 color = vec4(r, g, b, 1.0); + + // ── Pixelation: snap UV to grid ───────────────────── + float pixSize = mix(1.0, pixelation, intensity); + vec2 pixelUV = floor(jitteredUV * dims / pixSize) * pixSize / dims; + vec4 pixelColor = texture(colorTexture, mix(jitteredUV, pixelUV, intensity)); + + // Blend chromatic aberration with pixelated sample + color = mix(color, pixelColor, 0.7 * intensity); + + // ── Bayer dithering before posterization ──────────── + vec2 ditherCoord = jitteredUV * dims / pixSize; + float dither = bayer8(ditherCoord) - 0.5; + float ditherAmount = 0.12 * intensity; + vec3 dithered = color.rgb + dither * ditherAmount; + + // ── Posterize: reduce color levels ────────────────── + float levels = mix(256.0, 10.0, intensity); + vec3 posterized = floor(dithered * levels + 0.5) / levels; + + // ── Slight saturation boost ───────────────────────── + float gray = dot(posterized, vec3(0.299, 0.587, 0.114)); + vec3 saturated = mix(vec3(gray), posterized, 1.0 + 0.3 * intensity); + + // ── RGB shadow mask subpixel pattern ──────────────── + // Each pixel shows faint R/G/B vertical stripes + float subpixelX = mod(distUV.x * dims.x, 3.0); + vec3 subpixelMask = vec3( + smoothstep(0.0, 0.8, 1.0 - abs(subpixelX - 0.5)), // R stripe + smoothstep(0.0, 0.8, 1.0 - abs(subpixelX - 1.5)), // G stripe + smoothstep(0.0, 0.8, 1.0 - abs(subpixelX - 2.5)) // B stripe + ); + // Only apply at higher pixelation (visible "pixels") + float subpixelStrength = smoothstep(2.0, 6.0, pixSize) * 0.3 * intensity; + vec3 withSubpixels = mix(saturated, saturated * (subpixelMask * 0.7 + 0.3), subpixelStrength); + + // ── Block edge darkening ──────────────────────────── + vec2 pixelCenter = fract(distUV * dims / pixSize); + float blockEdge = smoothstep(0.0, 0.08, min(min(pixelCenter.x, 1.0 - pixelCenter.x), + min(pixelCenter.y, 1.0 - pixelCenter.y))); + float edgeFactor = mix(1.0, blockEdge * 0.15 + 0.85, intensity); + + vec3 result = withSubpixels * edgeFactor; + + // ── Horizontal scanlines — rolling CRT refresh ────── + float scanY = distUV.y * dims.y; + float scanline = sin(scanY * 1.0 + time * 2.5) * 0.5 + 0.5; + scanline = pow(scanline, 1.5); + float scanFade = 0.35 * intensity; + result *= mix(1.0, scanline * scanFade + (1.0 - scanFade), intensity); + + // ── Phosphor persistence / ghosting ───────────────── + // Approximate by blurring in a direction (simulates previous frame lingering) + vec3 ghost = texture(colorTexture, jitteredUV - vec2(texel.x * 2.0, 0.0)).rgb; + float ghostGray = dot(ghost, vec3(0.299, 0.587, 0.114)); + // Blend a dim ghost of the offset sample + result = mix(result, result + vec3(ghostGray) * 0.08, instability * intensity); + + // ── Flicker (overall brightness fluctuation ~50-60Hz) ── + float flicker = sin(time * 188.5) * 0.5 + 0.5; // ~60Hz equivalent + flicker = 1.0 - flicker * 0.03 * instability * intensity; // very subtle + result *= flicker; + + // ── Glitch lines (rare horizontal bright bars) ────── + float glitchSeed = hash(vec2(floor(time * 2.0), 0.0)); + float glitchLine = step(0.92 - instability * 0.08, glitchSeed); + if (glitchLine > 0.0) { + float glitchY = hash(vec2(floor(time * 2.0), 1.0)); + float glitchHit = smoothstep(0.0, 0.003, abs(distUV.y - glitchY)); + glitchHit = 1.0 - glitchHit; + result += glitchHit * 0.3 * instability * intensity; + } + + // ── Warm phosphor tint (P1 green-amber) ───────────── + vec3 warmTint = result * vec3(1.02, 1.0, 0.94); + result = mix(result, warmTint, 0.4 * intensity); + + // ── Edge vignette (darker corners — CRT curvature) ── + vec2 vigUV = distUV * (1.0 - distUV); + float vig = vigUV.x * vigUV.y * 20.0; + vig = clamp(pow(vig, 0.25 + 0.15 * intensity), 0.0, 1.0); + result *= mix(1.0, vig, 0.6 * intensity); + + out_FragColor = vec4(mix(texture(colorTexture, uv).rgb, result, intensity), 1.0); + } + `},bz={name:"anime",uniforms:{saturation:{default:1,min:0,max:2,label:"Saturation"},edgeThick:{default:.5,min:0,max:1,label:"Edge Thickness"}},fragmentShader:` + uniform sampler2D colorTexture; + uniform vec2 colorTextureDimensions; + uniform float intensity; + uniform float saturation; + uniform float edgeThick; + in vec2 v_textureCoordinates; + + vec3 rgb2hsv(vec3 c) { + vec4 K = vec4(0.0, -1.0/3.0, 2.0/3.0, -1.0); + vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g)); + vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r)); + float d = q.x - min(q.w, q.y); + float e = 1.0e-10; + return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); + } + + vec3 hsv2rgb(vec3 c) { + vec4 K = vec4(1.0, 2.0/3.0, 1.0/3.0, 3.0); + vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www); + return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y); + } + + void main() { + vec2 uv = v_textureCoordinates; + vec2 texel = 1.0 / colorTextureDimensions; + vec4 color = texture(colorTexture, uv); + + // Cel-shade: quantize luminance into bands + float luma = dot(color.rgb, vec3(0.299, 0.587, 0.114)); + float bands = mix(256.0, 4.0, intensity); + float celLuma = floor(luma * bands + 0.5) / bands; + float lumaScale = (luma > 0.001) ? celLuma / luma : 1.0; + vec3 celColor = color.rgb * lumaScale; + + // Boost saturation for vibrant anime look (driven by saturation uniform) + vec3 hsv = rgb2hsv(celColor); + hsv.y = min(hsv.y * (1.0 + 0.6 * intensity * saturation), 1.0); + hsv.z = min(hsv.z * (1.0 + 0.1 * intensity), 1.0); + vec3 saturated = hsv2rgb(hsv); + + // Soft edge detection for outlines + vec4 left = texture(colorTexture, uv + vec2(-texel.x, 0.0)); + vec4 right = texture(colorTexture, uv + vec2( texel.x, 0.0)); + vec4 up = texture(colorTexture, uv + vec2(0.0, texel.y)); + vec4 down = texture(colorTexture, uv + vec2(0.0, -texel.y)); + + float edgeH = length(right.rgb - left.rgb); + float edgeV = length(up.rgb - down.rgb); + float edge = sqrt(edgeH * edgeH + edgeV * edgeV); + float outline = 1.0 - smoothstep(0.05, mix(0.35, 0.1, edgeThick), edge) * 0.6 * intensity; + + // Warm color shift (Ghibli palette tends warm) + vec3 warmShift = saturated * vec3(1.02, 1.0, 0.95); + + vec3 result = warmShift * outline; + out_FragColor = vec4(mix(color.rgb, result, intensity), color.a); + } + `},Cz={name:"noir",uniforms:{contrastAmt:{default:1.2,min:0,max:2,label:"Contrast"},grainAmt:{default:.5,min:0,max:1,label:"Grain"},vignetteAmt:{default:.5,min:0,max:1,label:"Vignette"}},fragmentShader:` + uniform sampler2D colorTexture; + uniform vec2 colorTextureDimensions; + uniform float intensity; + uniform float contrastAmt; + uniform float grainAmt; + uniform float vignetteAmt; + in vec2 v_textureCoordinates; + + void main() { + vec2 uv = v_textureCoordinates; + vec4 color = texture(colorTexture, uv); + + // Desaturate + float luma = dot(color.rgb, vec3(0.299, 0.587, 0.114)); + vec3 gray = vec3(luma); + vec3 desaturated = mix(color.rgb, gray, intensity); + + // High contrast with S-curve (driven by contrastAmt uniform) + float contrast = 1.0 + contrastAmt * intensity; + vec3 contrasted = (desaturated - 0.5) * contrast + 0.5; + contrasted = clamp(contrasted, 0.0, 1.0); + + // Film grain (driven by grainAmt uniform) + float grain = fract(sin(dot(uv * colorTextureDimensions, vec2(12.9898, 78.233))) * 43758.5453); + grain = (grain - 0.5) * 0.08 * grainAmt * intensity; + contrasted += grain; + + // Vignette (driven by vignetteAmt uniform) + vec2 vigUV = uv * (1.0 - uv); + float vig = vigUV.x * vigUV.y * 16.0; + vig = pow(vig, 0.3 + 0.4 * vignetteAmt * intensity); + + // Slight sepia tint for warmth + vec3 sepia = vec3( + dot(contrasted, vec3(0.393, 0.769, 0.189)), + dot(contrasted, vec3(0.349, 0.686, 0.168)), + dot(contrasted, vec3(0.272, 0.534, 0.131)) + ); + vec3 tinted = mix(contrasted, sepia, 0.15 * intensity); + + vec3 result = tinted * vig; + out_FragColor = vec4(mix(color.rgb, result, intensity), color.a); + } + `},yz={name:"snow",uniforms:{density:{default:.6,min:0,max:1,label:"Density"},wind:{default:.5,min:0,max:1,label:"Wind"}},fragmentShader:` + uniform sampler2D colorTexture; + uniform vec2 colorTextureDimensions; + uniform float intensity; + uniform float time; + uniform float density; + uniform float wind; + in vec2 v_textureCoordinates; + + // Hash function for pseudo-random snow + float hash(vec2 p) { + p = fract(p * vec2(123.34, 456.21)); + p += dot(p, p + 45.32); + return fract(p.x * p.y); + } + + // Layered snow particles + float snowLayer(vec2 uv, float layer) { + float depth = 0.5 + layer * 0.5; + float speed = 0.4 + layer * 0.3; + float size = mix(0.01, 0.025, layer); + float windForce = sin(time * 0.5 + layer * 3.14) * (0.05 + wind * 0.2); + + vec2 snowUV = uv * vec2(1.0, 0.5) * (4.0 + layer * 4.0); + snowUV.y += time * speed; + snowUV.x += time * windForce; + + vec2 cell = floor(snowUV); + vec2 f = fract(snowUV); + + float snow = 0.0; + // Check neighboring cells for smooth particles + for (int y = -1; y <= 1; y++) { + for (int x = -1; x <= 1; x++) { + vec2 neighbor = vec2(float(x), float(y)); + vec2 point = vec2(hash(cell + neighbor), hash(cell + neighbor + 100.0)); + // Animate particle position slightly + point = 0.5 + 0.4 * sin(time * 0.3 + 6.2831 * point); + float d = length(f - neighbor - point); + snow += smoothstep(size, 0.0, d) * depth; + } + } + return snow; + } + + void main() { + vec2 uv = v_textureCoordinates; + vec4 color = texture(colorTexture, uv); + + // Cool/blue color shift + vec3 cool = color.rgb * vec3(0.85, 0.9, 1.1); + + // Desaturate partially + float luma = dot(cool, vec3(0.299, 0.587, 0.114)); + vec3 desaturated = mix(cool, vec3(luma), 0.4 * intensity); + + // Brighten (snow coverage lightens everything) + vec3 brightened = mix(desaturated, vec3(1.0), 0.15 * intensity); + + // Add white frost overlay on brighter areas + float frostMask = smoothstep(0.3, 0.8, luma); + vec3 frosted = mix(brightened, vec3(0.95, 0.97, 1.0), frostMask * 0.25 * intensity); + + // Accumulate snow particle layers (density controls amount) + float snow = 0.0; + snow += snowLayer(uv, 0.0) * 0.5; + snow += snowLayer(uv, 0.25) * 0.6; + snow += snowLayer(uv, 0.5) * 0.7; + snow += snowLayer(uv, 0.75) * 0.8; + snow += snowLayer(uv, 1.0) * 1.0; + snow = clamp(snow * (0.4 + density * 1.2), 0.0, 1.0); + + // Composite snow particles + vec3 result = frosted + snow * 0.8 * intensity; + + // Subtle fog in lower areas + float fog = smoothstep(0.0, 0.4, 1.0 - uv.y) * 0.1 * intensity; + result = mix(result, vec3(0.85, 0.88, 0.95), fog); + + out_FragColor = vec4(mix(color.rgb, result, intensity), color.a); + } + `},vz={name:"surveillance",uniforms:{gain:{default:.55,min:0,max:1,label:"Gain"},bloom:{default:.3,min:0,max:1,label:"Bloom"},scanlineStr:{default:1,min:0,max:1,label:"Scanlines"},pixelation:{default:2.5,min:1,max:6,label:"Pixelation"}},fragmentShader:` + uniform sampler2D colorTexture; + uniform vec2 colorTextureDimensions; + uniform float intensity; + uniform float time; + uniform float gain; + uniform float bloom; + uniform float scanlineStr; + uniform float pixelation; + in vec2 v_textureCoordinates; + + // ── Noise functions ─────────────────────────────────── + float hash(vec2 p) { + vec3 p3 = fract(vec3(p.xyx) * 0.1031); + p3 += dot(p3, p3.yzx + 33.33); + return fract((p3.x + p3.y) * p3.z); + } + + float valueNoise(vec2 p) { + vec2 i = floor(p); + vec2 f = fract(p); + f = f * f * (3.0 - 2.0 * f); + float a = hash(i); + float b = hash(i + vec2(1.0, 0.0)); + float c = hash(i + vec2(0.0, 1.0)); + float d = hash(i + vec2(1.0, 1.0)); + return mix(mix(a, b, f.x), mix(c, d, f.x), f.y); + } + + // ── Barrel distortion (NVG lens) ────────────────────── + vec2 barrelDistort(vec2 uv, float strength) { + vec2 c = uv * 2.0 - 1.0; + float r2 = dot(c, c); + float distort = 1.0 + r2 * strength * 0.5 + r2 * r2 * strength * 0.15; + c *= distort; + return c * 0.5 + 0.5; + } + + // ── Honeycomb pattern (fiber optic plate texture) ───── + float honeycomb(vec2 uv) { + vec2 dims = colorTextureDimensions; + float scale = min(dims.x, dims.y) * 0.008; + vec2 p = uv * dims * scale; + // Hex grid + vec2 r = vec2(1.0, 1.732); + vec2 h = r * 0.5; + vec2 a = mod(p, r) - h; + vec2 b = mod(p - h, r) - h; + vec2 gv = dot(a, a) < dot(b, b) ? a : b; + float d = max(abs(gv.x), abs(gv.y * 0.577 + abs(gv.x) * 0.5)); + return smoothstep(0.4, 0.45, d); + } + + // ── 7-segment digit renderer ────────────────────────── + float segment(vec2 p, int seg) { + float s = 0.0; + if (seg == 0) s = step(0.2, p.x) * step(p.x, 0.8) * step(0.85, p.y) * step(p.y, 1.0); + if (seg == 1) s = step(0.7, p.x) * step(p.x, 0.9) * step(0.5, p.y) * step(p.y, 0.95); + if (seg == 2) s = step(0.7, p.x) * step(p.x, 0.9) * step(0.05, p.y) * step(p.y, 0.5); + if (seg == 3) s = step(0.2, p.x) * step(p.x, 0.8) * step(0.0, p.y) * step(p.y, 0.15); + if (seg == 4) s = step(0.1, p.x) * step(p.x, 0.3) * step(0.05, p.y) * step(p.y, 0.5); + if (seg == 5) s = step(0.1, p.x) * step(p.x, 0.3) * step(0.5, p.y) * step(p.y, 0.95); + if (seg == 6) s = step(0.2, p.x) * step(p.x, 0.8) * step(0.42, p.y) * step(p.y, 0.58); + return s; + } + + float digit(vec2 p, int d) { + int masks[10] = int[10](0x7E, 0x30, 0x6D, 0x79, 0x33, 0x5B, 0x5F, 0x70, 0x7F, 0x7B); + int m = masks[d]; + float s = 0.0; + for (int i = 0; i < 7; i++) { + if ((m >> (6 - i) & 1) == 1) s += segment(p, i); + } + return clamp(s, 0.0, 1.0); + } + + // Render HH:MM:SS timestamp + float renderTimestamp(vec2 uv) { + vec2 tsOrigin = vec2(0.02, 0.03); + vec2 tsSize = vec2(0.22, 0.035); + vec2 p = (uv - tsOrigin) / tsSize; + if (p.x < 0.0 || p.x > 1.0 || p.y < 0.0 || p.y > 1.0) return 0.0; + + int totalSec = int(mod(time, 86400.0)); + int hours = totalSec / 3600; + int minutes = (totalSec % 3600) / 60; + int seconds = totalSec % 60; + + float charWidth = 1.0 / 8.5; + int charIdx = int(p.x / charWidth); + float localX = mod(p.x, charWidth) / charWidth; + vec2 localP = vec2(localX, p.y); + + int dv = -1; + if (charIdx == 0) dv = hours / 10; + else if (charIdx == 1) dv = hours % 10; + else if (charIdx == 2) return (step(0.3, localP.x) * step(localP.x, 0.7)) * + (step(0.2, localP.y) * step(localP.y, 0.4) + step(0.6, localP.y) * step(localP.y, 0.8)); + else if (charIdx == 3) dv = minutes / 10; + else if (charIdx == 4) dv = minutes % 10; + else if (charIdx == 5) return (step(0.3, localP.x) * step(localP.x, 0.7)) * + (step(0.2, localP.y) * step(localP.y, 0.4) + step(0.6, localP.y) * step(localP.y, 0.8)); + else if (charIdx == 6) dv = seconds / 10; + else if (charIdx == 7) dv = seconds % 10; + + if (dv < 0 || dv > 9) return 0.0; + return digit(localP, dv); + } + + // ── Crosshair (thin, subtle NVG reticle) ────────────── + float crosshair(vec2 uv) { + vec2 c = uv - 0.5; + float h = smoothstep(0.001, 0.0004, abs(c.y)) * + step(0.01, abs(c.x)) * step(abs(c.x), 0.025); + float v = smoothstep(0.001, 0.0004, abs(c.x)) * + step(0.01, abs(c.y)) * step(abs(c.y), 0.025); + return clamp(h + v, 0.0, 1.0); + } + + void main() { + vec2 uv = v_textureCoordinates; + vec2 dims = colorTextureDimensions; + vec2 texel = 1.0 / dims; + + // ── Barrel distortion (NVG lens distortion) ───────── + float dist = 0.5 * intensity; + vec2 distUV = barrelDistort(uv, dist); + + // ── Circular vignette mask (NVG tube field of view) ── + vec2 centered = uv * 2.0 - 1.0; + float aspect = dims.x / dims.y; + centered.x *= aspect; + float radius = length(centered); + float tubeMask = pow(1.0 - smoothstep(0.6, 1.05, radius), 0.7); + // Tube brightness falloff (center brightest) + float tubeShading = 1.0 - radius * radius * 0.3; + tubeShading = max(tubeShading, 0.0); + + // If outside tube, render black + if (tubeMask < 0.001) { + out_FragColor = vec4(vec3(0.0), 1.0); + return; + } + + // Black outside distorted area + if (distUV.x < 0.0 || distUV.x > 1.0 || distUV.y < 0.0 || distUV.y > 1.0) { + out_FragColor = vec4(vec3(0.0), 1.0); + return; + } + + // ── Intensifier tube resolution pixelation ──────────── + float pixSize = mix(1.0, pixelation, intensity); + vec2 snappedUV = floor(distUV * dims / pixSize) * pixSize / dims; + distUV = mix(distUV, snappedUV, intensity); + + vec4 original = texture(colorTexture, distUV); + + // ── Luminance ─────────────────────────────────────── + float luma = dot(original.rgb, vec3(0.299, 0.587, 0.114)); + + // ── Auto-gain response ────────────────────────────── + // Higher gain = more amplification, more noise, more bloom + float gainLevel = mix(0.8, 2.5, gain); + float amplified = clamp(luma * gainLevel, 0.0, 1.0); + + // Slight contrast curve for gain response + amplified = pow(amplified, mix(1.2, 0.7, gain)); + + // ── Intensifier tube bloom (THE key NVG visual) ───── + // Bloom around bright sources — wider kernel for realistic halos + float bloomAccum = 0.0; + float bloomW = 0.0; + for (int y = -5; y <= 5; y++) { + for (int x = -5; x <= 5; x++) { + vec2 offset = vec2(float(x), float(y)) * texel * 4.0; + float sLuma = dot(texture(colorTexture, distUV + offset).rgb, vec3(0.299, 0.587, 0.114)); + float bright = smoothstep(0.4, 0.9, sLuma * gainLevel); + float w = exp(-float(x * x + y * y) / 18.0); + bloomAccum += bright * w; + bloomW += w; + } + } + bloomAccum /= bloomW; + + // Edge glow / corona on bright objects + float corona = bloomAccum * bloom * 1.5; + + // ── P43 phosphor green (530nm) ────────────────────── + vec3 phosphor = vec3(0.16, 1.0, 0.22); + vec3 nvgColor = phosphor * (amplified + corona); + + // ── Scintillation (image intensifier sparkle noise) ── + // Base tube grain (slow, coherent) + vec2 grainCoord = uv * 120.0 + vec2(time * 0.5, time * 0.3); + float tubeGrain = valueNoise(grainCoord); + tubeGrain = (tubeGrain - 0.5) * mix(0.06, 0.2, gain) * intensity; + nvgColor += phosphor * tubeGrain; + + // More noise in dark areas (real gain response) + float darkNoise = (1.0 - amplified) * hash(uv * dims + vec2(time * 200.0, time * 300.0)); + nvgColor += phosphor * darkNoise * 0.08 * gain * intensity; + + // ── Honeycomb fiber optic plate ───────────────────── + float hc = honeycomb(distUV); + nvgColor *= 1.0 - hc * 0.04 * intensity; // very subtle + + // ── Scanlines (subtle, from the display) ──────────── + float scanline = sin(distUV.y * dims.y * 1.2 + time * 2.0) * 0.5 + 0.5; + scanline = pow(scanline, 2.5); + nvgColor *= 1.0 - scanline * scanlineStr * 0.15 * intensity; + + // ── Tube shading (brightness falloff from center) ─── + nvgColor *= tubeShading; + + // ── Circular vignette (dark edges, NVG tube shape) ── + nvgColor *= tubeMask; + + // ── HUD Overlay ───────────────────────────────────── + + // Top-left: "NVG" / "I²" label marker + vec2 labelArea = (uv - vec2(0.03, 0.92)) / vec2(0.06, 0.03); + if (labelArea.x >= 0.0 && labelArea.x <= 1.0 && labelArea.y >= 0.0 && labelArea.y <= 1.0) { + float lbl = step(0.1, labelArea.x) * step(labelArea.x, 0.9) * + step(0.2, labelArea.y) * step(labelArea.y, 0.8); + nvgColor += phosphor * lbl * 0.3 * intensity; + } + + // Gain indicator below label: "AUTO" marker + vec2 gainArea = (uv - vec2(0.03, 0.88)) / vec2(0.05, 0.025); + if (gainArea.x >= 0.0 && gainArea.x <= 1.0 && gainArea.y >= 0.0 && gainArea.y <= 1.0) { + float gLbl = step(0.1, gainArea.x) * step(gainArea.x, 0.9) * + step(0.2, gainArea.y) * step(gainArea.y, 0.8); + nvgColor += phosphor * gLbl * 0.2 * intensity; + } + + // Center crosshair (thin, subtle) + float ch = crosshair(uv); + nvgColor += phosphor * ch * 0.4 * intensity; + + // Bottom-left: Timestamp (7-segment) + float ts = renderTimestamp(uv); + nvgColor += phosphor * ts * 0.6 * intensity; + + // REC indicator — top-right (blinking) + vec2 recPos = uv - vec2(0.95, 0.94); + float recDot = smoothstep(0.008, 0.004, length(recPos)); + float blink = step(0.5, fract(time * 0.8)); + // REC dot in slightly warmer green + nvgColor += vec3(0.3, 1.0, 0.2) * recDot * blink * intensity; + + // ── Final composite ───────────────────────���───────── + nvgColor = clamp(nvgColor, 0.0, 1.0); + + // Keep NVG output fully tube-masked at full intensity to avoid color bleed at the lens edge. + vec3 finalColor = mix(original.rgb, nvgColor * tubeMask, intensity); + + out_FragColor = vec4(finalColor, 1.0); + } + `},Mz={name:"thermal",uniforms:{sensitivity:{default:.75,min:0,max:1,label:"Sensitivity"},bloom:{default:.65,min:0,max:1,label:"Bloom"},mode:{default:0,min:0,max:1,label:"WHOT/BHOT"},pixelation:{default:1.5,min:1,max:6,label:"Pixelation"},palette:{default:0,min:0,max:1,label:"Ironbow"}},fragmentShader:` + uniform sampler2D colorTexture; + uniform vec2 colorTextureDimensions; + uniform float intensity; + uniform float time; + uniform float sensitivity; + uniform float bloom; + uniform float mode; + uniform float pixelation; + uniform float palette; + in vec2 v_textureCoordinates; + + // ── Ironbow "Predator" thermal palette ──────────────── + // Maps a 0-1 temperature to the classic FLIR ironbow ramp: + // black -> deep purple -> magenta -> red -> orange -> yellow -> white. + vec3 ironbow(float t) { + t = clamp(t, 0.0, 1.0); + const vec3 c0 = vec3(0.0, 0.0, 0.0); // cold + const vec3 c1 = vec3(0.13, 0.0, 0.30); // deep purple + const vec3 c2 = vec3(0.49, 0.0, 0.45); // magenta + const vec3 c3 = vec3(0.86, 0.10, 0.18); // red + const vec3 c4 = vec3(1.0, 0.55, 0.0); // orange + const vec3 c5 = vec3(1.0, 0.91, 0.32); // yellow + const vec3 c6 = vec3(1.0, 1.0, 1.0); // hot (white) + float s = t * 6.0; + if (s < 1.0) return mix(c0, c1, s); + if (s < 2.0) return mix(c1, c2, s - 1.0); + if (s < 3.0) return mix(c2, c3, s - 2.0); + if (s < 4.0) return mix(c3, c4, s - 3.0); + if (s < 5.0) return mix(c4, c5, s - 4.0); + return mix(c5, c6, s - 5.0); + } + + // ── Value noise (coherent, smooth, drifting) ────────── + float hash(vec2 p) { + vec3 p3 = fract(vec3(p.xyx) * 0.1031); + p3 += dot(p3, p3.yzx + 33.33); + return fract((p3.x + p3.y) * p3.z); + } + + float valueNoise(vec2 p) { + vec2 i = floor(p); + vec2 f = fract(p); + f = f * f * (3.0 - 2.0 * f); // smoothstep interpolation + float a = hash(i); + float b = hash(i + vec2(1.0, 0.0)); + float c = hash(i + vec2(0.0, 1.0)); + float d = hash(i + vec2(1.0, 1.0)); + return mix(mix(a, b, f.x), mix(c, d, f.x), f.y); + } + + // Fractal Brownian motion for layered coherent noise + float fbm(vec2 p) { + float v = 0.0; + float a = 0.5; + vec2 shift = vec2(100.0); + for (int i = 0; i < 4; i++) { + v += a * valueNoise(p); + p = p * 2.0 + shift; + a *= 0.5; + } + return v; + } + + // ── 7-segment digit renderer ────────────────────────── + float segment(vec2 p, int seg) { + float s = 0.0; + if (seg == 0) s = step(0.2, p.x) * step(p.x, 0.8) * step(0.85, p.y) * step(p.y, 1.0); + if (seg == 1) s = step(0.7, p.x) * step(p.x, 0.9) * step(0.5, p.y) * step(p.y, 0.95); + if (seg == 2) s = step(0.7, p.x) * step(p.x, 0.9) * step(0.05, p.y) * step(p.y, 0.5); + if (seg == 3) s = step(0.2, p.x) * step(p.x, 0.8) * step(0.0, p.y) * step(p.y, 0.15); + if (seg == 4) s = step(0.1, p.x) * step(p.x, 0.3) * step(0.05, p.y) * step(p.y, 0.5); + if (seg == 5) s = step(0.1, p.x) * step(p.x, 0.3) * step(0.5, p.y) * step(p.y, 0.95); + if (seg == 6) s = step(0.2, p.x) * step(p.x, 0.8) * step(0.42, p.y) * step(p.y, 0.58); + return s; + } + + float digit(vec2 p, int d) { + int masks[10] = int[10](0x7E, 0x30, 0x6D, 0x79, 0x33, 0x5B, 0x5F, 0x70, 0x7F, 0x7B); + int m = masks[d]; + float s = 0.0; + for (int i = 0; i < 7; i++) { + if ((m >> (6 - i) & 1) == 1) s += segment(p, i); + } + return clamp(s, 0.0, 1.0); + } + + // Render a character (digit, '.', or '°') at position + float renderChar(vec2 p, int ch) { + if (ch == 10) { // '.' decimal point + return smoothstep(0.15, 0.0, length(p - vec2(0.5, 0.08))); + } + if (ch == 11) { // '°' degree symbol + float ring = abs(length(p - vec2(0.5, 0.82)) - 0.08); + return smoothstep(0.04, 0.02, ring); + } + if (ch >= 0 && ch <= 9) return digit(p, ch); + return 0.0; + } + + // ── Crosshair ───────────────────────────────────────── + float crosshair(vec2 uv) { + vec2 c = uv - 0.5; + float h = smoothstep(0.0015, 0.0005, abs(c.y)) * + step(0.015, abs(c.x)) * step(abs(c.x), 0.04); + float v = smoothstep(0.0015, 0.0005, abs(c.x)) * + step(0.015, abs(c.y)) * step(abs(c.y), 0.04); + return clamp(h + v, 0.0, 1.0); + } + + // ── Scale bar (right edge) ──────────────────────────── + float scaleBar(vec2 uv) { + // Vertical bar on right edge + float barX = step(0.94, uv.x) * step(uv.x, 0.955); + float barY = step(0.15, uv.y) * step(uv.y, 0.85); + return barX * barY; + } + + void main() { + vec2 uv = v_textureCoordinates; + vec2 dims = colorTextureDimensions; + vec2 texel = 1.0 / dims; + vec2 hudUV = uv; // preserve original UV for HUD overlay + + // ── Circular vignette mask (FLIR optics field of view) ── + vec2 centered = uv * 2.0 - 1.0; + float aspect = dims.x / dims.y; + centered.x *= aspect; + float radius = length(centered); + float lensMask = pow(1.0 - smoothstep(0.6, 1.05, radius), 0.7); + // Tube brightness falloff (center brightest) + float lensShading = 1.0 - radius * radius * 0.25; + lensShading = max(lensShading, 0.0); + + // If outside lens, render black + if (lensMask < 0.001) { + out_FragColor = vec4(vec3(0.0), 1.0); + return; + } + + // ── Sensor resolution pixelation (authentic FLIR resolution limits) ── + float pixSize = mix(1.0, pixelation, intensity); + vec2 snappedUV = floor(uv * dims / pixSize) * pixSize / dims; + uv = mix(uv, snappedUV, intensity); + + // ── Soft IR blur (thermal cameras have lower resolution / diffraction) ── + vec3 blurred = vec3(0.0); + float totalWeight = 0.0; + for (int y = -2; y <= 2; y++) { + for (int x = -2; x <= 2; x++) { + float w = exp(-0.5 * float(x * x + y * y) / 2.0); + blurred += texture(colorTexture, uv + vec2(float(x), float(y)) * texel * 1.5).rgb * w; + totalWeight += w; + } + } + blurred /= totalWeight; + vec4 original = texture(colorTexture, uv); + + // Mix between sharp and blurred based on intensity + vec3 src = mix(original.rgb, blurred, 0.6 * intensity); + + // ── Luminance → temperature mapping ───────────────── + float luma = dot(src, vec3(0.299, 0.587, 0.114)); + + // Sensitivity remaps the luminance range + float sens = mix(0.25, 1.0, sensitivity); + float temp = clamp((luma - (0.5 - sens * 0.5)) / sens, 0.0, 1.0); + + // ── Temperature banding (contour lines) ───────────── + float bands = 12.0; + float bandLine = abs(fract(temp * bands) - 0.5); + float contour = smoothstep(0.04, 0.06, bandLine); + temp *= mix(1.0, contour * 0.85 + 0.15, 0.3 * intensity); + + // ── White-Hot / Black-Hot mode ────────────────────── + float isBlackHot = step(0.5, mode); + float thermal = mix(temp, 1.0 - temp, isBlackHot); + + // Monochrome FLIR (white/black-hot) vs Ironbow "Predator" color ramp. + // Ironbow maps TRUE temperature (cold->dark, hot->white) so the colors + // read correctly regardless of the WHOT/BHOT toggle. + vec3 mono = vec3(thermal); + vec3 iron = ironbow(temp); + vec3 thermalColor = mix(mono, iron, palette); + + // ── Hot-spot bloom/bleed ──────────────────────────── + // Sample a wider area for bloom on bright spots + float bloomSample = 0.0; + float bloomWeight = 0.0; + for (int y = -4; y <= 4; y++) { + for (int x = -4; x <= 4; x++) { + vec2 offset = vec2(float(x), float(y)) * texel * 3.0; + float sLuma = dot(texture(colorTexture, uv + offset).rgb, vec3(0.299, 0.587, 0.114)); + float sMapped = clamp((sLuma - (0.5 - sens * 0.5)) / sens, 0.0, 1.0); + float sFinal = mix(sMapped, 1.0 - sMapped, isBlackHot); + float w = exp(-0.5 * float(x * x + y * y) / 8.0); + // Only bloom the "hot" pixels (bright in WHOT, dark values in BHOT... + // but since we already inverted, just bloom high values) + float hotness = smoothstep(0.6, 1.0, sFinal); + bloomSample += hotness * w; + bloomWeight += w; + } + } + bloomSample /= bloomWeight; + thermalColor += bloomSample * bloom * 0.8; + + // ── Coherent temporal noise (slowly drifting, cloud-like) ── + vec2 noiseCoord = uv * 80.0 + vec2(time * 0.3, time * 0.2); + float noise = fbm(noiseCoord); + noise = (noise - 0.5) * 0.08 * intensity; + thermalColor += noise; + + // ── Subtle motion blur feel (slight blur) ─────────── + // Already handled by the initial IR blur above + + // ── HUD Overlay ───────────────────────────────────── + float hud = 0.0; + + // Top-left: "FLIR" label + mode indicator + // Rendered as simple box presence markers (not full text rendering) + // We'll use a simplified approach: render mode text near top-left + vec2 labelArea = (hudUV - vec2(0.02, 0.92)) / vec2(0.08, 0.04); + if (labelArea.x >= 0.0 && labelArea.x <= 1.0 && labelArea.y >= 0.0 && labelArea.y <= 1.0) { + // Simple horizontal bar as "FLIR" label marker + hud += step(0.1, labelArea.x) * step(labelArea.x, 0.9) * + step(0.3, labelArea.y) * step(labelArea.y, 0.7) * 0.6; + } + + // Mode indicator below label + vec2 modeArea = (hudUV - vec2(0.02, 0.88)) / vec2(0.06, 0.03); + if (modeArea.x >= 0.0 && modeArea.x <= 1.0 && modeArea.y >= 0.0 && modeArea.y <= 1.0) { + hud += step(0.1, modeArea.x) * step(modeArea.x, 0.9) * + step(0.2, modeArea.y) * step(modeArea.y, 0.8) * 0.4; + } + + // Center crosshair + hud += crosshair(hudUV) * 0.7; + + // Top-right: simulated temperature readout (derived from center luminance) + float centerLuma = dot(texture(colorTexture, vec2(0.5)).rgb, vec3(0.299, 0.587, 0.114)); + float tempC = 20.0 + centerLuma * 30.0; // 20°C to 50°C range + int tempInt = int(tempC); + int tempDec = int(fract(tempC) * 10.0); + + // Temperature digits at top-right + float tempHud = 0.0; + vec2 tempOrigin = vec2(0.88, 0.92); + vec2 charSize = vec2(0.018, 0.035); + float spacing = 0.02; + + // Tens digit + vec2 d1p = (hudUV - tempOrigin) / charSize; + if (d1p.x >= 0.0 && d1p.x <= 1.0 && d1p.y >= 0.0 && d1p.y <= 1.0) { + tempHud += renderChar(d1p, tempInt / 10); + } + // Ones digit + vec2 d2p = (hudUV - (tempOrigin + vec2(spacing, 0.0))) / charSize; + if (d2p.x >= 0.0 && d2p.x <= 1.0 && d2p.y >= 0.0 && d2p.y <= 1.0) { + tempHud += renderChar(d2p, tempInt % 10); + } + // Decimal point + vec2 dpp = (hudUV - (tempOrigin + vec2(spacing * 2.0, 0.0))) / charSize; + if (dpp.x >= 0.0 && dpp.x <= 1.0 && dpp.y >= 0.0 && dpp.y <= 1.0) { + tempHud += renderChar(dpp, 10); // '.' + } + // Decimal digit + vec2 d3p = (hudUV - (tempOrigin + vec2(spacing * 2.6, 0.0))) / charSize; + if (d3p.x >= 0.0 && d3p.x <= 1.0 && d3p.y >= 0.0 && d3p.y <= 1.0) { + tempHud += renderChar(d3p, tempDec); + } + // Degree symbol + vec2 dgp = (hudUV - (tempOrigin + vec2(spacing * 3.5, 0.0))) / charSize; + if (dgp.x >= 0.0 && dgp.x <= 1.0 && dgp.y >= 0.0 && dgp.y <= 1.0) { + tempHud += renderChar(dgp, 11); // '°' + } + hud += tempHud * 0.8; + + // Bottom-right: frame counter + int frame = int(mod(time * 30.0, 10000.0)); + float framHud = 0.0; + vec2 fOrigin = vec2(0.88, 0.04); + for (int i = 0; i < 4; i++) { + int dv = (frame / int(pow(10.0, float(3 - i)))) % 10; + vec2 fp = (hudUV - (fOrigin + vec2(float(i) * spacing, 0.0))) / charSize; + if (fp.x >= 0.0 && fp.x <= 1.0 && fp.y >= 0.0 && fp.y <= 1.0) { + framHud += renderChar(fp, dv); + } + } + hud += framHud * 0.5; + + // Scale bar (right edge gradient) + float bar = scaleBar(hudUV); + if (bar > 0.0) { + float barGrad = (hudUV.y - 0.15) / 0.7; // 0 at bottom, 1 at top + float barVal = mix(barGrad, 1.0 - barGrad, isBlackHot); + thermalColor = mix(thermalColor, vec3(barVal), bar * 0.9); + } + + // Composite HUD (rendered in white, slightly transparent) + float hudBright = mix(1.0, 0.0, isBlackHot); // HUD is white in WHOT, dark in BHOT inverted + // Actually, HUD should always be visible — use contrast + thermalColor += hud * 0.6 * intensity; + + // ── Lens shading + vignette ─────────────────── + thermalColor *= lensShading; + thermalColor *= lensMask; + + // Clamp final + thermalColor = clamp(thermalColor, 0.0, 1.0); + + // Blend with original based on intensity, then fade to black at lens edges + vec3 finalColor = mix(original.rgb, thermalColor, intensity); + finalColor *= mix(1.0, lensMask, intensity); + + out_FragColor = vec4(finalColor, 1.0); + } + `},ti=2,jE=200,oi=0,Jh=100;function qE(e,t,n){return Math.max(t,Math.min(n,e))}function Ni(e){const t=Number(e);return Number.isFinite(t)?qE(Math.round(t),0,jE):oi}function wz(e){const t=qE(Math.round(Number(e)||0),0,Jh);return Ni((Jh-t)*2)}function ca(e,t=1){const n=Number(e);if(!Number.isFinite(n))return oi;const i=Number(t);return Number.isFinite(i)&&i>=ti||n>Jh?Ni(n):wz(n)}function d0(e){return Ni(e)/jE}const Ez=500,Ir={retro:_z,surveillance:vz,thermal:Mz,anime:bz,noir:Cz,snow:yz},Rr=Object.freeze({mode:"dense",densityPct:75}),Tz={bloom:{enabled:!1,intensity:oi},sharpen:{enabled:!0,intensity:49},hudVariant:"tactical",detectionMode:Rr.mode.toUpperCase(),detectionDensity:Rr.densityPct,detectionAllocation:"ELASTIC",detectionFadePct:7,detectionOutsideOpacityPct:1,celestialRing:!1},h0={retro:{bloom:{enabled:!1,intensity:oi},sharpen:{enabled:!0,intensity:49},styleParams:{retro:{pixelation:1,distortion:0,instability:.42}},hudVariant:"tactical",hudVisible:!0,detection:Rr},surveillance:{bloom:{enabled:!1,intensity:oi},sharpen:{enabled:!0,intensity:49},styleParams:{surveillance:{gain:.18,bloom:.22,scanlineStr:.96,pixelation:1}},hudVariant:"tactical",hudVisible:!0,detection:Rr},thermal:{bloom:{enabled:!1,intensity:oi},sharpen:{enabled:!0,intensity:49},styleParams:{thermal:{sensitivity:.85,bloom:.2,mode:.33,pixelation:1}},hudVariant:"tactical",hudVisible:!0,detection:Rr}},kz=` + uniform sampler2D colorTexture; + uniform vec2 colorTextureDimensions; + uniform float amount; + in vec2 v_textureCoordinates; + + void main() { + vec2 uv = v_textureCoordinates; + vec2 texel = 1.0 / colorTextureDimensions; + vec4 center = texture(colorTexture, uv); + vec4 blur = ( + texture(colorTexture, uv + vec2(-texel.x, -texel.y)) + + texture(colorTexture, uv + vec2( 0.0, -texel.y)) + + texture(colorTexture, uv + vec2( texel.x, -texel.y)) + + texture(colorTexture, uv + vec2(-texel.x, 0.0)) + + center + + texture(colorTexture, uv + vec2( texel.x, 0.0)) + + texture(colorTexture, uv + vec2(-texel.x, texel.y)) + + texture(colorTexture, uv + vec2( 0.0, texel.y)) + + texture(colorTexture, uv + vec2( texel.x, texel.y)) + ) / 9.0; + vec4 sharpened = center + (center - blur) * amount; + out_FragColor = vec4(clamp(sharpened.rgb, 0.0, 1.0), center.a); + } +`,WE={normal:"NORMAL",retro:"CRT",surveillance:"NVG",thermal:"FLIR",anime:"ANIME",noir:"NOIR",snow:"SNOW"};class cu{constructor(){this.destroyed=!1,this.removers=new Set,this.frames=new Set,this.timers=new Set}listen(t,n,i,o){if(this.destroyed||!t)return()=>{};const r=()=>{t.removeEventListener(n,s,o),this.removers.delete(r)},s=a=>{if(o!=null&&o.once&&r(),!this.destroyed)return i(a)};return t.addEventListener(n,s,o),this.removers.add(r),r}frame(t){if(this.destroyed)return null;const n=requestAnimationFrame(i=>{this.frames.delete(n),this.destroyed||t(i)});return this.frames.add(n),n}timeout(t,n){if(this.destroyed)return null;const i=setTimeout(()=>{this.timers.delete(i),this.destroyed||t()},n);return this.timers.add(i),i}cancelTimeout(t){clearTimeout(t),this.timers.delete(t)}destroy(){if(!this.destroyed){this.destroyed=!0;for(const t of this.removers)t();for(const t of this.frames)cancelAnimationFrame(t);for(const t of this.timers)clearTimeout(t);this.frames.clear(),this.timers.clear()}}}const Az="v6",f0="v8",m0=100,Iz=139;class Rz{constructor({syncPanelCollapseButton:t,layoutRightPanels:n,syncCctvPanelViewport:i,showToast:o}){this._syncPanelCollapseButton=t,this._layoutRightPanels=n,this._syncCctvPanelViewport=i,this._showToast=o,this._ppToggles=document.getElementById("pp-toggles"),this._panelZCounter=m0+10,this._draggableResizeObserver=null,this._cancelDrag=null,this.removers=[],this.destroyed=!1}listen(t,n,i){if(this.destroyed||!t)return;const o=r=>{this.destroyed||i(r)};t.addEventListener(n,o),this.removers.push(()=>t.removeEventListener(n,o))}_reclampDraggablePanels(){if(this.destroyed)return;const t=this._ppToggles;if(!t||!t.style.top||t.style.top==="auto")return;const n=parseInt(t.style.top,10);Number.isFinite(n)&&(t.style.top=`${this._clampToViewport(0,n,t).top}px`,this._pinPanelToRight(t))}_maybeNotifyLayoutReset(){try{const t=`godsEyeView.${f0}.layoutResetNotified`;if(localStorage.getItem(t))return;localStorage.setItem(t,"1"),Object.keys(localStorage).some(i=>i.startsWith("godsEyeView.v6.panelPos."))&&this._showToast("Panel layout updated — positions reset to new defaults")}catch{}}_initPanelDrag(){var n;if(this.destroyed)return;const t=[{id:"pp-toggles",panel:this._ppToggles,handle:(n=this._ppToggles)==null?void 0:n.querySelector(".panel-drag-handle.compact")}].filter(Boolean);for(const i of t)!i.panel||!i.handle||(this._restorePanelPosition(i.id,i.panel),this._makePanelDraggable(i.id,i.panel,i.handle));this._ppToggles&&typeof ResizeObserver<"u"&&(this._draggableResizeObserver=new ResizeObserver(()=>this._reclampDraggablePanels()),this._draggableResizeObserver.observe(this._ppToggles))}_panelStorageKey(t){return`godsEyeView.${f0}.panelPos.${t}`}_panelCollapseStorageKey(t){return`godsEyeView.${Az}.panelCollapsed.${t}`}_restorePanelCollapsedState(t,{allowStored:n=!0}={}){const i=document.getElementById(t);if(!i)return;let o=i.classList.contains("collapsed"),r=null;if(n)try{r=localStorage.getItem(this._panelCollapseStorageKey(t)),r==="1"&&(o=!0),r==="0"&&(o=!1)}catch{}t==="pp-toggles"&&r===null&&(o=!0),i.classList.toggle("collapsed",o),this._syncPanelCollapseButton(i)}_savePanelCollapsedState(t,n){try{localStorage.setItem(this._panelCollapseStorageKey(t),n?"1":"0")}catch{}}_pinPanelToRight(t){if(!t)return;const n=t.getBoundingClientRect(),i=Math.max(6,Math.round(window.innerWidth-n.right));t.style.right=`${i}px`,t.style.left="auto"}_restorePanelPosition(t,n){try{const i=localStorage.getItem(this._panelStorageKey(t));if(!i)return;const o=JSON.parse(i);if(!o||typeof o.left!="number"||typeof o.top!="number")return;const{left:r,top:s}=this._clampToViewport(Math.round(o.left),Math.round(o.top),n);n.style.left=`${r}px`,n.style.top=`${s}px`,n.style.right="auto",n.style.bottom="auto",t==="pp-toggles"&&this._pinPanelToRight(n)}catch{}}_clampToViewport(t,n,i){const o=i.getBoundingClientRect(),r=Math.max(6,window.innerWidth-o.width-6),s=Math.max(6,window.innerHeight-o.height-6);return{left:Math.max(6,Math.min(r,t)),top:Math.max(6,Math.min(s,n))}}_savePanelPosition(t,n){const i=n.getBoundingClientRect();try{localStorage.setItem(this._panelStorageKey(t),JSON.stringify({left:Math.round(i.left),top:Math.round(i.top)}))}catch{}}_promotePanelZ(t){if(this._panelZCounter+=1,this._panelZCounter>Iz){const n=[...document.querySelectorAll(".panel-draggable")].filter(o=>o.style.zIndex).sort((o,r)=>Number(o.style.zIndex)-Number(r.style.zIndex));let i=m0+1;for(const o of n)o.style.zIndex=String(i),i+=1;this._panelZCounter=i}t.style.zIndex=String(this._panelZCounter)}_makePanelDraggable(t,n,i){this.listen(n,"pointerdown",()=>{this._promotePanelZ(n)}),this.listen(i,"pointerdown",o=>{var f;if(o.button!==0||o.target.closest(".panel-collapse-btn")||o.target.closest("input, select, option, button:not(.panel-collapse-btn)"))return;(f=this._cancelDrag)==null||f.call(this),o.preventDefault();const r=n.getBoundingClientRect(),s=o.clientX,a=o.clientY,c=s-r.left,l=a-r.top;n.style.left=`${r.left}px`,n.style.top=`${r.top}px`,n.style.right="auto",n.style.bottom="auto",n.classList.add("panel-dragging"),this._promotePanelZ(n);const u=p=>{const g=p.clientX-c,_=p.clientY-l,m=Math.max(6,window.innerWidth-r.width-6),b=Math.max(6,window.innerHeight-r.height-6),C=Math.max(6,Math.min(m,g)),y=Math.max(6,Math.min(b,_));n.style.left=`${C}px`,n.style.top=`${y}px`,t==="pp-toggles"&&this._layoutRightPanels(),t==="cctv-panel"&&this._syncCctvPanelViewport()},h=()=>{n.classList.remove("panel-dragging"),window.removeEventListener("pointermove",u),window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",d),this._cancelDrag=null},d=()=>{h(),t==="pp-toggles"&&this._pinPanelToRight(n),this._savePanelPosition(t,n),t==="cctv-panel"&&this._syncCctvPanelViewport()};this._cancelDrag=h,window.addEventListener("pointermove",u),window.addEventListener("pointerup",d),window.addEventListener("pointercancel",d)})}destroy(){var t,n;if(!this.destroyed){this.destroyed=!0,(t=this._cancelDrag)==null||t.call(this);for(const i of this.removers.splice(0))i();(n=this._draggableResizeObserver)==null||n.disconnect(),this._draggableResizeObserver=null}}}function KE({naturalHeights:e,availableHeight:t,minimumHeight:n=96}){const i=e.map(d=>Math.max(0,Number(d)||0));if(!i.length)return[];const o=Math.max(0,Number(t)||0);if(i.reduce((d,f)=>d+f,0)<=o)return i;if(o===0)return i.map(()=>0);const s=Math.max(0,Number(n)||0),a=i.map(d=>Math.min(d,s)),c=a.reduce((d,f)=>d+f,0);if(c>=o){const d=c>0?o/c:0;return a.map(f=>f*d)}const l=o-c,u=i.map((d,f)=>Math.max(0,d-a[f])),h=u.reduce((d,f)=>d+f,0);return h<=0?a:a.map((d,f)=>d+l*(u[f]/h))}function Lz({baseBottom:e,obstacles:t=[],safeGap:n=0}){let i=Number(e)||0;const o=Number(n)||0;for(const r of t){const s=Number(r==null?void 0:r.top);Number.isFinite(s)&&(i=Math.min(i,s-o))}return i}function YE({naturalHeights:e,allocatedHeights:t,minimumVisibleRatio:n=.5,collapseLaterPanels:i=!1}){const o=Math.max(0,Number(n)||0),r=[];for(let s=1;s0&&c/ad){const f=Math.min(d-l,u-d),p=d-f,g=d+f;g-p>=h&&(l=p,u=g)}return u-l!l.classList.contains("panel-glow"));if(!n)return Math.ceil(e.scrollHeight||e.getBoundingClientRect().height);const i=n.getBoundingClientRect(),o=t(e),r=t(n),s=parseFloat(r.paddingBottom)||0;let a=parseFloat(r.paddingTop)||0;for(const l of n.children){const u=t(l);if(u.display==="none"||u.visibility==="hidden")continue;const h=l.getBoundingClientRect(),d=parseFloat(u.marginBottom)||0,f=Math.max(h.height,l.scrollHeight||0),p=h.top-i.top+f+d;a=Math.max(a,p)}const c=(parseFloat(o.borderTopWidth)||0)+(parseFloat(o.borderBottomWidth)||0)+(parseFloat(o.paddingTop)||0)+(parseFloat(o.paddingBottom)||0);return Math.ceil(a+s+c)}function Fz({stack:e,obstacles:t,windowRef:n,hud:i,preferredPanelId:o,onCollapse:r,onRetry:s,collapsedHeights:a,onAligned:c,getComputedStyle:l=u=>n.getComputedStyle(u)}){if(!e)return;const u=[...e.querySelectorAll(":scope > [data-panel-id]")];if(!u.length)return;if(!i.visible||i.variant!=="tactical")for(const Z of u.filter(ae=>ae.classList.contains("layout-auto-collapsed")))Z.classList.remove("collapsed","layout-auto-collapsed"),r(Z);if(n.matchMedia("(max-width: 720px)").matches){e.classList.remove("layout-focus"),e.classList.remove("layout-tail"),e.style.removeProperty("--left-stack-safe-top"),e.style.removeProperty("--left-stack-safe-bottom"),e.style.removeProperty("--left-stack-centered-height"),e.dataset.layoutMode="mobile";for(const Z of u)Z.removeAttribute("aria-hidden"),Z.style.removeProperty("--left-panel-allocated-height");return}const h=Math.max(1,n.innerHeight),d=e.getBoundingClientRect(),f=h*.26,p=h*.04,g=h*.012;let _=h*.04,m=f,b=h-p;const C=[];for(const Z of t){if(e.contains(Z))continue;let ae=!1;for(let Y=Z;Y;Y=Y.parentElement){const K=l(Y);if(K.display==="none"||K.visibility==="hidden"||Number(K.opacity)===0){ae=!0;break}}if(ae)continue;const oe=Z.getBoundingClientRect();if(!(oe.width<=0||oe.height<=0||!(oe.right>d.left&&oe.left=f&&C.push({top:oe.top})}b=Lz({baseBottom:b,obstacles:C,safeGap:g});const y=b,v=h*.16;({safeTop:m,safeBottom:b}=Pz({viewportHeight:h,safeTop:m,safeBottom:b,obstacleSafeTop:_,obstacleSafeBottom:y,minimumHeight:v}));const M=h*.5;for(const Z of u){const ae=Z.getBoundingClientRect();Z.classList.contains("collapsed")&&ae.height>0&&a.set(Z.id,ae.height)}const w=u.filter(Z=>!Z.classList.contains("collapsed")),E=w.find(Z=>Z.id===o),k=E?[E,...w.filter(Z=>Z!==E)]:w;for(const Z of k)Z.style.removeProperty("--left-panel-allocated-height");const T=Math.max(0,b-m),I=k.map(Z=>xz(Z,l)),R=I.reduce((Z,ae)=>Z+ae,0),S=u.reduce((Z,ae)=>{if(!ae.classList.contains("collapsed"))return Z;const oe=a.get(ae.id);return Z+(oe||ae.getBoundingClientRect().height||0)},0);let A=S;const L=parseFloat(l(e).rowGap)||0;k.length&&(A+=R),A+=L*Math.max(0,u.length-1);const F=e.classList.contains("layout-focus"),P=e.classList.contains("layout-tail"),O=F||P,D=h*.01,$=k.length>0&&(O?A>T-D*2:A>T-D),x=R+S+L*Math.max(0,u.length-1),N=M-x*.5,G=Math.min(N,m),W=G+x,V=Math.max(0,y-_),H=P?D:-D,B=k.length>0&&G>=_-H&&W<=y+H,q=$&&!B,z=q?_:B?G:m,j=q?y:B?W:b,ne=z/h*100,ee=(h-j)/h*100,re=`${ne.toFixed(3)}vh`,se=`${ee.toFixed(3)}vh`,me=q?Math.max(0,j-z-L*Math.max(0,k.length-1)):R,be=KE({naturalHeights:I,availableHeight:me}),J=i.visible?YE({naturalHeights:I,allocatedHeights:be,collapseLaterPanels:q&&i.variant==="tactical"}):[];if(J.length){for(const Z of J){const ae=k[Z];ae.classList.add("collapsed","layout-auto-collapsed"),r(ae)}s();return}e.style.getPropertyValue("--left-stack-safe-top")!==re&&e.style.setProperty("--left-stack-safe-top",re),e.style.getPropertyValue("--left-stack-safe-bottom")!==se&&e.style.setProperty("--left-stack-safe-bottom",se),e.style.removeProperty("--left-stack-centered-height");for(const Z of u)Z.style.removeProperty("--left-panel-allocated-height");k.forEach((Z,ae)=>{Z.style.setProperty("--left-panel-allocated-height",`${be[ae].toFixed(1)}px`)}),e.classList.toggle("layout-focus",q),e.classList.toggle("layout-tail",B),e.dataset.layoutMode=q?"focus":B?"tail":"normal",e.dataset.safeTopPct=ne.toFixed(2),e.dataset.safeBottomPct=(100-ee).toFixed(2),e.dataset.availableHeightPct=(T/h*100).toFixed(2),e.dataset.requiredHeightPct=(A/h*100).toFixed(2),e.dataset.tailAvailableHeightPct=(V/h*100).toFixed(2),e.dataset.expandedCount=String(k.length);for(const Z of u)q&&Z.classList.contains("collapsed")?Z.setAttribute("aria-hidden","true"):Z.removeAttribute("aria-hidden");c()}function Sz({stack:e,obstacles:t,windowRef:n,hud:i,preferredPanelId:o,onCollapse:r,onRetry:s,leftStack:a,displayPanel:c,readDisplayScrollTop:l,documentRef:u=e==null?void 0:e.ownerDocument,getComputedStyle:h=d=>n.getComputedStyle(d)}){if(!e)return;const d=[...e.children].filter(H=>H.matches("[data-panel-id]"));if(!i.visible||i.variant!=="tactical")for(const H of d.filter(B=>B.classList.contains("layout-auto-collapsed")))H.classList.remove("collapsed","layout-auto-collapsed"),r(H);const f=n.matchMedia("(max-width: 720px)").matches,p=d.some(H=>!H.classList.contains("collapsed")&&(!f||H.id!=="pp-toggles")),g=_4({hudVariant:i.variant,hasExpandedPanel:p});e.classList.toggle("layout-exclusive",g);for(const H of d)g&&H.classList.contains("collapsed")?H.setAttribute("aria-hidden","true"):H.removeAttribute("aria-hidden");if(f){e.classList.remove("layout-focus"),e.style.removeProperty("--right-stack-safe-top"),e.style.removeProperty("--right-stack-max-height");for(const H of d)H.style.removeProperty("--right-panel-allocated-height");e.dataset.layoutMode="mobile";return}const _=Math.max(1,n.innerHeight),m=Math.max(8,_*.012),b=e.getBoundingClientRect(),C=a==null?void 0:a.getBoundingClientRect().top,y=Number.isFinite(C)?C:_*.26,v=[];for(const H of t){if(e.contains(H))continue;let B=!1;for(let z=H;z;z=z.parentElement){const j=h(z);if(j.display==="none"||j.visibility==="hidden"||Number(j.opacity)===0){B=!0;break}}if(B)continue;const q=H.getBoundingClientRect();q.width<=0||q.height<=0||v.push({left:q.left,right:q.right,top:q.top,bottom:q.bottom})}const M=d.filter(H=>!g||!H.classList.contains("collapsed")),w=l();for(const H of M)!H.classList.contains("collapsed")&&H!==c&&H.style.removeProperty("--right-panel-allocated-height");const E=parseFloat(h(e).rowGap)||0,k=M.reduce((H,B)=>H+Math.max(B.getBoundingClientRect().height,B.scrollHeight||0,B.classList.contains("collapsed")?42:0),0)+E*Math.max(0,M.length-1),T=g4({viewportHeight:_,panelHeight:k,laneLeft:b.left,laneRight:b.right,obstacles:v,baseTop:y,baseBottom:_*.96,gap:m,align:"start"});if(!T)return;const{safeTop:I,safeBottom:R,maxHeight:S}=T,A=_*.01,F=e.classList.contains("layout-focus")?k>S-A*2:k>S-A,P=F?I:T.top,O=M.reduce((H,B)=>B.classList.contains("collapsed")?H+B.getBoundingClientRect().height:H,0),D=M.filter(H=>!H.classList.contains("collapsed")),$=D.find(H=>H.contains(u.activeElement)),x=D.find(H=>H.id===o)||$,N=x?[x,...D.filter(H=>H!==x)]:D,G=Math.max(0,R-P-O-E*Math.max(0,M.length-1)),W=KE({naturalHeights:N.map(H=>Math.max(H.getBoundingClientRect().height,H.scrollHeight||0)),availableHeight:G}),V=i.visible?YE({naturalHeights:N.map(H=>Math.max(H.getBoundingClientRect().height,H.scrollHeight||0)),allocatedHeights:W,collapseLaterPanels:F&&i.variant==="tactical"}):[];if(V.length){for(const H of V){const B=N[H];B.classList.add("collapsed","layout-auto-collapsed"),r(B)}s();return}N.forEach((H,B)=>{const q=`${W[B].toFixed(1)}px`;H.style.getPropertyValue("--right-panel-allocated-height")!==q&&H.style.setProperty("--right-panel-allocated-height",q)});for(const H of d)N.includes(H)||H.style.removeProperty("--right-panel-allocated-height");if(e.style.setProperty("--right-stack-safe-top",`${P.toFixed(1)}px`),e.style.setProperty("--right-stack-max-height",`${Math.max(0,R-P).toFixed(1)}px`),e.classList.toggle("layout-focus",F),e.dataset.layoutMode=F?"focus":"normal",e.dataset.safeTop=P.toFixed(1),e.dataset.safeBottom=R.toFixed(1),e.dataset.availableHeight=S.toFixed(1),e.dataset.requiredHeight=k.toFixed(1),e.dataset.expandedCount=String(N.length),c&&N.includes(c)){const H=Math.max(0,c.scrollHeight-c.clientHeight);c.scrollTop=Math.min(w,H)}}const Nz=240,p0=["#cockpit-hud .cockpit-topline","#cockpit-hud .cockpit-topline > div","#title-bar","#style-indicator","#top-center-actions","#traffic-sync-chip","#cctv-sync-chip","#intel-hud .hud-top-left","#intel-hud .hud-top-right","#intel-hud .hud-bottom-left","#intel-hud .hud-bottom-right","#intel-hud .hud-top-bar","#intel-hud .hud-bottom-bar","#intel-hud .hud-left-edge","#intel-hud .hud-right-edge","#cockpit-context","#cesium-credits .cesium-credit-logoContainer","#cesium-credits .cesium-credit-textContainer","#location-bar","#control-panel","#gev-voice-control","#pp-toggles","#param-slider-panel"].join(", "),g0=["#cockpit-hud .cockpit-topline","#cockpit-hud .cockpit-topline > div","#title-bar","#style-indicator","#top-center-actions","#traffic-sync-chip","#cctv-sync-chip","#intel-hud .hud-top-left","#intel-hud .hud-top-right","#intel-hud .hud-bottom-left","#intel-hud .hud-bottom-right","#intel-hud .hud-top-bar","#intel-hud .hud-bottom-bar","#intel-hud .hud-left-edge","#intel-hud .hud-right-edge","#cockpit-context","#cockpit-signal-stream","#cesium-credits .cesium-credit-logoContainer","#cesium-credits .cesium-credit-textContainer","#command-dock","#gev-voice-control"].join(", ");class Dz{constructor({readHud:t,scheduleCockpitLayout:n,syncPanelCollapseButton:i,readDisplayScrollTop:o}){this.readHud=t,this.scheduleCockpitLayout=n,this._syncPanelCollapseButton=i,this.readDisplayScrollTop=o,this.destroyed=!1,this._adaptivePanelSettleTimer=null,this._commandDockTrayObserver=null,this._leftStackCockpitModeHandler=null,this._leftStackCollapsedHeights=new Map,this._leftStackHudTransitionHandler=null,this._leftStackLayoutFrame=null,this._leftStackMutationObserver=null,this._leftStackPreferredPanelId=null,this._leftStackReconsiderAutoCollapse=!1,this._leftStackResizeObserver=null,this._rightStackHudTransitionHandler=null,this._rightStackLayoutFrame=null,this._rightStackMutationObserver=null,this._rightStackPreferredPanelId=null,this._rightStackReconsiderAutoCollapse=!1,this._rightStackResizeObserver=null,this._cockpitLayoutFrame=null,this._cockpitLayoutTimer=null,this._leftPanelStack=document.getElementById("left-panel-stack"),this._rightPanelStack=document.getElementById("right-context-rail"),this._ppToggles=document.getElementById("pp-toggles"),this._cctvPanel=document.getElementById("cctv-panel"),this._sliderPanel=document.getElementById("param-slider-panel"),this._detectionBtn=document.getElementById("detection-toggle")}_scheduleAdaptivePanelLayout({settle:t=!1}={}){this.destroyed||(this._scheduleLeftPanelLayout({reconsiderAutoCollapse:!0}),this._scheduleRightPanelLayout({reconsiderAutoCollapse:!0}),this.scheduleCockpitLayout(),t&&(clearTimeout(this._adaptivePanelSettleTimer),this._adaptivePanelSettleTimer=setTimeout(()=>{this.destroyed||(this._adaptivePanelSettleTimer=null,this._scheduleLeftPanelLayout({reconsiderAutoCollapse:!0}),this._scheduleRightPanelLayout({reconsiderAutoCollapse:!0}),this.scheduleCockpitLayout())},Nz)))}_initCommandDockTrayMetrics(){var n,i;if(this.destroyed)return;const t=document.getElementById("command-dock");t&&((i=(n=this._commandDockTrayObserver)==null?void 0:n.disconnect)==null||i.call(n),typeof ResizeObserver=="function"&&(this._commandDockTrayObserver=new ResizeObserver(()=>this._updateCommandDockTrayStack()),t.querySelectorAll(".dock-popover-content").forEach(o=>{this._commandDockTrayObserver.observe(o)})),this._updateCommandDockTrayStack())}_updateCommandDockTrayStack(){var f,p,g;if(this.destroyed)return;const t=document.getElementById("command-dock");if(!t)return;const n=t.querySelector("#location-bar.dock-pinned:not(.collapsed)"),i=t.querySelector("#control-panel.dock-pinned:not(.collapsed)"),o=((f=n==null?void 0:n.querySelector(".dock-popover-content"))==null?void 0:f.getBoundingClientRect().height)||0,r=((p=i==null?void 0:i.querySelector(".dock-popover-content"))==null?void 0:p.getBoundingClientRect().height)||0,s=+(o>0)+ +(r>0),a=Math.ceil(o),c=Math.ceil(r),l=t.querySelector(".dock-pinned-top.dock-pinned:not(.collapsed)"),u=(l==null?void 0:l.id)==="location-bar"?i:n,h=((g=u==null?void 0:u.querySelector(".dock-popover-content"))==null?void 0:g.getBoundingClientRect().height)||0,d=s>1?`calc(${a}px + ${c}px + 1.2rem)`:`${a+c}px`;t.style.setProperty("--dock-location-pinned-height",`${a}px`),t.style.setProperty("--dock-presets-pinned-height",`${c}px`),t.style.setProperty("--dock-lower-pinned-height",`${Math.ceil(h)}px`),t.style.setProperty("--dock-pinned-stack-height",d),t.classList.toggle("dock-has-pinned-tray",s>0),t.classList.toggle("dock-has-two-pinned-trays",s>1)}_initRightPanelAdaptiveLayout(){var o,r;if(this.destroyed)return;const t=this._rightPanelStack;if(!t||!this._ppToggles)return;this._ppToggles.style.removeProperty("top"),this._ppToggles.style.removeProperty("right"),this._ppToggles.style.removeProperty("bottom"),this._ppToggles.style.removeProperty("left"),this._ppToggles.style.removeProperty("z-index"),this._ppToggles.classList.remove("panel-draggable","panel-dragging"),(o=this._ppToggles.querySelector(".pp-header-row"))==null||o.removeAttribute("title"),t.prepend(this._ppToggles);const n=document.getElementById("global-context-panel");if(this._cctvPanel&&(this._cctvPanel.style.removeProperty("top"),this._cctvPanel.style.removeProperty("right"),this._cctvPanel.style.removeProperty("bottom"),this._cctvPanel.style.removeProperty("left"),this._cctvPanel.style.removeProperty("z-index"),this._cctvPanel.classList.remove("panel-draggable","panel-dragging"),t.insertBefore(this._cctvPanel,n),this._syncPanelCollapseButton(this._cctvPanel)),this._sliderPanel){this._sliderPanel.style.removeProperty("top"),this._sliderPanel.style.removeProperty("right"),this._sliderPanel.style.removeProperty("bottom"),this._sliderPanel.style.removeProperty("left"),this._sliderPanel.style.removeProperty("max-height");const s=(r=this._detectionBtn)==null?void 0:r.closest(".pp-toggle-group");s?s.after(this._sliderPanel):this._ppToggles.append(this._sliderPanel)}if(typeof ResizeObserver<"u"){this._rightStackResizeObserver=new ResizeObserver(()=>{this._scheduleRightPanelLayout()}),this._rightStackResizeObserver.observe(t);for(const s of[this._ppToggles,this._cctvPanel,n])s&&this._rightStackResizeObserver.observe(s);document.querySelectorAll(g0).forEach(s=>{this._rightStackResizeObserver.observe(s)})}if(typeof MutationObserver<"u"){this._rightStackMutationObserver=new MutationObserver(()=>{this._scheduleRightPanelLayout()}),this._rightStackMutationObserver.observe(t,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:["class","hidden","data-variant"]});const s=document.getElementById("intel-hud");s&&this._rightStackMutationObserver.observe(s,{subtree:!0,attributes:!0,attributeFilter:["class","hidden","data-variant"]})}const i=document.getElementById("intel-hud");i&&(this._rightStackHudTransitionHandler=s=>{(s.propertyName==="opacity"||s.propertyName==="visibility")&&this._scheduleRightPanelLayout({reconsiderAutoCollapse:!0})},i.addEventListener("transitionend",this._rightStackHudTransitionHandler)),this._scheduleRightPanelLayout()}_scheduleRightPanelLayout({reconsiderAutoCollapse:t=!1}={}){this.destroyed||(t&&(this._rightStackReconsiderAutoCollapse=!0),!(!this._rightPanelStack||this._rightStackLayoutFrame!==null)&&(this._rightStackLayoutFrame=requestAnimationFrame(()=>{if(!this.destroyed){if(this._rightStackLayoutFrame=null,this._rightStackReconsiderAutoCollapse){this._rightStackReconsiderAutoCollapse=!1;for(const n of this._rightPanelStack.querySelectorAll(".layout-auto-collapsed"))n.classList.remove("collapsed","layout-auto-collapsed"),this._syncPanelCollapseButton(n)}this._syncRightPanelAdaptiveLayout()}})))}_syncRightPanelAdaptiveLayout(){this.destroyed||Sz({stack:this._rightPanelStack,obstacles:document.querySelectorAll(g0),windowRef:window,hud:this.readHud(),preferredPanelId:this._rightStackPreferredPanelId,onCollapse:t=>this._syncPanelCollapseButton(t),onRetry:()=>this._scheduleRightPanelLayout(),leftStack:this._leftPanelStack,displayPanel:this._ppToggles,readDisplayScrollTop:this.readDisplayScrollTop})}_initLeftPanelAdaptiveLayout(){if(this.destroyed)return;const t=this._leftPanelStack;if(!t)return;if(typeof ResizeObserver<"u"&&(this._leftStackResizeObserver=new ResizeObserver(()=>{this._scheduleLeftPanelLayout()}),this._leftStackResizeObserver.observe(t),t.querySelectorAll(":scope > [data-panel-id]").forEach(i=>{this._leftStackResizeObserver.observe(i);const o=[...i.children].find(r=>!r.classList.contains("panel-glow"));o&&this._leftStackResizeObserver.observe(o)}),document.querySelectorAll(p0).forEach(i=>{this._leftStackResizeObserver.observe(i)})),typeof MutationObserver<"u"){this._leftStackMutationObserver=new MutationObserver(()=>{this._scheduleLeftPanelLayout()}),this._leftStackMutationObserver.observe(t,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:["class"]});const i=document.getElementById("intel-hud");i&&this._leftStackMutationObserver.observe(i,{attributes:!0,attributeFilter:["class","data-variant"]});const o=document.getElementById("cesium-credits");o&&this._leftStackMutationObserver.observe(o,{subtree:!0,childList:!0})}const n=document.getElementById("intel-hud");n&&(this._leftStackHudTransitionHandler=i=>{(i.propertyName==="opacity"||i.propertyName==="visibility")&&(this._scheduleLeftPanelLayout({reconsiderAutoCollapse:!0}),this.scheduleCockpitLayout())},n.addEventListener("transitionend",this._leftStackHudTransitionHandler)),this._leftStackCockpitModeHandler=()=>{this.destroyed||(this._scheduleLeftPanelLayout(),this._cockpitLayoutFrame!==null&&cancelAnimationFrame(this._cockpitLayoutFrame),this._cockpitLayoutFrame=requestAnimationFrame(()=>{this._cockpitLayoutFrame=null,this._scheduleLeftPanelLayout()}),clearTimeout(this._cockpitLayoutTimer),this._cockpitLayoutTimer=setTimeout(()=>{this._cockpitLayoutTimer=null,this._scheduleLeftPanelLayout()},300))},window.addEventListener("gev:cockpit-mode-changed",this._leftStackCockpitModeHandler),this._scheduleLeftPanelLayout()}_scheduleLeftPanelLayout({reconsiderAutoCollapse:t=!1}={}){this.destroyed||(t&&(this._leftStackReconsiderAutoCollapse=!0),!(!this._leftPanelStack||this._leftStackLayoutFrame!==null)&&(this._leftStackLayoutFrame=requestAnimationFrame(()=>{if(!this.destroyed){if(this._leftStackLayoutFrame=null,this._leftStackReconsiderAutoCollapse){this._leftStackReconsiderAutoCollapse=!1;for(const n of this._leftPanelStack.querySelectorAll(".layout-auto-collapsed"))n.classList.remove("collapsed","layout-auto-collapsed"),this._syncPanelCollapseButton(n)}this._syncLeftPanelAdaptiveLayout()}})))}_syncLeftPanelAdaptiveLayout(){this.destroyed||Fz({stack:this._leftPanelStack,obstacles:document.querySelectorAll(p0),windowRef:window,hud:this.readHud(),preferredPanelId:this._leftStackPreferredPanelId,onCollapse:t=>this._syncPanelCollapseButton(t),onRetry:()=>this._scheduleLeftPanelLayout(),collapsedHeights:this._leftStackCollapsedHeights,onAligned:()=>this._scheduleRightPanelLayout()})}destroy(){var t,n;if(!this.destroyed){this.destroyed=!0;for(const i of["_leftStackLayoutFrame","_rightStackLayoutFrame","_cockpitLayoutFrame"])this[i]!==null&&cancelAnimationFrame(this[i]),this[i]=null;clearTimeout(this._adaptivePanelSettleTimer),clearTimeout(this._cockpitLayoutTimer),this._adaptivePanelSettleTimer=this._cockpitLayoutTimer=null;for(const i of["_commandDockTrayObserver","_leftStackResizeObserver","_leftStackMutationObserver","_rightStackResizeObserver","_rightStackMutationObserver"])(t=this[i])==null||t.disconnect(),this[i]=null;for(const i of["_leftStackHudTransitionHandler","_rightStackHudTransitionHandler"])this[i]&&((n=document.getElementById("intel-hud"))==null||n.removeEventListener("transitionend",this[i])),this[i]=null;this._leftStackCockpitModeHandler&&window.removeEventListener("gev:cockpit-mode-changed",this._leftStackCockpitModeHandler),this._leftStackCockpitModeHandler=null}}}function XE(){const e=[];return{listen(t,n,i,o){t&&(t.addEventListener(n,i,o),e.push(()=>t.removeEventListener(n,i,o)))},destroy(){for(const t of e.splice(0))t()}}}function Oz({panel:e,buttons:t=[],onChange:n,onEscape:i}){if(!e||typeof n!="function"||typeof i!="function")throw new TypeError("Panel disclosure requires a panel, onChange and onEscape");const o=XE();for(const r of new Set(t))o.listen(r,"click",()=>{n(!e.classList.contains("collapsed"),{explicit:!0})});return o.listen(e,"keydown",i),{destroy:()=>o.destroy()}}function Bz(e,{panel:t,onChange:n,beforeCollapse:i}){var a,c,l,u,h;if(e.key!=="Escape"||e.defaultPrevented||!t||t.classList.contains("collapsed")||!t.contains(e.target))return!1;const o=(c=(a=e.target)==null?void 0:a.closest)==null?void 0:c.call(a,".panel-collapsible:not(.collapsed), #param-slider-panel:not(.collapsed)");if(o&&o!==t)return!1;e.preventDefault(),e.stopPropagation(),i==null||i(),n(!0,{explicit:!0});const r=t.querySelector(`[data-dock-toggle-target="${t.id}"]`)||t.querySelector(`[data-collapse-target="${t.id}"]`);return e.target===r||((l=r==null?void 0:r.contains)==null?void 0:l.call(r,e.target))?(u=r==null?void 0:r.blur)==null||u.call(r):(h=r==null?void 0:r.focus)==null||h.call(r,{preventScroll:!0}),!0}function Vz({panel:e,disclosure:t=null,onChange:n,onEscape:i,focusTarget:o=null,isActive:r=()=>!0,openDelayMs:s=850,closeDelayMs:a=1e3,documentRef:c=e==null?void 0:e.ownerDocument}){if(!e||!c||typeof n!="function"||typeof i!="function")throw new TypeError("Hover disclosure requires a panel, document, onChange and onEscape");const l=c,u=l.defaultView,h=u.clearTimeout.bind(u),d=u.performance,f=XE(),p=f.listen;let g=!1,_=null,m=null,b=0,C=null,y=0;const v=()=>{h(C),C=null,y+=1},M=()=>{_&&(h(_),_=null)},w=()=>{m&&(h(m),m=null)},E=()=>{M(),_=u.setTimeout(()=>{_=null,!(g||!r())&&e.matches(":hover")&&(d.now()-b<280||e.classList.contains("collapsed")&&n(!1))},s)},k=()=>{const A=l.activeElement;if(!A||!e.contains(A))return!1;try{return A.matches(":focus-visible")}catch{return!0}},T=()=>{w(),m=u.setTimeout(()=>{m=null,!(g||!r())&&(e.matches(":hover")||k()||e.classList.contains("dock-pinned")||e.classList.contains("collapsed")||n(!0))},a)};p(e,"wheel",()=>{b=d.now(),M()},{passive:!0}),p(e,"click",A=>{A.target.closest(".panel-collapse-btn, .dock-tray-toggle")||(M(),w(),e.classList.contains("collapsed")&&n(!1,{explicit:!0}))}),p(e,"pointerenter",A=>{const L=A.pointerType||"mouse";L!=="mouse"&&L!=="pen"||(w(),e.classList.contains("collapsed")&&E())}),p(e,"pointerleave",A=>{const L=A.pointerType||"mouse";L!=="mouse"&&L!=="pen"||(M(),T())}),p(e,"pointerdown",()=>{v(),M(),w()});const I=()=>{const A=o==null?void 0:o();return g||!r()||!(A!=null&&A.focus)?!1:(A.focus({preventScroll:!0}),l.activeElement===A)},R=()=>{if(v(),g||!r()||!o)return;const A=y;let L=0;const F=()=>{A===y&&(C=null,!(g||!r()||e.classList.contains("collapsed"))&&l.activeElement===t&&(I()||A===y&&(++L>24||(C=u.setTimeout(F,30)))))};C=u.setTimeout(F,240)},S=({focusContent:A=!1}={})=>{if(g||!r())return;v(),M(),w();const L=e.classList.contains("collapsed");n(!L,{explicit:!0}),L&&A&&R()};return p(t,"click",A=>{A.stopPropagation(),S({focusContent:A.detail===0})}),p(t,"keydown",A=>{A.key==="Enter"&&(A.preventDefault(),A.stopPropagation(),!A.repeat&&S({focusContent:!0}))}),p(e,"focusin",()=>w()),p(e,"focusout",A=>{v(),!e.contains(A.relatedTarget)&&T()}),p(e,"keydown",A=>{A.key==="Escape"&&(A.defaultPrevented||i(A),v(),M(),w())}),{cancelPendingFocus:v,destroy(){g||(g=!0,M(),w(),v(),f.destroy())}}}const _0=Object.freeze([{id:"control-panel",pinnable:!0},{id:"location-bar",pinnable:!0},{id:"data-panel"},{id:"cctv-panel"},{id:"radio-panel"},{id:"scene-panel"},{id:"global-context-panel"},{id:"pp-toggles"},{id:"param-slider-panel"}]),Hz=Object.freeze(["data-panel","cctv-panel","scene-panel","pp-toggles","global-context-panel","radio-panel"]);class $z{constructor({elements:t,operations:n,readHud:i,readCockpit:o,readShareLinks:r,readInitialShare:s,readScrollRestoreOwner:a,readDisplayScrollTop:c}){Object.assign(this,t,n,{readHud:i,readCockpit:o,readShareLinks:r,readInitialShare:s,readScrollRestoreOwner:a,readDisplayScrollTop:c}),this._disposed=!1,this._lifetime=new cu,this._cockpitPanelRestore=null,this._cockpitContextCollapsedForDataPanel=!1,this._panelPosition=new Rz({syncPanelCollapseButton:l=>this._syncPanelCollapseButton(l),layoutRightPanels:()=>this._layoutRightPanels(),syncCctvPanelViewport:()=>this._syncCctvPanelViewport(),showToast:l=>this._showToast(l)}),this._panelLayout=new Dz({readHud:()=>({visible:this.hud.visible,variant:this.hud.getVariant()}),scheduleCockpitLayout:()=>{var l;return(l=this.cockpitView)==null?void 0:l.scheduleContextLayout()},syncPanelCollapseButton:l=>this._syncPanelCollapseButton(l),readDisplayScrollTop:()=>{var l;return this._displayPortalScrollRestoreOwner==="standard"?this._standardDisplayScrollTop:((l=this._ppToggles)==null?void 0:l.scrollTop)||0}})}get hud(){return this.readHud()}get cockpitView(){return this.readCockpit()}get shareLinkManager(){return this.readShareLinks()}get _initialShareState(){return this.readInitialShare()}get _displayPortalScrollRestoreOwner(){return this.readScrollRestoreOwner()}get _standardDisplayScrollTop(){return this.readDisplayScrollTop()}_initPanelChrome(){for(const n of this._panelDisclosureControls||[])n.destroy();this._panelDisclosureControls=[];const t=new Map;document.querySelectorAll(".panel-collapse-btn[data-collapse-target]").forEach(n=>{const i=n.dataset.collapseTarget;i&&(t.has(i)||t.set(i,[]),t.get(i).push(n))});for(const[n,i]of t){const o=document.getElementById(n);o&&(this._panelDisclosureControls.push(Oz({panel:o,buttons:i,onChange:(r,s)=>this.setPanelCollapsed(n,r,s),onEscape:r=>this._collapsePanelOnEscape(r,n)})),this._restorePanelCollapsedState(n,{allowStored:!this._initialShareState}))}this.setPanelCollapsed("control-panel",!0,{syncShare:!1,persist:!1}),this.setPanelCollapsed("location-bar",!0,{syncShare:!1,persist:!1}),this._initAutoHoverPanel("control-panel",{openDelayMs:140,closeDelayMs:420}),this._initAutoHoverPanel("location-bar",{openDelayMs:140,closeDelayMs:420}),this._initCommandDockPins(),this._initCommandDockTrayMetrics(),this._maybeNotifyLayoutReset()}_collapsePanelOnEscape(t,n){return Bz(t,{panel:document.getElementById(n),onChange:(i,o)=>this.setPanelCollapsed(n,i,o),beforeCollapse:()=>{n!=="location-bar"||!this._locationSearch||(this._locationSearch.classList.remove("expanded"),this._locationSearch.value="",this._locationSearch.blur())}})}_initCommandDockPins(){document.querySelectorAll(".dock-pin-btn[data-pin-target]").forEach(t=>{this._lifetime.listen(t,"click",n=>{n.stopPropagation();const i=t.dataset.pinTarget;this._setCommandDockPanelPinState(i)})})}_setCommandDockPanelPinState(t,n,{restore:i=!1,persist:o=!0,syncShare:r=!0}={}){var l,u,h,d;const s=document.getElementById(t),a=document.querySelector(`.dock-pin-btn[data-pin-target="${t}"]`);if(!s||!a)return;const c=typeof n=="boolean"?n:!s.classList.contains("dock-pinned");if(s.classList.toggle("dock-pinned",c),a.setAttribute("aria-pressed",String(c)),document.querySelectorAll("#command-dock .dock-pinned-top").forEach(f=>{f.classList.remove("dock-pinned-top")}),c)s.classList.add("dock-pinned-top"),this.setPanelCollapsed(t,!1,{explicit:!i,restore:i,persist:o,syncShare:!1});else{const f=document.querySelector("#command-dock .dock-pinned");f==null||f.classList.add("dock-pinned-top"),!i&&!s.matches(":hover")&&this.setPanelCollapsed(t,!0,{explicit:!0,persist:o,syncShare:!1})}return this._updateCommandDockTrayStack(),r&&(i||(u=(l=this.shareLinkManager)==null?void 0:l.claimRestoreLane)==null||u.call(l,"panel",t),(d=(h=this.shareLinkManager)==null?void 0:h.onPanelStateChange)==null||d.call(h)),c}_initCommandDockTrayMetrics(){return this._panelLayout._initCommandDockTrayMetrics()}_updateCommandDockTrayStack(){return this._panelLayout._updateCommandDockTrayStack()}_maybeNotifyLayoutReset(){return this._panelPosition._maybeNotifyLayoutReset()}_initAutoHoverPanel(t,{openDelayMs:n=850,closeDelayMs:i=1e3}={}){var s,a;const o=document.getElementById(t);if(!o)return;this._hoverPanelControls??(this._hoverPanelControls=new Map),(s=this._hoverPanelControls.get(t))==null||s.destroy();const r=Vz({panel:o,documentRef:document,disclosure:o.querySelector(`[data-dock-toggle-target="${t}"]`),openDelayMs:n,closeDelayMs:i,isActive:()=>!this._disposed,onChange:(c,l)=>this.setPanelCollapsed(t,c,l),onEscape:c=>this._collapsePanelOnEscape(c,t),focusTarget:t==="control-panel"?()=>o.querySelector(".map-stack-chip.active")||o.querySelector(".map-stack-chip"):null});this._hoverPanelControls.set(t,r),t==="control-panel"&&((a=this._cancelMapSourceFocus)==null||a.call(this),this._cancelMapSourceFocus=r.cancelPendingFocus)}_restorePanelCollapsedState(t,n){return this._panelPosition._restorePanelCollapsedState(t,n)}_savePanelCollapsedState(t,n){return this._panelPosition._savePanelCollapsedState(t,n)}_scheduleRightPanelLayout(t){return this._panelLayout._scheduleRightPanelLayout(t)}_scheduleLeftPanelLayout(t){return this._panelLayout._scheduleLeftPanelLayout(t)}_syncPanelCollapseButton(t){var r,s;const n=["pp-toggles","cctv-panel","global-context-panel"].includes(t==null?void 0:t.id),i=t.classList.contains("collapsed");t.querySelectorAll(".panel-collapse-btn[data-collapse-target]").forEach(a=>{var h,d;if(a.closest("[data-panel-id], #param-slider-panel")!==t)return;n?a.textContent=i?"◀":"▶":a.textContent=i?"+":"−",a.setAttribute("aria-expanded",String(!i));const l=((d=(h=t.querySelector(".panel-title, .pp-header-label"))==null?void 0:h.textContent)==null?void 0:d.trim())||"panel",u=i?"Expand":"Collapse";if(a.title=`${u} ${l}`,a.setAttribute("aria-label",`${u} ${l}`),t.id==="radio-panel"){const f=i?"Expand":"Collapse";a.title=`${f} Radio`,a.setAttribute("aria-label",`${f} Radio section`)}});const o=t.querySelector(`[data-dock-toggle-target="${t.id}"]`);if(o){const a=((s=(r=t.querySelector(".panel-title, .location-toolbar-label"))==null?void 0:r.textContent)==null?void 0:s.trim())||"panel",c=i?"Expand":"Collapse";o.setAttribute("aria-expanded",String(!i)),o.setAttribute("aria-label",`${c} ${a}`),o.title=`${c} ${a}`}t.id==="radio-panel"&&this._contextRadioDetailsBtn&&this._contextRadioDetailsBtn.setAttribute("aria-expanded",String(!i)),(t.id==="radio-panel"||t.id==="global-context-panel")&&this._syncContextRadioLauncherState()}_buildSharePanelState(){const t=[];for(const n of _0){const i=document.getElementById(n.id);if(!i)continue;const o=i.classList.contains("layout-auto-collapsed")?!1:i.classList.contains("collapsed"),r={id:n.id,collapsed:o};n.pinnable&&(r.pinned=i.classList.contains("dock-pinned")),t.push(r)}return t.length?{specs:t}:null}_restorePanelState(t){var i,o;if(!t||!Array.isArray(t.specs))return;const n=new Map(t.specs.map(r=>[r.id,r]));for(const r of _0){const s=n.get(r.id);if(!s||typeof s.collapsed!="boolean")continue;r.pinnable&&typeof s.pinned=="boolean"&&this._setCommandDockPanelPinState(r.id,s.pinned,{restore:!0,persist:!1,syncShare:!1});const a=s.pinned&&r.pinnable?!1:s.collapsed;this.setPanelCollapsed(r.id,a,{restore:!0,persist:!1,syncShare:!1})}(o=(i=this.shareLinkManager)==null?void 0:i.onPanelStateChange)==null||o.call(i)}setPanelCollapsed(t,n,{explicit:i=!1,restore:o=!1,persist:r=!0,syncShare:s=!0}={}){var p,g,_,m,b,C,y,v,M,w,E,k,T,I;t==="control-panel"&&n&&((p=this._cancelMapSourceFocus)==null||p.call(this));const a=document.getElementById(t);if(!a)return;i&&!o&&((_=(g=this.shareLinkManager)==null?void 0:g.claimRestoreLane)==null||_.call(g,"panel",t));const c=!!n,l=a.classList.contains("layout-auto-collapsed"),u=(m=this._leftPanelStack)!=null&&m.contains(a)?a:null,h=t==="radio-panel"?document.getElementById("global-context-panel"):(b=this._rightPanelStack)!=null&&b.contains(a)?a:null,d=this._panelLayout._leftStackPreferredPanelId,f=this._panelLayout._rightStackPreferredPanelId;if(i&&!o&&!c&&u?this._panelLayout._leftStackPreferredPanelId=u.id:i&&!o&&c&&(u==null?void 0:u.id)===this._panelLayout._leftStackPreferredPanelId&&(this._panelLayout._leftStackPreferredPanelId=null),i&&!o&&!c&&h?this._panelLayout._rightStackPreferredPanelId=h.id:i&&!o&&c&&(h==null?void 0:h.id)===this._panelLayout._rightStackPreferredPanelId&&(this._panelLayout._rightStackPreferredPanelId=null),a.classList.contains("collapsed")===c&&!l){this._syncPanelCollapseButton(a),d!==this._panelLayout._leftStackPreferredPanelId&&this._scheduleLeftPanelLayout({reconsiderAutoCollapse:!0}),f!==this._panelLayout._rightStackPreferredPanelId&&this._scheduleRightPanelLayout({reconsiderAutoCollapse:!0});return}if(a.classList.remove("layout-auto-collapsed"),!c&&((C=this.cockpitView)!=null&&C.active)&&t==="data-panel"&&(this._cockpitContextCollapsedForDataPanel=!this.cockpitView.contextCollapsed,this._cockpitContextCollapsedForDataPanel&&this.cockpitView.setContextCollapsed(!0)),!c&&t==="global-context-panel"&&((y=this._contextRadioDock)!=null&&y.classList.contains("disclosure-open"))&&((v=this._setRadioDisclosure)==null||v.call(this,!1)),!c&&t==="radio-panel"&&((M=document.getElementById("global-context-panel"))!=null&&M.classList.contains("collapsed"))&&this.setPanelCollapsed("global-context-panel",!1,{restore:o,persist:r,syncShare:s}),!c&&!o&&t==="location-bar"){const R=document.getElementById("control-panel");R&&!R.classList.contains("dock-pinned")&&this.setPanelCollapsed("control-panel",!0,{restore:o,persist:r,syncShare:s})}else if(!c&&!o&&t==="control-panel"){const R=document.getElementById("location-bar");R&&!R.classList.contains("dock-pinned")&&this.setPanelCollapsed("location-bar",!0,{restore:o,persist:r,syncShare:s})}a.classList.toggle("collapsed",c),c&&((w=this.cockpitView)!=null&&w.active)&&t==="data-panel"&&this._cockpitContextCollapsedForDataPanel&&(this._cockpitContextCollapsedForDataPanel=!1,this.cockpitView.setContextCollapsed(!1)),this._syncPanelCollapseButton(a),r!==!1&&this._savePanelCollapsedState(t,c),t==="pp-toggles"&&this._layoutRightPanels(),(E=this._rightPanelStack)!=null&&E.contains(a)&&this._scheduleRightPanelLayout({reconsiderAutoCollapse:!0}),t==="cctv-panel"&&this._syncCctvPanelViewport(),this._lifetime.frame(()=>this._updateCommandDockTrayStack()),this._scheduleLeftPanelLayout({reconsiderAutoCollapse:((k=this._leftPanelStack)==null?void 0:k.contains(a))===!0}),s&&((I=(T=this.shareLinkManager)==null?void 0:T.onPanelStateChange)==null||I.call(T))}_layoutRightPanels(){this._scheduleRightPanelLayout()}enterCockpit(){var t,n;this._cockpitPanelRestore=new Map,this._cockpitContextCollapsedForDataPanel=!1;for(const i of Hz){const o=document.getElementById(i);o&&this._cockpitPanelRestore.set(i,o.classList.contains("collapsed")),this.setPanelCollapsed(i,!0,{persist:!1,syncShare:!1})}(t=this.cockpitView)==null||t.setContextCollapsed(!1),(n=this.cockpitView)==null||n.setSignalCollapsed(!1,{user:!0})}exitCockpit(){const t=this._cockpitPanelRestore;if(this._cockpitPanelRestore=null,this._cockpitContextCollapsedForDataPanel=!1,!!t)for(const[n,i]of t)this.setPanelCollapsed(n,i,{persist:!1,syncShare:!1})}destroy(){var t,n,i;if(!this._disposed){this._disposed=!0,this._lifetime.destroy(),this._panelPosition.destroy(),this._panelLayout.destroy();for(const o of this._panelDisclosureControls||[])o.destroy();this._panelDisclosureControls=[],(t=this._hoverPanelControls)==null||t.forEach(o=>o.destroy()),(n=this._hoverPanelControls)==null||n.clear(),(i=this._cancelMapSourceFocus)==null||i.call(this)}}}class Gz{constructor({viewer:t,requestRender:n,holdRender:i,releaseRender:o,requestFrame:r=u=>requestAnimationFrame(u),cancelFrame:s=u=>cancelAnimationFrame(u),now:a=()=>performance.now(),wallNow:c=()=>Date.now(),createStage:l=u=>new Cesium.PostProcessStage(u)}){this.viewer=t,this.requestRender=n,this.holdRender=i,this.releaseRender=o,this.requestFrame=r,this.cancelFrame=s,this.now=a,this.wallNow=c,this.createStage=l,this.stages={},this.transitions=new Map,this.startTime=c(),this.bloomEnabled=!1,this.sharpenEnabled=!1,this.bloomIntensity=oi,this.sharpenIntensity=.49,this.bloomStage=null,this.sharpenStage=null,this.frameId=null,this.stopped=!1,this.destroyed=!1,this.stageEntries=[],this.previousBloom=null}initStyles(){if(!(this.stopped||this.stageEntries.length)){for(const[t,n]of Object.entries(Ir)){const i={intensity:0};n.fragmentShader.includes("uniform float time")&&(i.time=0);for(const[r,s]of Object.entries(n.uniforms||{}))i[r]=s.default;const o=this.createStage({name:`godsEyeView_${t}`,fragmentShader:n.fragmentShader,uniforms:i});o.enabled=!1,this.viewer.scene.postProcessStages.add(o),this.stages[t]=o}this.stageEntries=Object.entries(this.stages)}}initPostProcess(t=this.sharpenIntensity){if(this.stopped||this.sharpenStage)return;this.bloomStage=this.viewer.scene.postProcessStages.bloom;const n=["glowOnly","contrast","brightness","delta","sigma","stepSize"];this.previousBloom={enabled:this.bloomStage.enabled,uniforms:Object.fromEntries(n.map(i=>[i,this.bloomStage.uniforms[i]]))},this.bloomStage.enabled=!1,Object.assign(this.bloomStage.uniforms,{glowOnly:!1,contrast:256,brightness:-.35,delta:.25,sigma:.35,stepSize:1}),this.sharpenStage=this.createStage({name:"godsEyeView_sharpen",fragmentShader:kz,uniforms:{amount:1.3}}),this.sharpenStage.enabled=!1,this.viewer.scene.postProcessStages.add(this.sharpenStage),this.applySharpenIntensity(t)}setStageIntensity(t,n){this.stopped||!t||(t.uniforms.intensity=n,t.enabled=n>.001,t.enabled&&t.uniforms.time!==void 0&&this.startAnimationLoop(),this.requestRender("style-stage"))}syncStagesEnabledFromIntensity(){for(const[,t]of this.stageEntries)this.setStageIntensity(t,t.uniforms.intensity)}syncBloomEnabled(){this.stopped||!this.bloomStage||(this.bloomStage.enabled=this.bloomEnabled&&d0(this.bloomIntensity)>.06)}applyBloomIntensity(t){if(this.stopped||(this.bloomIntensity=Ni(t),this.requestRender("bloom"),!this.bloomStage))return;const n=d0(this.bloomIntensity),i=n<=.06?0:(n-.06)/.94,o=i*i*(3-2*i);this.bloomStage.uniforms.contrast=255-o*168,this.bloomStage.uniforms.brightness=-.5+o*.36,this.bloomStage.uniforms.sigma=.28+o*6.3,this.bloomStage.uniforms.delta=.2+o*2.25,this.bloomStage.uniforms.stepSize=1+o*1.25,this.syncBloomEnabled()}setBloomEnabled(t){this.stopped||(this.bloomEnabled=!!t,this.syncBloomEnabled(),this.requestRender("bloom"))}applySharpenIntensity(t){this.stopped||(this.sharpenIntensity=t,this.sharpenStage&&(this.sharpenStage.uniforms.amount=.1+t*2),this.requestRender("sharpen"))}setSharpenEnabled(t){this.stopped||(this.sharpenEnabled=!!t,this.sharpenStage&&(this.sharpenStage.enabled=this.sharpenEnabled),this.requestRender("sharpen"))}startTransition(t,n,i){this.stopped||(this.transitions.set(t,{start:this.now(),from:n,to:i}),this.startAnimationLoop())}startAnimationLoop(){if(this.stopped||this.frameId!==null)return;const t=()=>{if(this.stopped)return;const n=this.now(),i=(this.wallNow()-this.startTime)/1e3;for(const[s,a]of this.transitions){const c=Math.min((n-a.start)/Ez,1),l=c<.5?2*c*c:1-Math.pow(-2*c+2,2)/2;this.setStageIntensity(this.stages[s],a.from+(a.to-a.from)*l),c>=1&&(this.setStageIntensity(this.stages[s],a.to),this.transitions.delete(s))}let o=!1;for(const[,s]of this.stageEntries)s.enabled&&s.uniforms.time!==void 0&&(s.uniforms.time=i,s.uniforms.intensity>.001&&(o=!0));const r=this.transitions.size>0||o;r?this.holdRender("style-anim"):this.releaseRender("style-anim"),this.frameId=r?this.requestFrame(t):null};this.frameId=this.requestFrame(t)}stop(){this.stopped||(this.stopped=!0,this.frameId!==null&&this.cancelFrame(this.frameId),this.frameId=null,this.releaseRender("style-anim"),this.transitions.clear())}destroy(){if(this.destroyed)return;this.stop(),this.destroyed=!0;const t=this.viewer.scene.postProcessStages;for(const[,n]of this.stageEntries)t.remove(n);this.sharpenStage&&t.remove(this.sharpenStage),this.bloomStage&&this.previousBloom&&(Object.assign(this.bloomStage.uniforms,this.previousBloom.uniforms),this.bloomStage.enabled=this.previousBloom.enabled)}}const b0=Object.freeze({1:"normal",2:"retro",3:"surveillance",4:"thermal",5:"anime",6:"noir",7:"snow"});function Uz({documentRef:e,searchInput:t,actions:n}){const i=o=>{var a,c;if((((c=(a=o.target)==null?void 0:a.matches)==null?void 0:c.call(a,"select, input, textarea"))||o.target===t)&&o.key!=="Escape")return;b0[o.key]&&n.setStyle(b0[o.key]),o.key==="Escape"&&n.dismissSearch();const s=o.key.toLowerCase();s==="h"&&n.toggleHud(),s==="o"&&n.toggleOrbit(),s==="v"&&n.toggleCleanView(),s==="f"&&n.toggleLayers(),s==="d"&&n.cycleDetection(),s==="c"&&n.toggleCctv()};return e.addEventListener("keydown",i),{destroy(){e.removeEventListener("keydown",i)}}}function zz({container:e,documentRef:t=e.ownerDocument}){let n=[],i=!1;const o=()=>{if(!i){for(const[r,s]of n)r.removeEventListener("input",s);n=[],e.replaceChildren()}};return{render({uniforms:r,readValue:s,writeValue:a,onChange:c}){if(!i){o();for(const[l,u]of Object.entries(r)){const h=t.createElement("div");h.className="param-slider-row";const d=t.createElement("span");d.className="param-label",d.textContent=u.label;const f=t.createElement("input");f.type="range",f.className="param-slider",f.setAttribute("aria-label",u.label),f.min=u.min,f.max=u.max,f.step=u.max<=1?"0.01":"0.1",f.value=s(l);const p=u.max<=1?2:1,g=t.createElement("span");g.className="param-value",g.textContent=parseFloat(f.value).toFixed(p);const _=()=>{const m=parseFloat(f.value);a(l,m),g.textContent=m.toFixed(p),c()};f.addEventListener("input",_),n.push([f,_]),h.append(d,f,g),e.appendChild(h)}}},clear:o,destroy(){i||(o(),i=!0)}}}const QE=Object.freeze(["optical","crt","nvg","thermal","noir"]),jz=Object.freeze({crt:"retro",nvg:"surveillance",thermal:"thermal",noir:"noir"});function qm(e){return QE.includes(e)?e:"optical"}function qz(e,t){var i;const n={};for(const[o,r]of Object.entries(e)){const s=((i=t==null?void 0:t.get(o))==null?void 0:i.to)??r.uniforms.intensity;r.uniforms.intensity=s,t==null||t.delete(o),n[o]=s}return n}function C0(e,t,n={}){const i=qm(t);if(i==="optical"){for(const[r,s]of Object.entries(n))e[r]&&(e[r].uniforms.intensity=s);return null}for(const r of Object.values(e))r.uniforms.intensity=0;const o=jz[i]||null;return o&&e[o]&&(e[o].uniforms.intensity=1),o}function ef(e){const t=Number(e==null?void 0:e.densityPct);return{mode:String((e==null?void 0:e.mode)||"OFF").toUpperCase(),densityPct:Number.isFinite(t)?t:null}}function Wz(e,t){if(t)return null;const n=ef(e);return{restore:n,turnOn:n.mode==="OFF"}}function Kz(e,t,n=!1){if(!e||n)return null;const i=ef(e),o=ef(t);return i.mode===o.mode&&i.densityPct===o.densityPct?null:i}function Yz({active:e,restore:t,getState:n,applyPreset:i,restoreState:o,styleOwnsDetection:r=!1}){if(e){const a=Wz(n(),t);return a?(a.turnOn&&i(),{restore:a.restore,changed:a.turnOn}):{restore:t,changed:!1}}const s=Kz(t,n(),r);return s&&o(s),{restore:null,changed:!!s}}function Xz({owned:e,liveMode:t,liveDensityPct:n}){return e?{mode:e.mode??t,densityPct:Number.isFinite(e.densityPct)?e.densityPct:n}:{mode:t,densityPct:n}}function Qz({changed:e,hadOwnership:t,hasOwnership:n}){return!!e||!!t!=!!n}const y0="gev:detection-allocation:v1";class Zz{constructor({viewer:t,services:n,elements:i,operations:o,mapStackController:r,readHud:s,readCockpit:a,readDataManager:c,readShareLinks:l,readCelestialRing:u,readContextMode:h,readContextChanging:d,readDisplayPortalActive:f}){Object.assign(this,i,o,{viewer:t,services:n,mapStackController:r,readHud:s,readCockpit:a,readDataManager:c,readShareLinks:l,readCelestialRing:u,readContextMode:h,readContextChanging:d,readDisplayPortalActive:f}),this._lifetime=new cu,this._visualEffects=new Gz({viewer:t,requestRender:n.governorRequestRender,holdRender:n.holdContinuousRender,releaseRender:n.releaseContinuousRender}),this.activeStyle="normal",document.documentElement.dataset.gevStyle=this.activeStyle,this._detectionUserOverridden=!1,this._cockpitVisionMode="optical",this._cockpitVisionRestore=null,this._contactsDetectionRestore=null,this._detectionAllocationBtns=[document.getElementById("detection-allocation-elastic"),document.getElementById("detection-allocation-weighted")].filter(Boolean);let p="ELASTIC";try{p=localStorage.getItem(y0)||"ELASTIC"}catch{}this._detectionAllocationPreference=xo(p)}get hud(){return this.readHud()}get cockpitView(){return this.readCockpit()}get _dataManager(){return this.readDataManager()}get shareLinkManager(){return this.readShareLinks()}get celestialRing(){return this.readCelestialRing()}get _contextMode(){return this.readContextMode()}get _contextModeChanging(){return this.readContextChanging()}get _cockpitDisplayPortalActive(){return this.readDisplayPortalActive()}get stages(){return this._visualEffects.stages}get transitions(){return this._visualEffects.transitions}get bloomEnabled(){return this._visualEffects.bloomEnabled}get sharpenEnabled(){return this._visualEffects.sharpenEnabled}_initStages(){this._visualEffects.initStyles()}_setStageIntensity(t,n){this._visualEffects.setStageIntensity(t,n)}_syncStagesEnabledFromIntensity(){this._visualEffects.syncStagesEnabledFromIntensity()}_syncContactsDetection(){var i;if(this._contextModeChanging)return;const t=Yz({active:this._contextMode==="flights",restore:this._contactsDetectionRestore,styleOwnsDetection:!this._detectionUserOverridden&&!!((i=h0[this.activeStyle])!=null&&i.detection),getState:()=>{const o=this.getDetectionState();return{mode:o.detectionMode,densityPct:o.densityPct}},applyPreset:()=>this._applyDetectionPreset(Rr),restoreState:o=>this._applyDetectionPreset(o)}),n=!!this._contactsDetectionRestore;this._contactsDetectionRestore=t.restore,Qz({changed:t.changed,hadOwnership:n,hasOwnership:!!t.restore})&&(t.changed&&this._syncDetectionUiFromEngine(),this._syncShareState())}_setCockpitVision(t,n,{revealParameters:i=!1}={}){const o=n?qm(t):"optical";if(!this.stages)return;if(!n){if(this._cockpitVisionRestore)for(const[s,a]of Object.entries(this._cockpitVisionRestore))this.stages[s]&&this._setStageIntensity(this.stages[s],a);this._cockpitVisionRestore=null,this._cockpitVisionMode="optical",this._syncIrBoost(),this._updateSliderPanel(this.activeStyle,{reveal:!1}),this._revealCockpitStyleParameters({openDisplay:i});return}if(this._cockpitVisionRestore||(this._cockpitVisionRestore=qz(this.stages,this.transitions)),o==="optical"){C0(this.stages,o,this._cockpitVisionRestore),this._syncStagesEnabledFromIntensity(),this._cockpitVisionMode=o,this._syncIrBoost(),this._updateSliderPanel(this.activeStyle,{reveal:!1}),this._revealCockpitStyleParameters({openDisplay:i});return}const r=C0(this.stages,o,this._cockpitVisionRestore);this._syncStagesEnabledFromIntensity(),this._cockpitVisionMode=o,this._syncIrBoost(),this._updateSliderPanel(r||null,{reveal:!1}),this._revealCockpitStyleParameters({openDisplay:i})}_syncIrBoost(){var r,s,a,c,l;const t=(r=this.cockpitView)!=null&&r.active?this._cockpitVisionMode:null,n=t&&t!=="optical"?t:this.activeStyle,i=n==="surveillance"||n==="thermal"||n==="nvg";(s=this._dataManager)==null||s.setLayerParams("flights",{irBoost:i}),(a=this._dataManager)==null||a.setLayerParams("military",{irBoost:i}),window.dispatchEvent(new CustomEvent("gev:vision-change",{detail:{style:n,cockpit:!!(t&&t!=="optical")}}));const o=(c=this.viewer)==null?void 0:c.scene;o!=null&&o.fog&&i!==this._irBoostActive&&(this._irBoostActive=i,i?(this._irFogWasEnabled=o.fog.enabled,o.fog.enabled=!1):this._irFogWasEnabled!=null&&(o.fog.enabled=this._irFogWasEnabled,this._irFogWasEnabled=null),(l=o.requestRender)==null||l.call(o))}_syncCockpitInheritedStyle(){var t;if(!(!((t=this.cockpitView)!=null&&t.active)||!this.stages)){this._cockpitVisionRestore=Object.fromEntries(Object.keys(this.stages).map(n=>[n,n===this.activeStyle?1:0]));for(const n of Object.keys(this.stages))this.transitions.delete(n);this.cockpitView.setVisionMode(this.cockpitView.visionMode)}}_revealCockpitStyleParameters({openDisplay:t=!1}={}){var n,i,o,r,s;if(!(!((n=this.cockpitView)!=null&&n.active)||!((i=this._sliderPanel)!=null&&i.classList.contains("active")))){if(t&&((o=this._cockpitDisplayToggleBtn)==null?void 0:o.getAttribute("aria-expanded"))!=="true"){(r=this._setCockpitDisclosure)==null||r.call(this,"display",!0);return}((s=this._cockpitDisplayToggleBtn)==null?void 0:s.getAttribute("aria-expanded"))==="true"&&(this._sliderPanel.classList.remove("collapsed"),this._syncPanelCollapseButton(this._sliderPanel),this._lifetime.frame(()=>this._lifetime.frame(()=>{var a,c;(c=(a=this._sliderPanel)==null?void 0:a.scrollIntoView)==null||c.call(a,{block:"nearest"})})))}}_initBloomSharpen(){this._visualEffects.initPostProcess(this._sharpenSlider?parseInt(this._sharpenSlider.value,10)/100:.6)}_getBloomIntensity(){return this._visualEffects.bloomIntensity}_syncBloomStageEnabled(){this._visualEffects.syncBloomEnabled()}_setBloomIntensity(t,{syncShare:n=!0}={}){const{governorRequestRender:i}=this.services;i("bloom");const o=Ni(t);this._bloomSlider&&(this._bloomSlider.value=String(o)),this._bloomSliderValue&&(this._bloomSliderValue.textContent=`${o}%`),this._applyBloomIntensity(o),n&&this._syncShareState()}_applyBloomIntensity(t){this._visualEffects.applyBloomIntensity(t)}_setBloomEnabled(t){const{governorRequestRender:n}=this.services;n("bloom"),this._visualEffects.setBloomEnabled(t),this._syncBloomStageEnabled(),this._bloomBtn.classList.toggle("active",this.bloomEnabled),this._bloomSliderRow.classList.toggle("visible",this.bloomEnabled),this.bloomEnabled&&this._applyBloomIntensity(this._getBloomIntensity()),this._syncShareState(),this._layoutRightPanels()}_applySharpenIntensity(t){this._visualEffects.applySharpenIntensity(t)}_setSharpenEnabled(t){const{governorRequestRender:n}=this.services;n("sharpen"),this._visualEffects.setSharpenEnabled(t),this._sharpenBtn.classList.toggle("active",this.sharpenEnabled),this._sharpenSliderRow&&this._sharpenSliderRow.classList.toggle("visible",this.sharpenEnabled),this.sharpenEnabled&&this._sharpenSlider&&this._applySharpenIntensity(parseInt(this._sharpenSlider.value,10)/100),this._syncShareState(),this._layoutRightPanels()}_applyDetectionDensityFromUi(){const{getDetectionMode:t,setDetectionTuning:n}=this.services;if(!this._detectionDensitySlider)return;const i=wt(this._detectionDensitySlider.value);this._detectionDensitySlider.value=String(i),this._detectionDensityValue&&(this._detectionDensityValue.textContent=`${i}%`),n({densityPct:i}),this._updateDetectionButton(t())}_applyDetectionFadeFromUi(){var r,s,a,c;const{setKeyholeFadeTuning:t}=this.services,n=Math.max(0,Math.min(40,Math.round(Number((r=this._detectionFadeSlider)==null?void 0:r.value)||0))),i=(s=this._detectionOpacitySlider)==null?void 0:s.value,o=Math.max(0,Math.min(100,Math.round(i==null?3:Number(i)||0)));this._detectionFadeSlider&&(this._detectionFadeSlider.value=String(n)),this._detectionFadeValue&&(this._detectionFadeValue.textContent=`${n}%`),this._detectionOpacitySlider&&(this._detectionOpacitySlider.value=String(o)),this._detectionOpacityValue&&(this._detectionOpacityValue.textContent=`${o}%`),t({fadeRatio:n/100,outsideOpacity:o/100}),(c=(a=this.viewer.scene).requestRender)==null||c.call(a)}_setDetectionAllocation(t,{syncShare:n=!0,persist:i=!0}={}){const{setDetectionTuning:o}=this.services,r=String(t||"").trim().toUpperCase();if(!Hl.includes(r))return!1;const s=xo(r);this._detectionAllocationPreference=s,o({allocationStrategy:s});for(const a of this._detectionAllocationBtns){const c=a.dataset.allocation===s;a.classList.toggle("active",c),a.setAttribute("aria-checked",String(c))}if(i)try{localStorage.setItem(y0,s)}catch{}return n&&this._syncShareState(),!0}_syncDetectionUiFromEngine(){const{getKeyholeFadeTuning:t,getDetectionTuning:n,getDetectionMode:i}=this.services,o=n();this._detectionDensitySlider&&(this._detectionDensitySlider.value=String(o.densityPct)),this._detectionDensityValue&&(this._detectionDensityValue.textContent=`${o.densityPct}%`),this._setDetectionAllocation(o.allocationStrategy,{syncShare:!1,persist:!1});const r=t();this._detectionFadeSlider&&(this._detectionFadeSlider.value=String(Math.round(r.fadeRatio*100))),this._detectionOpacitySlider&&(this._detectionOpacitySlider.value=String(Math.round(r.outsideOpacity*100))),this._applyDetectionFadeFromUi(),this._updateDetectionButton(i())}_setDetectionMode(t){const{setDetectionModeByLabel:n}=this.services;t&&(n(t),this._syncDetectionUiFromEngine(),this._syncShareState())}_setHudVariant(t){t&&(this.hud.setVariant(t),this._hudLayoutSelect&&this._hudLayoutSelect.value!==this.hud.getVariant()&&(this._hudLayoutSelect.value=this.hud.getVariant()),this._syncShareState(),this._scheduleAdaptivePanelLayout({settle:!0}))}_applyStylePresetDefaults(t){const{governorRequestRender:n}=this.services,i=h0[t];if(!i)return;if(i.styleParams&&typeof i.styleParams=="object")for(const[s,a]of Object.entries(i.styleParams)){const c=this.stages[s];if(!(!c||!a||typeof a!="object"))for(const[l,u]of Object.entries(a))c.uniforms[l]!==void 0&&(c.uniforms[l]=u,n("style-param"))}const o=i.bloom||{};typeof o.intensity=="number"&&this._bloomSlider&&this._setBloomIntensity(Ni(o.intensity),{syncShare:!1}),typeof o.enabled=="boolean"&&this._setBloomEnabled(o.enabled);const r=i.sharpen||{};if(typeof r.intensity=="number"&&this._sharpenSlider){const s=Math.max(0,Math.min(100,Math.round(r.intensity)));this._sharpenSlider.value=String(s),this._sharpenSliderValue.textContent=`${s}%`,this._applySharpenIntensity(s/100)}typeof r.enabled=="boolean"&&this._setSharpenEnabled(r.enabled),i.hudVariant&&this._setHudVariant(i.hudVariant),typeof i.hudVisible=="boolean"&&(this.hud.setMode(i.hudVisible?"on":"off"),this._updateHudButtonState()),i.detection&&!this._detectionUserOverridden&&this._applyDetectionPreset(i.detection)}_applyDetectionPreset(t){if(t){if(typeof t.densityPct=="number"&&this._detectionDensitySlider){const n=wt(t.densityPct);this._detectionDensitySlider.value=String(n),this._detectionDensityValue&&(this._detectionDensityValue.textContent=`${n}%`),this._applyDetectionDensityFromUi()}t.mode&&this._setDetectionMode(String(t.mode).toUpperCase())}}_applyGlobalPostDefaults(){const t=Tz;if(this._bloomSlider&&this._setBloomIntensity(Ni(t.bloom.intensity),{syncShare:!1}),this._setBloomEnabled(t.bloom.enabled),this._sharpenSlider){const n=Math.max(0,Math.min(100,Math.round(t.sharpen.intensity)));this._sharpenSlider.value=String(n),this._sharpenSliderValue.textContent=`${n}%`,this._applySharpenIntensity(n/100)}if(this._setSharpenEnabled(t.sharpen.enabled),this._setHudVariant(t.hudVariant),this.hud.setMode("on"),this._updateHudButtonState(),t.detectionMode&&this._setDetectionMode(t.detectionMode),typeof t.detectionDensity=="number"&&this._detectionDensitySlider){const n=wt(t.detectionDensity);this._detectionDensitySlider.value=String(n),this._detectionDensityValue.textContent=`${n}%`,this._applyDetectionDensityFromUi()}this._setDetectionAllocation(this._detectionAllocationPreference||t.detectionAllocation,{syncShare:!1,persist:!1}),this._detectionFadeSlider&&(this._detectionFadeSlider.value=String(t.detectionFadePct)),this._detectionOpacitySlider&&(this._detectionOpacitySlider.value=String(t.detectionOutsideOpacityPct)),this._applyDetectionFadeFromUi(),this.setCelestialRingEnabled(t.celestialRing,{syncShare:!1,focus:!1})}_shareableDetectionState(){var n;const{getDetectionMode:t}=this.services;return Xz({owned:this._contactsDetectionRestore,liveMode:t(),liveDensityPct:parseInt(((n=this._detectionDensitySlider)==null?void 0:n.value)||"50",10)})}_readShareState(){var s,a,c,l,u;const{getDetectionTuning:t,isScopeMaskEnabled:n,getScopeMaskFeather:i,getScopeTerminusOverride:o}=this.services,r=this._shareableDetectionState();return{bloomEnabled:this.bloomEnabled,sharpenEnabled:this.sharpenEnabled,options:{bloomIntensity:this._getBloomIntensity(),bloomVersion:ti,sharpenIntensity:parseInt(((s=this._sharpenSlider)==null?void 0:s.value)||"49",10),hudVariant:this.hud.getVariant(),hudVisible:this.hud.visible,detectionMode:r.mode,detectionDensity:r.densityPct,detectionAllocation:t().allocationStrategy,detectionFadePct:parseInt(((a=this._detectionFadeSlider)==null?void 0:a.value)||"7",10),detectionOutsideOpacityPct:parseInt(((c=this._detectionOpacitySlider)==null?void 0:c.value)||"1",10),celestialRingEnabled:this.celestialRingEnabled,scopeEnabled:n(),scopeFeatherPct:Math.round(i()*100),scopeTerminusPct:o()==null?null:Math.round(o()*100),mapStack:((u=(l=this.mapStackController)==null?void 0:l.getActiveId)==null?void 0:u.call(l))||"photoreal"}}}getDetectionState(){var o,r;const{getDetectionTuning:t,getDetectionMode:n}=this.services,i=this._detectionDensitySlider?parseInt(this._detectionDensitySlider.value,10):null;return{detectionMode:n(),densityPct:i,allocationStrategy:t().allocationStrategy,fadePct:parseInt(((o=this._detectionFadeSlider)==null?void 0:o.value)||"7",10),outsideOpacityPct:parseInt(((r=this._detectionOpacitySlider)==null?void 0:r.value)||"0",10)}}getDetectionDiagnostics(){const{readDetectionDiagnostics:t}=this.services;return t()}setDetection({enabled:t,mode:n,densityPct:i,allocationStrategy:o,fadePct:r,outsideOpacityPct:s}={}){var f,p,g;const{getDetectionMode:a,setDetectionModeByLabel:c}=this.services;if(t!==void 0&&typeof t!="boolean")return{ok:!1,error:`Invalid detection enabled value: ${t}`,...this.getDetectionState()};let l=null;if(typeof n=="string"&&n.trim()&&(l=Uf(n),!l))return{ok:!1,error:`Unknown detection mode: ${n}`,...this.getDetectionState()};let u=null;if(i!=null){if(!Number.isFinite(Number(i)))return{ok:!1,error:`Invalid density: ${i}`,...this.getDetectionState()};u=wt(Number(i))}if(l&&l!=="OFF"&&u!=null&&Eo(u)!==l)return{ok:!1,error:`Detection mode ${l} conflicts with density ${u}%`,...this.getDetectionState()};let h=null;return o!=null&&(h=String(o).trim().toUpperCase(),!Hl.includes(h))?{ok:!1,error:`Unknown allocation strategy: ${o}`,...this.getDetectionState()}:r!=null&&!Number.isFinite(Number(r))?{ok:!1,error:`Invalid fade distance: ${r}`,...this.getDetectionState()}:s!=null&&!Number.isFinite(Number(s))?{ok:!1,error:`Invalid outside opacity: ${s}`,...this.getDetectionState()}:((typeof t=="boolean"||l!==null||u!==null||h!==null||r!=null||s!=null)&&((p=(f=this.shareLinkManager)==null?void 0:f.claimRestoreLane)==null||p.call(f,"visual"),this._detectionUserOverridden=!0),h&&this._setDetectionAllocation(h,{syncShare:!1}),r!=null&&this._detectionFadeSlider&&(this._detectionFadeSlider.value=String(Math.max(0,Math.min(40,Math.round(Number(r)))))),s!=null&&this._detectionOpacitySlider&&(this._detectionOpacitySlider.value=String(Math.max(0,Math.min(100,Math.round(Number(s)))))),(r!=null||s!=null)&&this._applyDetectionFadeFromUi(),l&&l!=="OFF"&&u==null&&(u=$l(l)),u!=null&&this._detectionDensitySlider&&(this._detectionDensitySlider.value=String(u),this._applyDetectionDensityFromUi()),t===!1||l==="OFF"?c("OFF"):l?c(l):t===!0&&a()==="OFF"&&c(Eo(u??((g=this._detectionDensitySlider)==null?void 0:g.value)??50)),this._syncDetectionUiFromEngine(),this._syncShareState(),{ok:!0,...this.getDetectionState()})}setBloom({enabled:t,intensityPct:n}={}){var r,s;const i=()=>({enabled:!!this.bloomEnabled,intensityPct:this._bloomSlider?parseInt(this._bloomSlider.value,10):null});return t!==void 0&&typeof t!="boolean"?{ok:!1,error:`Invalid bloom enabled value: ${t}`,bloom:i()}:n!==void 0&&(typeof n!="number"||!Number.isFinite(n))?{ok:!1,error:`Invalid bloom intensity: ${n}`,bloom:i()}:((n!==void 0||t!==void 0)&&((s=(r=this.shareLinkManager)==null?void 0:r.claimRestoreLane)==null||s.call(r,"visual")),n!==void 0&&this._setBloomIntensity(Math.round(Math.max(0,Math.min(200,n)))),t!==void 0&&this._setBloomEnabled(t),{ok:!0,bloom:i()})}setSharpen({enabled:t,intensityPct:n}={}){var r,s;const i=()=>({enabled:!!this.sharpenEnabled,intensityPct:this._sharpenSlider?parseInt(this._sharpenSlider.value,10):null});if(t!==void 0&&typeof t!="boolean")return{ok:!1,error:`Invalid sharpen enabled value: ${t}`,sharpen:i()};if(n!==void 0&&(typeof n!="number"||!Number.isFinite(n)))return{ok:!1,error:`Invalid sharpen intensity: ${n}`,sharpen:i()};if((n!==void 0||t!==void 0)&&((s=(r=this.shareLinkManager)==null?void 0:r.claimRestoreLane)==null||s.call(r,"visual")),n!==void 0){const a=Math.round(Math.max(0,Math.min(100,n)));this._sharpenSlider&&(this._sharpenSlider.value=String(a)),this._sharpenSliderValue&&(this._sharpenSliderValue.textContent=`${a}%`),this._applySharpenIntensity(a/100),this._syncShareState()}return t!==void 0&&this._setSharpenEnabled(t),{ok:!0,sharpen:i()}}get celestialRingEnabled(){var t;return!!((t=this.celestialRing)!=null&&t.enabled)}setCelestialRingEnabled(t,{syncShare:n=!0,focus:i=!1}={}){var l,u,h,d,f,p;const{isCelestialRingStyleSupported:o}=this.services,r=o(this.activeStyle),s=()=>{var g;return{enabled:this.celestialRingEnabled,visible:!!((g=this.celestialRing)!=null&&g.visible)}};if(typeof t!="boolean")return{ok:!1,celestialRing:s(),cameraFocused:!1,error:`Invalid celestial ring enabled value: ${t}`};if(typeof n!="boolean"||typeof i!="boolean")return{ok:!1,celestialRing:s(),cameraFocused:!1,error:"Celestial ring options must be boolean"};if(!r&&t)return{ok:!1,celestialRing:s(),cameraFocused:!1,error:"Celestial ring is available only in Normal style"};n&&((u=(l=this.shareLinkManager)==null?void 0:l.claimRestoreLane)==null||u.call(l,"visual"));const a=r&&t;(h=this.celestialRing)==null||h.setEnabled(a),(d=this._celestialBtn)==null||d.classList.toggle("active",a),(f=this._celestialBtn)==null||f.setAttribute("aria-pressed",String(a)),this._celestialBtn&&(this._celestialBtn.disabled=!r,this._celestialBtn.setAttribute("aria-disabled",String(!r)),this._celestialBtn.title=r?"Celestial ring — reveal the full globe":"Celestial ring — available in Normal style");let c=!1;return a&&i&&(c=!!((p=this.celestialRing)!=null&&p.focusFullGlobe())),n&&this._syncShareState(),{ok:r||!t,celestialRing:s(),cameraFocused:c}}getVisualState(){var s,a,c,l,u,h;const{getDetectionTuning:t,getDetectionMode:n,isScopeMaskEnabled:i,getScopeMaskFeather:o}=this.services,r={};for(const[d,f]of Object.entries(this.stages)){const p=Ir[d];if(p!=null&&p.uniforms){r[d]={};for(const g of Object.keys(p.uniforms))r[d][g]=f.uniforms[g]}}return{style:this.activeStyle,bloom:{enabled:this.bloomEnabled,intensity:this._getBloomIntensity(),version:ti},sharpen:{enabled:this.sharpenEnabled,intensity:parseInt(((s=this._sharpenSlider)==null?void 0:s.value)||"49",10)},hud:{visible:this.hud.visible,variant:this.hud.getVariant()},detection:{mode:n(),density:parseInt(((a=this._detectionDensitySlider)==null?void 0:a.value)||"50",10),allocation:t().allocationStrategy,fadePct:parseInt(((c=this._detectionFadeSlider)==null?void 0:c.value)||"7",10),outsideOpacityPct:parseInt(((l=this._detectionOpacitySlider)==null?void 0:l.value)||"0",10)},scope:{enabled:i(),featherPct:Math.round(o()*100)},mapStack:((h=(u=this.mapStackController)==null?void 0:u.getActiveId)==null?void 0:h.call(u))||"photoreal",styleParams:r}}async applyVisualState(t={},{isCurrent:n=null}={}){var h,d,f,p,g,_,m,b,C,y;const{setScopeMaskEnabled:i,setScopeMaskFeather:o}=this.services,r=()=>typeof n=="function"&&!n();if(r())return!1;t.style&&t.style!==this.activeStyle&&this.setStyle(t.style,{applyPreset:!1});const s=t.bloom||{};if(typeof s.intensity=="number"&&this._bloomSlider){const v=ca(s.intensity,s.version??t.bloomVersion??ti);this._setBloomIntensity(v,{syncShare:!1})}typeof s.enabled=="boolean"&&this._setBloomEnabled(s.enabled);const a=t.sharpen||{};if(typeof a.intensity=="number"&&this._sharpenSlider){const v=Math.max(0,Math.min(100,Math.round(a.intensity)));this._sharpenSlider.value=String(v),this._sharpenSliderValue.textContent=`${v}%`,this._applySharpenIntensity(v/100)}typeof a.enabled=="boolean"&&this._setSharpenEnabled(a.enabled);const c=t.hud||{};c.variant&&this._setHudVariant(c.variant),typeof c.visible=="boolean"&&(this.hud.setMode(c.visible?"on":"off"),this._updateHudButtonState());const l=t.scope||{};if(typeof l.enabled=="boolean"&&(i(l.enabled),(h=this._scopeBtn)==null||h.classList.toggle("active",l.enabled),(d=this._scopeBtn)==null||d.setAttribute("aria-pressed",String(l.enabled))),typeof l.featherPct=="number"&&this._scopeFeatherSlider){const v=Math.max(0,Math.min(100,Math.round(l.featherPct)));this._scopeFeatherSlider.value=String(v),this._scopeFeatherValue&&(this._scopeFeatherValue.textContent=`${v}%`),o(v/100)}const u=t.detection||{};if(typeof u.density=="number"&&this._detectionDensitySlider){const v=wt(u.density);this._detectionDensitySlider.value=String(v),this._detectionDensityValue&&(this._detectionDensityValue.textContent=`${v}%`),this._applyDetectionDensityFromUi()}if(u.allocation&&this._setDetectionAllocation(u.allocation,{syncShare:!1}),typeof u.fadePct=="number"&&this._detectionFadeSlider&&(this._detectionFadeSlider.value=String(u.fadePct)),typeof u.outsideOpacityPct=="number"&&this._detectionOpacitySlider&&(this._detectionOpacitySlider.value=String(u.outsideOpacityPct)),this._applyDetectionFadeFromUi(),u.mode&&this._setDetectionMode(u.mode),t.mapStack){if(r())return!1;const v=((p=(f=this.mapStackController)==null?void 0:f.getActiveId)==null?void 0:p.call(f))??null,M=((_=(g=this.mapStackController)==null?void 0:g.getSwitchGeneration)==null?void 0:_.call(g))??null;if(await this._setMapStack(t.mapStack,{syncShare:!1}),r()){const w=((b=(m=this.mapStackController)==null?void 0:m.getSwitchGeneration)==null?void 0:b.call(m))??null,E=M!==null&&w!==null&&w<=M+1,k=((y=(C=this.mapStackController)==null?void 0:C.getActiveId)==null?void 0:y.call(C))??null;return E&&v&&k!==v&&await this._setMapStack(v,{syncShare:!1}),!1}}if(t.styleParams&&typeof t.styleParams=="object"){for(const[v,M]of Object.entries(t.styleParams)){const w=this.stages[v];if(!(!w||!M))for(const[E,k]of Object.entries(M))w.uniforms[E]!==void 0&&(w.uniforms[E]=k)}this._updateSliderPanel(this.activeStyle)}return this._syncShareState(),!0}applyCinematicPreset(t={}){const n=typeof t.bloom=="object"?t.bloom:{intensity:t.bloom};let i=null;typeof n.intensity=="number"&&(i=ca(n.intensity,n.version??t.bloomVersion??ti),this._setBloomIntensity(i,{syncShare:!1})),typeof n.enabled=="boolean"?this._setBloomEnabled(n.enabled):typeof n.intensity=="number"&&this._setBloomEnabled((i??this._getBloomIntensity())>0);const o=typeof t.sharpen=="object"?t.sharpen:{enabled:t.sharpen};if(typeof o.intensity=="number"&&this._sharpenSlider){const r=Math.max(0,Math.min(100,Math.round(o.intensity)));this._sharpenSlider.value=String(r),this._sharpenSliderValue.textContent=`${r}%`,this._applySharpenIntensity(r/100)}if(typeof o.enabled=="boolean"?this._setSharpenEnabled(o.enabled):typeof o.intensity=="number"&&this._setSharpenEnabled(o.intensity>0),t.hudVariant&&this._setHudVariant(t.hudVariant),t.detectionMode&&this._setDetectionMode(t.detectionMode),typeof t.detectionDensity=="number"&&this._detectionDensitySlider){const r=wt(t.detectionDensity);this._detectionDensitySlider.value=String(r),this._detectionDensityValue.textContent=`${r}%`,this._applyDetectionDensityFromUi()}if(t.detectionAllocation&&this._setDetectionAllocation(t.detectionAllocation,{syncShare:!1}),t.styleParams&&typeof t.styleParams=="object"){for(const[r,s]of Object.entries(t.styleParams)){const a=this.stages[r];if(!(!a||!s||typeof s!="object"))for(const[c,l]of Object.entries(s))a.uniforms[c]!==void 0&&(a.uniforms[c]=l)}this._updateSliderPanel(this.activeStyle)}this._syncShareState()}_updateSliderPanel(t,{reveal:n=!1}={}){const{governorRequestRender:i}=this.services;this._styleParameters||(this._styleParameters=zz({container:this._sliderContainer})),this._styleParameters.clear();const o=Ir[t];if(!o||!o.uniforms||t==="normal"){this._sliderPanel.classList.remove("active"),this._scheduleRightPanelLayout();return}this._styleParameters.render({uniforms:o.uniforms,readValue:r=>this.stages[t].uniforms[r],writeValue:(r,s)=>{var a,c;(c=(a=this.shareLinkManager)==null?void 0:a.claimRestoreLane)==null||c.call(a,"visual"),this.stages[t].uniforms[r]=s},onChange:()=>{i("style-param-slider"),this._syncShareState()}}),this._sliderPanel.classList.add("active"),this._scheduleRightPanelLayout(),n&&this._revealStyleParameters()}_revealStyleParameters(){var t;(t=this._sliderPanel)!=null&&t.classList.contains("active")&&(this._cockpitDisplayPortalActive||(this._sliderPanel.classList.remove("collapsed"),this._syncPanelCollapseButton(this._sliderPanel),this.setPanelCollapsed("pp-toggles",!1,{explicit:!0}),this._lifetime.frame(()=>this._lifetime.frame(()=>{const n=this._ppToggles;if(!n)return;const i=n.getBoundingClientRect(),o=this._sliderPanel.getBoundingClientRect();n.scrollTop+=o.top-i.top-8}))))}setStyle(t,{applyPreset:n=!0,revealParameters:i=n,restore:o=!1}={}){var c,l;const{setDetectionStyle:r}=this.services;if(o||(l=(c=this.shareLinkManager)==null?void 0:c.claimRestoreLane)==null||l.call(c,"visual"),t===this.activeStyle){i&&t!=="normal"&&this._revealStyleParameters();return}const s=this.activeStyle;this.activeStyle=t,document.documentElement.dataset.gevStyle=t,this.setCelestialRingEnabled(!1,{syncShare:!1,focus:!1}),s!=="normal"&&this.stages[s]&&this._startTransition(s,this.stages[s].uniforms.intensity,0),t!=="normal"&&this.stages[t]&&this._startTransition(t,this.stages[t].uniforms.intensity,1),n&&this._applyStylePresetDefaults(t),document.querySelectorAll(".style-btn").forEach(u=>{u.classList.toggle("active",u.dataset.style===t)});const a={surveillance:"NVG",thermal:"FLIR",retro:"CRT"};this._styleIndicator.textContent=a[t]||t.toUpperCase(),this._updateStyleMiniStatus(t),this._updateSliderPanel(t,{reveal:i}),this.hud.onStyleChange(t),this._updateHudButtonState(),r(t),this._syncIrBoost(),window.dispatchEvent(new CustomEvent("gev:style-change",{detail:{style:t}})),this._syncCockpitInheritedStyle(),this.shareLinkManager.onStyleChange(t),this._syncShareState()}_startTransition(t,n,i){this._visualEffects.startTransition(t,n,i)}_updateStyleMiniStatus(t=this.activeStyle){this._styleMiniValue&&(this._styleMiniValue.textContent=WE[t]||String(t||"normal").toUpperCase())}_updateHudButtonState(){this._hudBtn.classList.toggle("active",this.hud.visible),this._hudLayoutRow&&this._hudLayoutRow.classList.toggle("visible",this.hud.visible),this._scheduleAdaptivePanelLayout({settle:!0})}_updateDetectionButton(t){const n=this._detectionBtn,i=t!=="OFF";n.setAttribute("aria-pressed",String(i)),n.setAttribute("aria-label",i?`Detection overlay: ${String(t).toLowerCase()}`:"Detection overlay: off"),n.classList.remove("active","god","panoptic"),t==="SPARSE"?(n.querySelector(".pp-label").textContent="SPARSE",n.classList.add("active")):t==="BALANCED"?(n.querySelector(".pp-label").textContent="BALANCED",n.classList.add("active")):t==="DENSE"?(n.querySelector(".pp-label").textContent="DENSE",n.classList.add("active","panoptic")):n.querySelector(".pp-label").textContent="DETECT",this._detectionSliderRow&&this._detectionSliderRow.classList.toggle("visible",t!=="OFF"),this._detectionAllocationRow&&this._detectionAllocationRow.classList.toggle("visible",t!=="OFF"),this._detectionFadeRow&&this._detectionFadeRow.classList.toggle("visible",t!=="OFF"),this._detectionOpacityRow&&this._detectionOpacityRow.classList.toggle("visible",t!=="OFF"),this._layoutRightPanels()}stop(){var t;this._lifetime.destroy(),(t=this._styleParameters)==null||t.destroy(),this._visualEffects.stop()}releaseIrBoost(){var t,n,i,o;this._irBoostActive&&(this._irFogWasEnabled!=null&&((n=(t=this.viewer)==null?void 0:t.scene)!=null&&n.fog)&&(this.viewer.scene.fog.enabled=this._irFogWasEnabled),(i=this._dataManager)==null||i.setLayerParams("flights",{irBoost:!1}),(o=this._dataManager)==null||o.setLayerParams("military",{irBoost:!1}),this._irBoostActive=!1,this._irFogWasEnabled=null)}destroy(){this.stop(),this.releaseIrBoost(),this._visualEffects.destroy()}}class Jz{constructor({viewer:t,tracking:n,searchInput:i,interruptCameraMotion:o,isCockpitActive:r,clearLocation:s,cancelShareSelection:a,getDataManager:c,stopOrbit:l,showToast:u,cancelOrientation:h=()=>{}}){Object.assign(this,{viewer:t,tracking:n,searchInput:i,interruptCameraMotion:o,isCockpitActive:r,clearLocation:s,cancelShareSelection:a,getDataManager:c,stopOrbit:l,showToast:u,cancelOrientation:h}),this._navigationGeneration=0,this._activeLocationSearchGeneration=null,this._disposed=!1}_stampNavigation({cancelPendingSelection:t=!0,clearSearchedLocation:n=!0}={}){var s,a,c,l,u,h,d,f,p;this.cancelOrientation();const{flightsLayer:i,militaryFlightsLayer:o,satellitesLayer:r}=this.tracking;if(this._navigationGeneration+=1,n&&this.clearLocation(),t){const g=this.cancelShareSelection();try{(s=i.cancelPendingTrackingRestore)==null||s.call(i)}catch{}try{(a=o.cancelPendingTrackingRestore)==null||a.call(o)}catch{}try{(c=r.cancelPendingTrackingRestore)==null||c.call(r)}catch{}!g&&!((l=i.getTrackedInfo)!=null&&l.call(i))&&((u=this.getDataManager())==null||u.setLayerParams("flights",{selectedFlightsTrackingId:null},{origin:"tool"})),!g&&!((h=o.getTrackedInfo)!=null&&h.call(o))&&((d=this.getDataManager())==null||d.setLayerParams("military",{selectedMilitaryTrackingId:null},{origin:"tool"})),!g&&!((f=r.getTrackedInfo)!=null&&f.call(r))&&((p=this.getDataManager())==null||p.setLayerParams("satellites",{selectedSatTrackingId:null},{origin:"tool"}))}return this._activeLocationSearchGeneration!==null&&this._settleLocationSearchUi(this._activeLocationSearchGeneration),this._navigationGeneration}_settleLocationSearchUi(t){var n,i;this._activeLocationSearchGeneration===t&&(this._activeLocationSearchGeneration=null,(n=this.searchInput)==null||n.classList.remove("searching","expanded"),this.searchInput&&(this.searchInput.value=""),(i=this.searchInput)==null||i.blur())}_releaseFollowCamera({preserveVesselSelection:t=!0,preserveCameraFlight:n=!1,trackingOrigin:i="tool"}={}){var h,d,f,p,g,_;const{flightsLayer:o,militaryFlightsLayer:r,satellitesLayer:s,aisLiveVesselsLayer:a,militaryAwarenessLayer:c,rocketLaunchesLayer:l}=this.tracking;let u=!1;try{u=!!((h=c.releaseCameraOwnership)!=null&&h.call(c,{preserveVesselSelection:t,origin:i}))}catch{try{(d=o.stopTracking)==null||d.call(o,{origin:i})}catch{}try{(f=r.stopTracking)==null||f.call(r,{origin:i})}catch{}if(!t)try{(p=a.clearSelection)==null||p.call(a)}catch{}}try{(g=s.stopTracking)==null||g.call(s,{origin:i})}catch{}try{(_=l.releaseCameraOwnership)==null||_.call(l)}catch{}this.viewer.trackedEntity=void 0,this.interruptCameraMotion("explicit-navigation"),this.stopOrbit(),n||this.viewer.camera.cancelFlight();try{this.viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY)}catch{}return u}_runExplicitNavigation(t,n,i=void 0){return zh({disposed:this._disposed,cockpitActive:this.isCockpitActive(),noun:t,showToast:o=>this.showToast(o),stamp:()=>this._stampNavigation(),release:()=>this._releaseFollowCamera(i),navigate:n})}runOrientation(t,n){return zh({disposed:this._disposed,cockpitActive:this.isCockpitActive(),noun:t,showToast:i=>this.showToast(i),stamp:()=>this._stampNavigation({cancelPendingSelection:!1,clearSearchedLocation:!1}),release:()=>{this.interruptCameraMotion("camera-orientation"),this.stopOrbit(),this.viewer.camera.cancelFlight()},navigate:n})}_beginDeferredNavigation(t="location",{cancelPendingSelection:n=!0}={}){return AE({disposed:this._disposed,cockpitActive:this.isCockpitActive(),noun:t,showToast:i=>this.showToast(i),stamp:()=>this._stampNavigation({cancelPendingSelection:n,clearSearchedLocation:!1})})}_reassertNavigationHandoff(t){return IE({generation:t,currentGeneration:this._navigationGeneration,cockpitActive:this.isCockpitActive(),disposed:this._disposed,showToast:n=>this.showToast(n),release:()=>(this.clearLocation(),this._releaseFollowCamera())})}stop(){this._disposed=!0}destroy(){this.stop(),this._stampNavigation()}}const e8=160,t8=2200,Wm=5e3,n8=3e4,i8=1500,vc=Object.freeze(["zoom-in","empty","idle"]);function o8(e){const t=Number(e);return Number.isFinite(t)&&t>=0?t:0}function r8(e={}){const t=e.stats||{},n=String(e.lifecycleState||(e.enabled?"enabled":"disabled")),i=String(t.status||"").toLowerCase(),o=n==="disabling",r=n==="enabling"||o||t.loading===!0||t.refreshing===!0,s=o8(t.count),a=["military-installations","alpr-cameras"].includes(e.id)&&o,c=vc.includes(i),l=a?null:!c&&t.error||t.lastError||t.managerRefreshError||null,u=!a&&(t.unavailable===!0||t.available===!1||["unavailable","offline","down","error"].includes(i)),h=t.keyRequired===!0||t.missingKey===!0,d=t.degraded===!0||!!l,f=!!t.lastUpdate||s>0;return{id:String(e.id||""),label:String(e.name||e.id||"Layer"),loading:r,disabling:o,refresh:r&&e.enabled&&(t.refreshing===!0||f),lifecycleState:n,count:s,accepted:f,error:l,unavailable:u,keyRequired:h,degraded:d,cameraRetry:e.id==="alpr-cameras"&&e.enabled&&!o?{retryAt:Number(t.retryAt)||0,retrying:t.retrying===!0,error:l}:null,installationRetry:e.id==="military-installations"&&e.enabled&&!o?{retryAt:Number(t.retryAt)||0,retrying:t.retrying===!0,failureReason:t.failureReason,loading:r,status:t.status}:null}}function v0(e,t){if(!(t!=null&&t.length))return null;const n=new Set(t);return e.records.some(i=>n.has(i.id)&&(i.error||i.unavailable||i.keyRequired))?"error":null}function s8(e=[]){const t=e.map(r8),n=t.filter(o=>o.loading),i=n.length>0&&n.every(o=>o.disabling);return{records:t,active:n,activeIds:n.map(o=>o.id),disabling:i,refresh:!i&&n.length>0&&n.every(o=>o.refresh)}}function yl(){return{phase:"idle",visible:!1,startedAt:0,showAt:0,hideAt:0,activeIds:[],batchOutcome:null,terminal:null,operation:null}}function a8(e,t=0,{state:n="error",detail:i="",persistent:o=!1}={}){const r=String(e||"").trim();return r?{state:n,label:r,detail:String(i||"").trim(),persistent:!!o,dwellMs:o?null:Wm,hideAt:null}:null}function l8(e,t=0){const n=Number.isFinite(t)?t:0;return!(e!=null&&e.label)||(!e.persistent&&!Number.isFinite(e.hideAt)&&(e.hideAt=n+(Number.isFinite(e.dwellMs)?e.dwellMs:Wm)),Number.isFinite(e.hideAt)&&n>=e.hideAt)?null:{state:e.state||"error",label:e.label,detail:e.detail||""}}function M0(e,t,n=!1){return!n&&Number.isSafeInteger(e)&&e===t}function c8(e,t,n,i=0){const o=h8(t,n,i);return["error","retry"].includes(o==null?void 0:o.state)?o:l8(e,i)||o}function tf(){return{busy:!1,visible:!1,confirmationUntil:0,label:"",progressText:""}}function u8(e,{enabled:t=!1,stats:n={},forceShow:i=!1}={},o=0){const r=e||tf(),s=Number.isFinite(o)?o:0;if(!t)return tf();const a=Number.isFinite(n.phaseProgressPct),c=a?Math.max(0,Math.min(100,Math.round(n.phaseProgressPct))):n.loading?1:100,l=n.loading===!0||n.worldJumping===!0||a&&(c<100||(n.prewarmQueueDepth??0)>0),u=String(n.phaseLabel||n.loadingLabel||"").trim();if(l)return{busy:!0,visible:!0,confirmationUntil:0,label:u||"syncing road network",progressText:a?`${c}%`:"..."};const d=(r.confirmationUntil>s?r.confirmationUntil:0)||(r.busy||i?s+i8:0),f=d>s&&c>=100&&!!u;return{busy:!1,visible:f,confirmationUntil:f?d:0,label:f?u:"",progressText:""}}function Ka(e){const t=String((e==null?void 0:e.type)||"");return t==="visibility-failed"||t==="refresh-failed"||e!=null&&e.error?"error":t==="visibility-cancelled"||e!=null&&e.cancelled?"cancelled":t==="visibility"||t==="refresh"?"complete":null}function Ya(e,t){const n={complete:1,cancelled:2,error:3};return t?!e||n[t]>n[e]?t:e:e||null}function d8(e,t,n,i=null){const o=e||yl(),r=Number.isFinite(n)?n:0;if(t.active.length){const s=o.phase!=="loading",a=s?r:o.startedAt,c=s?[]:o.activeIds,l=[...new Set([...c,...t.activeIds])],u=String((i==null?void 0:i.layerId)||""),h=u&&l.includes(u),d=Ya(Ya(s?null:o.batchOutcome,v0(t,l)),h?Ka(i):null);return{phase:"loading",visible:!s&&r>=o.showAt,startedAt:a,showAt:s?r+e8:o.showAt,hideAt:0,activeIds:l,batchOutcome:d,terminal:null,operation:t.disabling?"disabling":t.refresh?"refresh":"loading",failedEventIds:[...new Set([...s?[]:o.failedEventIds||[],...h&&Ka(i)==="error"?[u]:[]])]}}if(o.phase==="loading"){const s=String((i==null?void 0:i.layerId)||""),a=s&&o.activeIds.includes(s),c=Ya(Ya(o.batchOutcome,v0(t,o.activeIds)),a?Ka(i):null)||"complete";return!(o.visible||r>=o.showAt)&&c==="complete"?yl():{...o,phase:"terminal",visible:!0,hideAt:r+(c==="error"?Wm:t8),batchOutcome:c,terminal:c,failedEventIds:[...new Set([...o.failedEventIds||[],...a&&Ka(i)==="error"?[s]:[]])]}}return o.phase==="terminal"&&r{var p;return((p=f.cameraRetry)==null?void 0:p.retryAt)>0}),o=t.records.some(f=>f.id!=="alpr-cameras"&&((e==null?void 0:e.activeIds)||[]).includes(f.id)&&(f.error||f.unavailable||f.keyRequired))||((e==null?void 0:e.failedEventIds)||[]).some(f=>f!=="alpr-cameras");if(i&&!t.active.length&&!o){const f=Math.max(0,Math.ceil((i.cameraRetry.retryAt-Date.now())/1e3));return{state:"retry",label:(i.cameraRetry.error||"Overpass temporarily unavailable").toUpperCase(),detail:`ALPR cameras · ${f?`retrying in ${f}s`:"retry pending"}`}}const r=t.records.find(f=>{var p;return((p=f.installationRetry)==null?void 0:p.retryAt)>0}),s=t.records.some(f=>f.id!=="military-installations"&&((e==null?void 0:e.activeIds)||[]).includes(f.id)&&(f.error||f.unavailable||f.keyRequired))||((e==null?void 0:e.failedEventIds)||[]).some(f=>f!=="military-installations");if(r&&!t.active.length&&!s){const f=mE(r.installationRetry),[p,g]=f.split(" — ");return{state:"retry",label:p.toUpperCase(),detail:g||""}}if(!(e!=null&&e.visible))return null;if(e.phase==="terminal"){const f={complete:"LOAD COMPLETE",cancelled:"LOAD CANCELLED",error:"LOAD FAILED"},p=e.operation==="disabling"&&e.terminal==="complete"?"LIVE DATA OFF":e.terminal==="complete"&&((d=e.activeIds)==null?void 0:d.length)===1&&e.activeIds[0]==="military-installations"?"MAPPED SITES LOADED":f[e.terminal]||"LOAD COMPLETE";return{state:e.terminal,label:p,detail:""}}const a=t.active;if(a.length===1&&a[0].cameraRetry&&!t.disabling)return{state:"loading",label:a[0].cameraRetry.retrying?"RETRYING ALPR CAMERAS":"FETCHING ALPR CAMERAS",detail:"OpenStreetMap · Overpass"};if(a.length===1&&a[0].installationRetry&&!t.disabling)return{state:"loading",label:a[0].installationRetry.retrying?"RETRYING MAPPED SITES":"FETCHING MAPPED SITES",detail:"OpenStreetMap · Overpass"};const c=Math.max(0,n-e.startedAt),l=t.disabling?"TURNING OFF LIVE DATA":t.refresh?"REFRESHING LIVE DATA":"LOADING LIVE DATA",u=a.slice(0,2).map(f=>f.label).join(" · "),h=a.length>2?` +${a.length-2}`:"";return{state:c>=n8?"long":t.disabling?"disabling":t.refresh?"refresh":"loading",label:l,detail:`${u}${h}`}}class f8{constructor({viewer:t,navigation:n,syncShareState:i,syncModels3d:o,showStatus:r,feedback:s,updateFeedback:a}){Object.assign(this,{viewer:t,navigation:n,syncShareState:i,syncModels3d:o,showStatus:r,feedback:s,updateFeedback:a}),this._lifetime=new cu,this._disposed=!1,this._shareTrackingAcquiringKey=null,this._shareTrackingNoticeGeneration=0,this._initialShareState=null,this._initialShareNavigationGeneration=null,this._initialShareRestoreTimeout=null,this._layerStateCoordinator=null,this._layerStateRestorePromise=null}attachLinks(t){this.shareLinkManager=t,this._initialShareState=t.parseInitialHash()}start(){var n,i,o,r;const t=this._initialShareState;this._initialShareRestorePromise=t?new Promise(s=>{this._resolveInitialShareRestore=s}):Promise.resolve({status:"not-requested",share:null,layers:[]}),t?(this._hasShareState=!0,this._initialShareNavigationGeneration=this.navigation._beginDeferredNavigation("shared view",{cancelPendingSelection:!1}),this._initialShareRestoreTimeout=setTimeout(()=>{if(this._initialShareRestoreTimeout=null,this._disposed)return;const s=this._initialShareNavigationGeneration,a=Number.isInteger(s)&&this.navigation._reassertNavigationHandoff(s);(async()=>{var c,l,u,h;try{const d=await this.shareLinkManager.applyState(t,{applyCamera:a,navigationToken:s}),f=await(this._layerStateRestorePromise||Promise.resolve([])),p=d.camera==="applied"?await((l=(c=this._layerStateCoordinator)==null?void 0:c.restoreShareTrackingSelection)==null?void 0:l.call(c)):{status:"superseded",cleared:((h=(u=this._layerStateCoordinator)==null?void 0:u.cancelPendingShareTracking)==null?void 0:h.call(u,"shared-camera-superseded",{clearSelection:!0}))===!0};this.shareLinkManager.completeInitialRestore(),this._settleInitialShareRestore({status:"settled",share:d,layers:f,tracking:p})}catch(d){this.shareLinkManager.completeInitialRestore(),this._settleInitialShareRestore({status:"failed",error:String((d==null?void 0:d.message)||d),share:null,layers:[]})}})()},1500)):this.syncShareState(),this._initialShareGestureHandler=()=>{this._disposed||!this._hasShareState||!this._resolveInitialShareRestore||kE(s=>this.navigation._stampNavigation(s))},(i=(n=this.viewer)==null?void 0:n.canvas)==null||i.addEventListener("pointerdown",this._initialShareGestureHandler,{passive:!0}),(r=(o=this.viewer)==null?void 0:o.canvas)==null||r.addEventListener("wheel",this._initialShareGestureHandler,{passive:!0})}connect(t){var n,i,o;this._dataManager=t,(n=this._layerStateCoordinator)==null||n.destroy(),this._layerStateCoordinator=null,this._layerStateRestorePromise=null,this._dataManager&&(this._layerStateCoordinator=new ey(this._dataManager,this.shareLinkManager,{onDurableStateChange:r=>this.syncModels3d(r),onTrackingRestoreStatus:r=>this._handleShareTrackingRestoreStatus(r)}),this._layerStateRestorePromise=this._layerStateCoordinator.start({shareLayerState:((i=this._initialShareState)==null?void 0:i.layerState)||null,shareCreatedAtMs:((o=this._initialShareState)==null?void 0:o.sharedAtMs)??null,allowLocalState:!this._initialShareState}),this._initialShareSelectionSuperseded&&this._layerStateCoordinator.cancelPendingShareTracking("superseded-before-layer-coordinator-start",{clearSelection:!0}),this._layerStateRestorePromise.then(()=>{var r;this.syncModels3d((r=this._layerStateCoordinator)==null?void 0:r.getDurableState())}))}cancelSelection(){var t,n;return this._hasShareState&&this._resolveInitialShareRestore&&!this._layerStateCoordinator&&(this._initialShareSelectionSuperseded=!0),((n=(t=this._layerStateCoordinator)==null?void 0:t.cancelPendingShareTracking)==null?void 0:n.call(t,"superseded-by-explicit-navigation",{clearSelection:!0}))===!0}get initialRestorePromise(){return this._initialShareRestorePromise||Promise.resolve({status:"not-requested"})}_handleShareTrackingRestoreStatus(t){var c;if(!t||this._disposed)return;const n=`${t.layerId||""}:${t.targetId??""}`;if(t.classification==="pending"){this._shareTrackingNoticeGeneration+=1,this._shareTrackingAcquiringKey=n,this.showStatus("ACQUIRING",{state:"acquiring",detail:`SHARED ${String(t.label||"SUBJECT").toUpperCase()}`,persistent:!0});return}const i=this._shareTrackingAcquiringKey===n;if(i&&(this._shareTrackingNoticeGeneration+=1,this._shareTrackingAcquiringKey=null,((c=this.feedback._globalStatusNotice)==null?void 0:c.state)==="acquiring"&&(this.feedback._globalStatusNotice=null,this.updateFeedback())),t.classification==="followed"||t.classification==="cancelled"||this._shareTrackingAcquiringKey)return;const o=i?this._shareTrackingNoticeGeneration:++this._shareTrackingNoticeGeneration,r=t.label||"entity",s=t.classification==="expired"?`Shared ${r} follow expired`:t.classification==="source-unavailable"?`Shared ${r} could not be restored — feed unavailable`:`Shared ${r} is unavailable`,a=()=>{this._lifetime.frame(()=>{if(!M0(o,this._shareTrackingNoticeGeneration,this._disposed))return;const l=document.getElementById("loading-screen");if(!l||getComputedStyle(l).visibility==="hidden"){this.showStatus(s);return}let u=null,h=()=>{};const d=()=>{h(),u&&this._lifetime.cancelTimeout(u),M0(o,this._shareTrackingNoticeGeneration,this._disposed)&&this.showStatus(s)};h=this._lifetime.listen(l,"transitionend",d,{once:!0}),u=this._lifetime.timeout(d,1e3)})};if(this._resolveInitialShareRestore){this.initialRestorePromise.then(a);return}a()}_settleInitialShareRestore(t){if(!this._resolveInitialShareRestore)return;const n=this._resolveInitialShareRestore;this._resolveInitialShareRestore=null,n(t),window.dispatchEvent(new CustomEvent("gev:initial-share-restore-settled",{detail:t}))}destroy(){var t,n,i,o,r;this._disposed||(this._disposed=!0,this._shareTrackingNoticeGeneration+=1,this._shareTrackingAcquiringKey=null,(t=this._layerStateCoordinator)==null||t.destroy(),this._layerStateCoordinator=null,this._layerStateRestorePromise=null,clearTimeout(this._initialShareRestoreTimeout),this._initialShareRestoreTimeout=null,this._settleInitialShareRestore({status:"destroyed",share:null,layers:[]}),(i=(n=this.viewer)==null?void 0:n.canvas)==null||i.removeEventListener("pointerdown",this._initialShareGestureHandler),(r=(o=this.viewer)==null?void 0:o.canvas)==null||r.removeEventListener("wheel",this._initialShareGestureHandler),this._initialShareGestureHandler=null,this._lifetime.destroy())}}function m8({viewer:e,documentRef:t=document}){var f;const n=t.getElementById("title-bar"),i=(f=e==null?void 0:e.scene)==null?void 0:f.postRender;if(!n||!i)return{destroy(){}};const o=t.createElement("div");o.className="frame-rate-readout",o.hidden=!0,o.textContent="FPS —",o.title="Rendered globe frames per second · toggle with `",n.appendChild(o);let r=null,s=null,a=0,c=0,l=!1;function u(){o.hidden=!0,r==null||r(),r=null,clearInterval(s),s=null}function h(){a=0,c=performance.now(),o.textContent="FPS —",o.hidden=!1,r=i.addEventListener(()=>{a++}),s=setInterval(()=>{const p=performance.now(),g=p-c;o.textContent=t.hidden||g<=0?"FPS —":`FPS ${Math.round(a*1e3/g)}`,a=0,c=p},1e3)}function d(p){var g,_,m;p.key!=="`"&&p.code!=="Backquote"||p.defaultPrevented||p.repeat||p.isComposing||p.ctrlKey||p.altKey||p.metaKey||p.shiftKey||(g=p.target)!=null&&g.isContentEditable||(m=(_=p.target)==null?void 0:_.closest)!=null&&m.call(_,'input, textarea, select, [contenteditable]:not([contenteditable="false"])')||(p.preventDefault(),o.hidden?h():u())}return t.addEventListener("keydown",d),{destroy(){l||(l=!0,u(),t.removeEventListener("keydown",d),o.remove())}}}function Mc(e,t=new Set){if(e===null)return e;if(typeof e!="object"){if(["string","number","boolean","undefined"].includes(typeof e))return e;throw new TypeError("Product state must contain plain data")}if(t.has(e))throw new TypeError("Circular product state");if(!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw new TypeError("Product state must contain plain records");const n=new Set(t).add(e),i=Array.isArray(e)?e.map(o=>Mc(o,n)):Object.fromEntries(Object.entries(e).map(([o,r])=>[o,Mc(r,n)]));return Object.freeze(i)}function wc(e){const t=new Set,n=[];let i=0,o=!1,r=!1,s=null;const a=()=>(r||(s=Mc(e())),s),c=(l,u)=>{try{l.listener(u)}catch{console.error("Product state listener failed")}};return Object.freeze({getSnapshot:a,subscribe(l,{emitCurrent:u=!0}={}){if(typeof l!="function")throw new TypeError("Expected a state listener");if(r)return()=>{};const h=u?a():null,d={listener:l,revision:i};return t.add(d),u&&c(d,Object.freeze({state:h,change:null,revision:i,initial:!0})),()=>t.delete(d)},publish(l=null){if(r)return!1;if(n.push(Object.freeze({state:a(),change:Mc(l),revision:++i,initial:!1})),o)return!0;o=!0;try{for(;!r&&n.length;){const u=n.shift();for(const h of[...t])r||!t.has(h)||h.revision>=u.revision||(h.revision=u.revision,c(h,u))}}finally{o=!1}return!0},destroy(){r||(r=!0,t.clear(),n.length=0)}})}const Km=190,p8=26,g8=620,_8=60,b8=.5,C8="gev-flap-host",ZE="gev-flap-active",w0="gev-flap-text",E0="gev-flap-cells",y8="gev-flap-cell",v8="is-flapping",JE="gev-flap-sizing",nf=" ",ua=new WeakMap,of=new WeakMap;function Gs(e,t){const n=Number(e);return Number.isFinite(n)&&n>0?n:t}function T0(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function M8(e,t,n={}){const i=Gs(n.charMs,Km),o=Gs(n.staggerMs,p8),r=Gs(n.maxTotalMs,g8),s=Array.from(String(e??"")),a=Array.from(String(t??"")),c=Math.max(s.length,a.length);let l=-1,u=-1;for(let _=0;_1?Math.min(o,d/(h-1)):0,p=[];let g=0;for(let _=0;_=c.delayMs+s);return a}function T8(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function k8(e){var n;if(!(e!=null&&e.isConnected))return!1;if(typeof e.checkVisibility=="function")return e.checkVisibility({opacityProperty:!0,visibilityProperty:!0,contentVisibilityAuto:!0});if(typeof e.getClientRects!="function"||e.getClientRects().length===0)return!1;const t=(n=e.ownerDocument)==null?void 0:n.defaultView;if(typeof(t==null?void 0:t.getComputedStyle)!="function")return!0;for(let i=e;i&&i.nodeType===1;i=i.parentElement){const o=t.getComputedStyle(i);if(o.visibility==="hidden"||o.display==="none"||Number(o.opacity)===0)return!1}return!0}function Ec(e){return typeof e.getBoundingClientRect=="function"?e.getBoundingClientRect().width:0}function eT(e){var a,c,l;const t=e.firstElementChild,n=t==null?void 0:t.nextElementSibling;if((a=t==null?void 0:t.classList)!=null&&a.contains(w0)&&((c=t.firstChild)==null?void 0:c.nodeType)===3&&((l=n==null?void 0:n.classList)!=null&&l.contains(E0))&&!n.nextElementSibling)return{text:t,cells:n};const i=e.ownerDocument||globalThis.document,o=e.textContent??"",r=i.createElement("span");r.className=w0,r.append(i.createTextNode(o));const s=i.createElement("span");return s.className=E0,s.setAttribute("aria-hidden","true"),e.classList.add(C8),e.replaceChildren(r,s),{text:r,cells:s}}function Gr(e){var t,n,i;(t=e.classList)==null||t.remove(JE),(n=e.style)==null||n.removeProperty("width"),(i=e.style)==null||i.removeProperty("--gev-flap-total")}function Ur(e){const t=of.get(e);t&&(of.delete(e),t())}function tT(e,t,n,i){if(Ur(e),!(t>.5)||Math.abs(n-t)<=.5)return Gr(e),!1;e.style.setProperty("--gev-flap-total",`${i}ms`),e.style.width=`${t}px`,e.classList.add(JE),e.offsetWidth,e.style.width=`${n}px`;const o=s=>{s&&(s.target!==e||s.propertyName!=="width")||(Ur(e),Gr(e))},r=()=>{e.removeEventListener("transitionend",o),e.removeEventListener("transitioncancel",o)};return e.addEventListener("transitionend",o),e.addEventListener("transitioncancel",o),of.set(e,r),!0}function nT(e){const t=ua.get(e);t&&(clearTimeout(t.timer),ua.delete(e))}function Ym(e,t){var n,i;e.classList.remove(ZE),t.cells.replaceChildren(),(n=e.style)==null||n.removeProperty("--gev-flap-dur"),(i=e.removeAttribute)==null||i.call(e,"aria-label")}function A8(e,t,n){if(ua.delete(e),e.textContent!==t)return;const i=eT(e),o=Ec(e);Ur(e),Gr(e),Ym(e,i);const r=Ec(e);tT(e,o,r,n)}function rf(e,t,n={}){if(!e)return!1;const i=String(t??""),o=eT(e),r=e.textContent??"";if(r===i)return!1;const s=ua.get(e),a=s?E8(s.plan,T0()-s.startedAt,{charMs:s.charMs}):r;nT(e);const c=Ec(e),u=n.immediate!==!0&&!T8()&&k8(e)?M8(a,i,n):null;if(o.text.firstChild.data=i,!(u!=null&&u.changedCount))return Ur(e),Gr(e),Ym(e,o),!1;const h=e.ownerDocument||globalThis.document,d=Gs(n.charMs,Km),f=[];for(const p of u.cells){const g=h.createElement("span");g.className=y8,g.dataset.flapNext=p.to||nf,p.changed&&(g.classList.add(v8),g.dataset.flapPrev=p.from||nf,g.style.setProperty("--gev-flap-delay",`${p.delayMs}ms`)),f.push(g)}return e.removeAttribute("aria-label"),Ur(e),Gr(e),o.cells.replaceChildren(...f),e.classList.add(ZE),e.style.setProperty("--gev-flap-dur",`${d}ms`),tT(e,c,Ec(e),u.durationMs),ua.set(e,{plan:u,charMs:d,startedAt:T0(),timer:setTimeout(()=>A8(e,i,u.durationMs),u.durationMs+_8)}),!0}function k0(e){var n;if(!e)return;nT(e),Ur(e),Gr(e);const t=(n=e.querySelector)==null?void 0:n.call(e,".gev-flap-cells");t&&Ym(e,{cells:t})}class I8{constructor({syncShareState:t}){this._syncShareState=t,this.destroyed=!1,this._recordingMode=!1,this._recordingConfig={hidePanels:!0,hudMode:"minimal",safeFrame:"16:9"},this._preRecordingHudState=null,this._safeFrameOverlay=document.getElementById("safe-frame-overlay"),this._safeFrameBox=document.getElementById("safe-frame-box"),this._hudLayoutSelect=document.getElementById("hud-layout-select"),this._hudBtn=document.getElementById("hud-toggle"),this.hud=null}_initRecordingOverlay(){this.destroyed||!this._safeFrameOverlay||!this._safeFrameBox||this._safeFrameOverlay.classList.remove("active","ratio-9-16","ratio-16-9")}setRecordingMode(t,n={}){if(this.destroyed)return;const{hidePanels:i=!0,hudMode:o="minimal",safeFrame:r="16:9"}=n;if(this._recordingMode=!!t,this._recordingConfig={hidePanels:i,hudMode:o,safeFrame:r},document.body.classList.toggle("recording-mode",this._recordingMode&&i),this._safeFrameOverlay&&(this._safeFrameOverlay.classList.remove("ratio-9-16","ratio-16-9"),this._safeFrameOverlay.classList.toggle("active",this._recordingMode),this._safeFrameOverlay.classList.add(r==="9:16"?"ratio-9-16":"ratio-16-9")),this._recordingMode)this._preRecordingHudState||(this._preRecordingHudState={mode:this.hud.getMode(),variant:this.hud.getVariant()}),o==="off"?this.hud.setMode("off"):o==="full"||o==="minimal"?(this.hud.setMode("on"),this.hud.setVariant(o==="minimal"?"minimal":"tactical"),this._hudLayoutSelect&&(this._hudLayoutSelect.value=this.hud.getVariant())):this.hud.setMode("auto");else{const s=this._preRecordingHudState;this._preRecordingHudState=null,s&&(this.hud.setVariant(s.variant),this._hudLayoutSelect&&(this._hudLayoutSelect.value=this.hud.getVariant())),this.hud.setMode(s?s.mode:"auto"),this._safeFrameOverlay&&this._safeFrameOverlay.classList.remove("active","ratio-9-16","ratio-16-9")}this._hudBtn.classList.toggle("active",this.hud.visible),this._syncShareState()}destroy(){this.destroyed||(this._recordingMode&&this.setRecordingMode(!1),this.destroyed=!0)}}function R8(e=globalThis.document){return{_rightPanelStack:e.getElementById("right-context-rail"),_styleIndicator:e.getElementById("active-style-name"),_sliderPanel:e.getElementById("param-slider-panel"),_sliderContainer:e.getElementById("param-sliders"),_ppToggles:e.getElementById("pp-toggles"),_bloomBtn:e.getElementById("bloom-toggle"),_bloomSliderRow:e.getElementById("bloom-slider-row"),_bloomSlider:e.getElementById("bloom-intensity-slider"),_bloomSliderValue:e.getElementById("bloom-intensity-value"),_sharpenBtn:e.getElementById("sharpen-toggle"),_sharpenSliderRow:e.getElementById("sharpen-slider-row"),_sharpenSlider:e.getElementById("sharpen-intensity-slider"),_sharpenSliderValue:e.getElementById("sharpen-intensity-value"),_hudBtn:e.getElementById("hud-toggle"),_hudLayoutRow:e.getElementById("hud-layout-row"),_hudLayoutSelect:e.getElementById("hud-layout-select"),_detectionSliderRow:e.getElementById("detection-slider-row"),_detectionDensitySlider:e.getElementById("detection-density-slider"),_detectionDensityValue:e.getElementById("detection-density-value"),_detectionAllocationRow:e.getElementById("detection-allocation-row"),_detectionFadeRow:e.getElementById("detection-fade-row"),_detectionFadeSlider:e.getElementById("detection-fade-slider"),_detectionFadeValue:e.getElementById("detection-fade-value"),_detectionOpacityRow:e.getElementById("detection-opacity-row"),_detectionOpacitySlider:e.getElementById("detection-opacity-slider"),_detectionOpacityValue:e.getElementById("detection-opacity-value"),_celestialBtn:e.getElementById("celestial-toggle"),_scopeBtn:e.getElementById("scope-toggle"),_scopeFeatherSlider:e.getElementById("scope-feather-slider"),_scopeFeatherValue:e.getElementById("scope-feather-value"),_mapStackChips:e.getElementById("map-stack-chips"),_mapStackStatus:e.getElementById("map-stack-status"),_cleanViewBtn:e.getElementById("clean-view-toggle"),_cleanViewExitBtn:e.getElementById("clean-view-exit"),_dataPanel:e.getElementById("data-panel"),_scenePanel:e.getElementById("scene-panel"),_cctvPanel:e.getElementById("cctv-panel"),_radioPanel:e.getElementById("radio-panel"),_contextRadioDock:e.getElementById("context-radio-dock"),_contextRadioToggleBtn:e.getElementById("context-radio-toggle-btn"),_contextRadioMini:e.getElementById("context-radio-mini"),_contextRadioMiniEnableBtn:e.getElementById("context-radio-mini-enable-btn"),_contextRadioDetailsBtn:e.getElementById("context-radio-details-btn"),_contextRadioMiniCloseBtn:e.getElementById("context-radio-mini-close-btn"),_contextRadioMiniStation:e.getElementById("context-radio-mini-station"),_contextRadioMiniPrevBtn:e.getElementById("context-radio-mini-prev-btn"),_contextRadioMiniPlayBtn:e.getElementById("context-radio-mini-play-btn"),_contextRadioMiniNextBtn:e.getElementById("context-radio-mini-next-btn"),_contextRadioMiniVolume:e.getElementById("context-radio-mini-volume"),_contextRadioMiniVolumeValue:e.getElementById("context-radio-mini-volume-value"),_cockpitUtilityControls:e.getElementById("cockpit-utility-controls"),_cockpitDisplayToggleBtn:e.getElementById("cockpit-display-toggle-btn"),_cockpitDisplayPanel:e.getElementById("cockpit-display-panel"),_cockpitRadioToggleBtn:e.getElementById("cockpit-radio-toggle-btn"),_cockpitRadioPanel:e.getElementById("cockpit-radio-panel"),_cockpitRadioEnableBtn:e.getElementById("cockpit-radio-enable-btn"),_cockpitRadioStation:e.getElementById("cockpit-radio-station"),_cockpitRadioPrevBtn:e.getElementById("cockpit-radio-prev-btn"),_cockpitRadioPlayBtn:e.getElementById("cockpit-radio-play-btn"),_cockpitRadioNextBtn:e.getElementById("cockpit-radio-next-btn"),_cockpitRadioVolume:e.getElementById("cockpit-radio-volume"),_cockpitRadioVolumeValue:e.getElementById("cockpit-radio-volume-value"),_radioLayerState:e.getElementById("radio-layer-state"),_radioEnableBtn:e.getElementById("radio-enable-btn"),_radioFilter:e.getElementById("radio-filter"),_radioStationName:e.getElementById("radio-station-name"),_radioStationMeta:e.getElementById("radio-station-meta"),_radioStationTags:e.getElementById("radio-station-tags"),_radioTuner:e.getElementById("radio-tuner"),_radioTunerSlider:e.getElementById("radio-tuner-slider"),_radioTunerNeedle:e.getElementById("radio-tuner-needle"),_radioTunerBandLabel:e.getElementById("radio-tuner-band-label"),_radioTunerValue:e.getElementById("radio-tuner-value"),_radioTunerStation:e.getElementById("radio-tuner-station"),_radioPrevBtn:e.getElementById("radio-prev-btn"),_radioPlayBtn:e.getElementById("radio-play-btn"),_radioNextBtn:e.getElementById("radio-next-btn"),_radioStopBtn:e.getElementById("radio-stop-btn"),_radioVolume:e.getElementById("radio-volume"),_radioVolumeValue:e.getElementById("radio-volume-value"),_radioPlaybackState:e.getElementById("radio-playback-state"),_radioStationHomepage:e.getElementById("radio-station-homepage"),_globalContextFlightsBtn:e.getElementById("global-context-flights-btn"),_globalContextMissionsBtn:e.getElementById("global-context-missions-btn"),_contextModeStandby:e.getElementById("context-mode-standby"),_contextFlightsView:e.getElementById("context-flights-view"),_contextMissionsView:e.getElementById("context-missions-view"),_installationsSearchBtn:e.getElementById("installations-search-btn"),_leftPanelStack:e.getElementById("left-panel-stack"),_cctvEnableBtn:e.getElementById("cctv-enable-btn"),_cctvNearestBtn:e.getElementById("cctv-nearest-btn"),_cctvPrevBtn:e.getElementById("cctv-prev-btn"),_cctvNextBtn:e.getElementById("cctv-next-btn"),_cctvSelect:e.getElementById("cctv-camera-select"),_cctvFocusBtn:e.getElementById("cctv-focus-btn"),_cctvCoverageBtn:e.getElementById("cctv-coverage-btn"),_cctvAutoHopBtn:e.getElementById("cctv-auto-hop-btn"),_cctvProjectionBtn:e.getElementById("cctv-projection-btn"),_cctvQualityChip:e.getElementById("cctv-quality-chip"),_cctvAdjustBtn:e.getElementById("cctv-adjust-btn"),_cctvCalReadout:e.getElementById("cctv-cal-readout"),_cctvCalibSaveBtn:e.getElementById("cctv-calib-save-btn"),_cctvCalibResetBtn:e.getElementById("cctv-calib-reset-btn"),_cctvFrame:e.getElementById("cctv-frame"),_cctvFrameWrap:e.getElementById("cctv-frame-wrap"),_cctvSourceBadge:e.getElementById("cctv-source-badge"),_cctvMeta:e.getElementById("cctv-meta"),_cctvSummary:e.getElementById("cctv-summary"),_shareBtn:e.getElementById("share-btn"),_tiltMapBtn:e.getElementById("tilt-map-view"),_northUpBtn:e.getElementById("north-up-view"),_clearSelectedLayersBtn:e.getElementById("clear-selected-layers"),_globalLoadingStatus:e.getElementById("global-loading-status"),_globalLoadingLabel:e.getElementById("global-loading-label"),_globalLoadingDetail:e.getElementById("global-loading-detail"),_resetGlobeBtn:e.getElementById("reset-globe-view"),_cockpitResetGlobeBtn:e.getElementById("cockpit-reset-globe"),_styleButtons:e.getElementById("style-buttons"),_trafficSyncChip:e.getElementById("traffic-sync-chip"),_trafficSyncLabel:e.getElementById("traffic-sync-label"),_trafficSyncProgress:e.getElementById("traffic-sync-progress"),_cctvSyncChip:e.getElementById("cctv-sync-chip"),_cctvSyncLabel:e.getElementById("cctv-sync-label"),_cctvSyncProgress:e.getElementById("cctv-sync-progress"),_toast:e.getElementById("toast"),_locationSearch:e.getElementById("location-search"),_searchToggle:e.getElementById("search-toggle"),_locationPills:e.getElementById("location-pills"),_poiRow:e.getElementById("poi-row"),_locationBarDivider:e.getElementById("location-bar-divider"),_styleMiniValue:e.getElementById("style-mini-value"),_locationMiniCity:e.getElementById("location-mini-city"),_locationMiniPoi:e.getElementById("location-mini-poi"),_safeFrameOverlay:e.getElementById("safe-frame-overlay"),_safeFrameBox:e.getElementById("safe-frame-box"),_detectionBtn:e.getElementById("detection-toggle"),_models3dBtn:e.getElementById("models3d-toggle"),_models3dModeRow:e.getElementById("models3d-mode-row")}}function L8(){var t,n,i,o,r;const e=((t=this.viewer)==null?void 0:t.trackedEntity)||this.trackedEntity;return R4({civilian:((i=(n=this.services.flightsLayer).getTrackedInfo)==null?void 0:i.call(n))||null,military:((r=(o=this.services.militaryFlightsLayer).getTrackedInfo)==null?void 0:r.call(o))||null,trackedId:(e==null?void 0:e.gevTrackedId)||""})}function P8(e,t=null){const n=e&&String((t==null?void 0:t.icao24)||"").trim().toLowerCase()||null,i=e&&["flights","military"].includes(t==null?void 0:t.layerId)?t.layerId:null;window.dispatchEvent(new CustomEvent("gev:cockpit-mode-changed",{detail:{active:e===!0,subjectId:n,layerId:i}}))}function x8(){var i;if(this.destroyed)return!1;const e=this.readAircraftInfo(),t=String((e==null?void 0:e.icao24)||"").trim();if(!t)return!1;this.services.toggleTr3b(t);const n=e.layerId==="military"?this.services.militaryFlightsLayer:this.services.flightsLayer;return(i=n.refreshTr3b)==null||i.call(n,t),this._tr3bSignature=null,this.syncTr3bToggle(e),!0}function F8(e){if(!this.tr3bToggle)return;const t=String((e==null?void 0:e.icao24)||"").trim(),n=!!t&&this.services.isTr3b(t),i=t?`${t}:${n?1:0}`:"";this._tr3bSignature!==i&&(this._tr3bSignature=i,this.tr3bToggle.hidden=!t,this.tr3bToggle.setAttribute("aria-pressed",n?"true":"false"),this.tr3bToggle.title=n?"Restore real aircraft":"Reclassify as TR-3B")}function S8(){var i;if(this.destroyed)return!1;if(this.active)return;const e=this.readAircraftInfo(),t=!!(e&&((i=this.viewer.trackedEntity)!=null&&i.position));this.syncTr3bToggle(t?e:null);const n=!!(this.isEntryAllowed()&&t);this._entryAvailable!==n&&(this._entryAvailable=n,this.entry&&(this.entry.hidden=!n),this.mapViewButton&&(this.mapViewButton.hidden=!0),this.resetGlobeButton&&(this.resetGlobeButton.hidden=!0))}function N8(e,t={}){var s,a;if(this.destroyed)return!1;const n=e<0?"navigatePrevious":"navigateNext",i=this.active;i&&(this.contextNavigationDeadlineMs=performance.now()+1500);const o=i?{...t,aircraftOnly:!0}:t;return!((a=(s=this.services.militaryAwarenessLayer)==null?void 0:s[n])!=null&&a.call(s,o))?(this.contextNavigationDeadlineMs=0,!1):(i&&this._adoptTrackedEntity(performance.now()),!0)}function D8(e,t=null){const n=this.viewer.trackedEntity;if(!this.active||!(n!=null&&n.position)||n===this.trackedEntity)return!1;const i=t||this.readAircraftInfo();return i?(this.trackedEntity&&this.viewer.entities.contains(this.trackedEntity)&&(this.trackedEntity.show=this.trackedEntityWasShown),this.trackedEntity=n,this.trackedEntityWasShown=n.show,n.show=!1,this.viewer.trackedEntity=void 0,this.cockpitAnchorValid=!1,this.heading=jt(i.track??0),this.lastFrameMs=e,this.lastHudUpdateMs=0,this.lastContextUpdateMs=0,this.lastCameraUpdateMs=0,this.contextNavigationDeadlineMs=0,this.dispatchCockpitModeChanged(!0,i),!0):!1}function O8(){var o,r,s,a;if(this.destroyed||this.active||!this.isEntryAllowed())return!1;const e=this.readAircraftInfo(),t=this.viewer.trackedEntity;if(!e||!(t!=null&&t.position))return!1;this.entryFocusOrigin=document.activeElement instanceof HTMLElement?document.activeElement:null,(o=this.onCameraTakeover)==null||o.call(this),this.viewer.camera.cancelFlight(),this.trackedEntity=t,this.trackedEntityWasShown=t.show,t.show=!1,this.heading=jt(e.track??0),this.lastFrameMs=performance.now(),this.lastCameraUpdateMs=0,this.lastHudUpdateMs=0,this.lastContextUpdateMs=0,this.contextNavigationDeadlineMs=0,this.lastGroundProbeMs=0,this.surfaceWaitStartedMs=performance.now(),this.surfaceAcquiring=!1,this.surfaceFallback=!1,this.lastCompassSignature="",this.cockpitAnchorValid=!1,this.lastCameraUpdateMs=0,this.active=!0,this.services.holdContinuousRender("cockpit"),this.viewer.trackedEntity=void 0,this.viewer.scene.screenSpaceCameraController.enableInputs=!1,document.body.classList.add("cockpit-mode"),this._entryAvailable=void 0,this.entry&&(this.entry.hidden=!0),this.tr3bToggle&&(this.tr3bToggle.hidden=!0,this._tr3bSignature=null),this.mapViewButton&&(this.mapViewButton.hidden=!1),this.resetGlobeButton&&(this.resetGlobeButton.hidden=!1),this.hud&&(this.hud.hidden=!1),this.signalStream&&(this.signalStream.hidden=!1),(r=this.hud)==null||r.classList.add("signals-active"),this.signalItems=[],this.signalSignatures.clear(),this.showBriefPage(0),this.startBriefRotation();const n=e.callsign||e.registration||e.icao24||"AIRCRAFT",i=String(Math.round(jt(e.track??0))).padStart(3,"0");return this.pushCockpitSignal("track","track","TRACK ACQUIRED",`${n} · COURSE ${i}°`),this.updateHud(e,performance.now(),!0),this.setVisionMode(this.visionMode),this.scheduleContextLayout(),(s=this.mapViewButton)==null||s.focus({preventScroll:!0}),(a=this.onEntered)==null||a.call(this),this.dispatchCockpitModeChanged(!0,e),!0}function B8({restoreTracking:e=!0}={}){var i,o,r,s,a;if(!this.active)return!1;const t=this.trackedEntity;this.active=!1,this.services.releaseContinuousRender("cockpit"),this.trackedEntity=null,this.heading=null,this.cockpitAnchorValid=!1,this.surfaceWaitStartedMs=0,this.surfaceAcquiring=!1,this.surfaceFallback=!1,this.lastHudUpdateMs=0,this.lastContextUpdateMs=0,this.contextNavigationDeadlineMs=0,this.lastCompassSignature="",this.stopBriefRotation(),(i=this.regionalBriefAbort)==null||i.abort(),this.regionalBriefAbort=null,this.regionalBriefRequestToken+=1,this.regionalBriefSubjectId=null,document.body.classList.remove("cockpit-mode"),(o=this.onExited)==null||o.call(this),(r=this.hud)==null||r.style.removeProperty("--cockpit-utility-top"),(s=this.hud)==null||s.style.removeProperty("--cockpit-utility-max-height"),this.hud&&(this.hud.hidden=!0),this.route&&(this.route.hidden=!0),this.clearPredictiveRoute(),this.setVisionMode("optical"),this.signalStream&&(this.signalStream.hidden=!0),(a=this.hud)==null||a.classList.remove("signals-active"),this.viewer.scene.screenSpaceCameraController.enableInputs=!0,t&&this.viewer.entities.contains(t)&&(t.show=this.trackedEntityWasShown),this.trackedEntityWasShown=!0,this.dispatchCockpitModeChanged(!1),e&&t&&this.viewer.entities.contains(t)&&(this.viewer.trackedEntity=t,this.restoreTrackingFrame(t)),this.syncEntry();const n=this.entryFocusOrigin===this.entry?this.entry:this.entry||this.entryFocusOrigin;return this.entryFocusOrigin=null,!this.destroyed&&(n!=null&&n.isConnected)&&!n.hidden&&n.focus({preventScroll:!0}),!0}const V8=28,H8=7,A0=2.6,I0=12,$8=-4,G8=50,R0=100,U8=250,z8=12,j8=8,q8=96,W8=.12,K8=50,Y8=500,X8=5e3,Q8=9e3,Z8="Cycle briefing pages automatically every 9 seconds (Signals → News → Local). Pauses while you hover or focus the panel. Live signal data refreshes continuously either way.",J8="Stop automatic page cycling. Previous, Next, and the SIG/NEWS/LOCAL tabs stay available.",e6=5*6e4,t6=25e3,L0=[{id:"signals",kicker:"LIVE SIGNALS",subtitle:"OBSERVED / MAPPED PINGS",source:"SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS"},{id:"news",kicker:"REGIONAL NEWS",subtitle:"LATEST LOCATION-MATCHED REPORTING",source:"GOOGLE NEWS RSS · LOCATION QUERY · RECENT"},{id:"local",kicker:"LOCAL INFO",subtitle:"PLACE / CONDITIONS / POSITION",source:"OPENSTREETMAP · OPEN-METEO · UTC"}];function n6(e){if(!e)return!1;for(let n=e;n instanceof Element;n=n.parentElement){const i=getComputedStyle(n);if(i.display==="none"||i.visibility==="hidden"||Number(i.opacity)===0)return!1}const t=e.getBoundingClientRect();return t.width>0&&t.height>0}function i6(e){const t=Date.parse(e);if(!Number.isFinite(t))return"TIME UNKNOWN";const n=Math.max(0,Math.round((Date.now()-t)/6e4));if(n<60)return`${n}M AGO`;const i=Math.round(n/60);return i<48?`${i}H AGO`:`${Math.round(i/24)}D AGO`}function o6(e){if(!Number.isFinite(e))return"DIR UNKNOWN";const t=["N","NE","E","SE","S","SW","W","NW"],n=(e%360+360)%360;return`${t[Math.round(n/45)%t.length]} · ${Math.round(n)}°`}function fd(e,t,n,{circularRange:i=null,immediate:o=!1}={}){if(!e)return;const r=String(t),s=e.dataset.rollingText,a=Number(e.dataset.rollingValue),c=performance.now(),l=Number(e.dataset.rollingAt);if(!o&&s!==void 0&&s!==r&&Number.isFinite(l)&&c-l<220)return;if(e.dataset.rollingText=r,e.dataset.rollingAt=String(c),Number.isFinite(n)?e.dataset.rollingValue=String(n):delete e.dataset.rollingValue,e.setAttribute("aria-label",r),o||s===void 0||s===r){(s!==r||!e.querySelector(".cockpit-roll-token"))&&e.replaceChildren(...Array.from(r,_=>{const m=document.createElement("span");return m.className="cockpit-roll-token",m.setAttribute("aria-hidden","true"),m.textContent=_,m}));return}let u=Number.isFinite(n)&&Number.isFinite(a)?n-a:0;if(Number.isFinite(i)&&i>0){const _=i/2;u>_?u-=i:u<-_&&(u+=i)}const h=u<0?"down":"up",d=Math.max(s.length,r.length),f=s.padStart(d," "),p=r.padStart(d," "),g=document.createDocumentFragment();for(let _=0;_=250&&(this._lastEntrySyncMs=h,this.syncEntry());return}const e=performance.now(),t=this.readAircraftInfo();if(this._adoptTrackedEntity(e,t),!t||!this.trackedEntity||!this.viewer.entities.contains(this.trackedEntity)){if(e0&&h>0&&(Cesium.Cartesian3.multiplyByScalar(this.scratchCorrection,d/h,this.scratchCorrection),Cesium.Cartesian3.add(this.cockpitAnchor,this.scratchCorrection,this.cockpitAnchor))}const a=Cesium.Cartographic.fromCartesian(this.cockpitAnchor,Cesium.Ellipsoid.WGS84,this.scratchAnchorCartographic),c=Cesium.Cartographic.fromCartesian(n,Cesium.Ellipsoid.WGS84,this.scratchTargetCartographic);let l=this.services.cachedGroundFloor(t.latitude,t.longitude);if(t.onGround===!0){const h=[{lat:t.latitude,lon:t.longitude}];this.services.warmGroundFloor(h);const d=this.services.cachedMeshFloor(t.latitude,t.longitude);if(this.services.meshFloorPreferred()&&!Number.isFinite(d)){if(Es(e,this.lastGroundProbeMs,Y8)){this.lastGroundProbeMs=e;const f=this.viewer.camera.positionCartographic;this.services.sampleMeshFloorCells(this.viewer.scene,h,{excludeObjects:[this.trackedEntity],viewerLat:Cesium.Math.toDegrees(f.latitude),viewerLon:Cesium.Math.toDegrees(f.longitude)})}if(l=this.services.cachedMeshFloor(t.latitude,t.longitude),Number.isFinite(l))this.surfaceWaitStartedMs=0,this.surfaceAcquiring=!1,this.surfaceFallback=!1;else{if(this.surfaceWaitStartedMs||(this.surfaceWaitStartedMs=e),!y4(e,this.surfaceWaitStartedMs,X8)){this.surfaceAcquiring=!0,this.surfaceFallback=!1,Es(e,this.lastHudUpdateMs,R0)&&(this.lastHudUpdateMs=e,this.updateHud(t,e));return}this.surfaceAcquiring=!1,this.surfaceFallback=!0}}}else this.surfaceWaitStartedMs=0,this.surfaceAcquiring=!1,this.surfaceFallback=!1;if(!Number.isFinite(l)&&s<90&&Number.isFinite(c==null?void 0:c.height)&&(l=c.height-this.services.GROUND_FLOOR_LIFT_M),a&&Number.isFinite(l)){const h=Ob(a.height,l,I0-A0);h!==a.height&&(a.height=h,Cesium.Ellipsoid.WGS84.cartographicToCartesian(a,this.cockpitAnchor))}Cesium.Transforms.eastNorthUpToFixedFrame(this.cockpitAnchor,Cesium.Ellipsoid.WGS84,this.scratchEnu),this.scratchLocal.x=Math.sin(o),this.scratchLocal.y=Math.cos(o),this.scratchLocal.z=0,Cesium.Matrix4.multiplyByPointAsVector(this.scratchEnu,this.scratchLocal,this.scratchHorizontal),Cesium.Cartesian3.normalize(this.scratchHorizontal,this.scratchHorizontal),this.scratchLocal.x=Math.sin(o)*Math.cos(r),this.scratchLocal.y=Math.cos(o)*Math.cos(r),this.scratchLocal.z=Math.sin(r),Cesium.Matrix4.multiplyByPointAsVector(this.scratchEnu,this.scratchLocal,this.scratchForward),Cesium.Cartesian3.normalize(this.scratchForward,this.scratchForward),this.scratchLocal.x=-Math.sin(o)*Math.sin(r),this.scratchLocal.y=-Math.cos(o)*Math.sin(r),this.scratchLocal.z=Math.cos(r),Cesium.Matrix4.multiplyByPointAsVector(this.scratchEnu,this.scratchLocal,this.scratchUp),Cesium.Cartesian3.normalize(this.scratchUp,this.scratchUp),Cesium.Cartesian3.multiplyByScalar(this.scratchHorizontal,H8,this.scratchCamera),Cesium.Cartesian3.add(this.cockpitAnchor,this.scratchCamera,this.scratchCamera),Cesium.Matrix4.getTranslation(this.scratchEnu,this.scratchTarget),Cesium.Cartesian3.normalize(this.scratchTarget,this.scratchTarget),Cesium.Cartesian3.multiplyByScalar(this.scratchTarget,A0,this.scratchTarget),Cesium.Cartesian3.add(this.scratchCamera,this.scratchTarget,this.scratchCamera);const u=Cesium.Cartographic.fromCartesian(this.scratchCamera,Cesium.Ellipsoid.WGS84,this.scratchCameraCartographic);if(u){const h=Cesium.Math.toDegrees(u.latitude),d=Cesium.Math.toDegrees(u.longitude),f=this.services.cachedGroundFloor(h,d);Number.isFinite(f)&&(l=Math.max(l??Number.NEGATIVE_INFINITY,f));const p=Ob(u.height,l,I0);p!==u.height&&(u.height=p,Cesium.Ellipsoid.WGS84.cartographicToCartesian(u,this.scratchCamera))}this.viewer.camera.setView({destination:this.scratchCamera,orientation:{direction:this.scratchForward,up:this.scratchUp}}),Es(e,this.lastHudUpdateMs,R0)&&(this.lastHudUpdateMs=e,this.updateHud(t,e))}function s6(e,t=performance.now(),n=!1){this.lastAircraftInfo=e;const i=jt(this.heading??e.track??0);this.callsign&&(this.callsign.textContent=e.callsign||e.registration||e.icao24||"AIRCRAFT");const o=Number.isFinite(e.velocityMps)?e.velocityMps*1.94384:null;fd(this.speed,ad(o),o,{immediate:n}),this.speedRim&&this.speedRim.classList.toggle("unavailable",o===null),this.speedRimValue&&(this.speedRimValue.textContent=ad(o));const r=I4(o,this.speedRimTicks.length);this.speedRimTicks.forEach((c,l)=>{const u=r[l];if(c.hidden=!u,!u)return;c.style.setProperty("--slot",u.slot.toFixed(4)),c.style.setProperty("--depth",u.depth.toFixed(4)),c.style.setProperty("--curve",Bb(u.slot).toFixed(5)),c.classList.toggle("major",u.major);const h=c.querySelector("b");h&&(h.textContent=ad(u.valueKt))});const s=v4(e.altitudeM,e.onGround);if(this.altitude){const c=Number.isFinite(s)?Math.round(s):null;fd(this.altitude,c!==null?c.toLocaleString("en-US"):"-----",c,{immediate:n})}this.altitudeRim&&this.altitudeRim.classList.toggle("unavailable",s===null),this.altitudeRimValue&&(this.altitudeRimValue.textContent=Vb(s));const a=k4(s,this.altitudeRimTicks.length);if(this.altitudeRimTicks.forEach((c,l)=>{const u=a[l];if(c.hidden=!u,!u)return;c.style.setProperty("--slot",u.slot.toFixed(4)),c.style.setProperty("--depth",u.depth.toFixed(4)),c.style.setProperty("--curve",Bb(u.slot).toFixed(5)),c.classList.toggle("major",u.major);const h=c.querySelector("b");h&&(h.textContent=Vb(u.valueFt))}),fd(this.headingValue,String(Math.round(i)%360).padStart(3,"0"),i,{circularRange:360,immediate:n}),this.compassTape){const c=w4(i),l=c.join(",");l!==this.lastCompassSignature&&(this.lastCompassSignature=l,this.compassTape.innerHTML=c.map((u,h)=>{const d=h-3;return`${E4(u)}`}).join(""))}if(this.clock&&(this.clock.textContent=new Date().toISOString().slice(11,19)+"Z"),this.position){const c=Number.isFinite(e.latitude)?`${Math.abs(e.latitude).toFixed(3)}°${e.latitude>=0?"N":"S"}`:"--",l=Number.isFinite(e.longitude)?`${Math.abs(e.longitude).toFixed(3)}°${e.longitude>=0?"E":"W"}`:"--";this.position.textContent=`${c} · ${l}`}if(this.aircraftMeta){const c=this.surfaceAcquiring?"ACQUIRING SURFACE":this.surfaceFallback?"SURFACE FALLBACK":e.stale?"STALE FEED":"LIVE TRACK";this.aircraftMeta.textContent=`${e.layerId==="military"?"MILITARY":"COMMERCIAL"} · ${c} · COURSE ALIGNED`}this.updateRoute(e),(n||Es(t,this.lastContextUpdateMs,U8))&&(this.lastContextUpdateMs=t,this.updateLocalPosition(e),this.maybeRefreshRegionalBrief(e),this.updateContext(e,i)),this.hud&&(this.hud.dataset.layer=e.layerId||"flights")}function a6(e){var a,c;const t=(a=e==null?void 0:e.route)==null?void 0:a.origin,n=(c=e==null?void 0:e.route)==null?void 0:c.destination,i=Number.isFinite(n==null?void 0:n.lat)&&Number.isFinite(n==null?void 0:n.lon),o=l=>[l==null?void 0:l.code,l==null?void 0:l.name].filter(Boolean).join(" · ")||"UNKNOWN";if(this.routeFrom&&(this.routeFrom.textContent=o(t)),this.routeTo&&(this.routeTo.textContent=o(n)),this.routeStatus&&(this.routeStatus.textContent=i?"ARROW · ESTIMATED DIRECTION":"ROUTE DATA UNAVAILABLE"),this.route&&(this.route.hidden=!t&&!n),!i||!Number.isFinite(e==null?void 0:e.longitude)||!Number.isFinite(e==null?void 0:e.latitude)){this.clearPredictiveRoute();return}const r=Gm(e.latitude,e.longitude,n.lat,n.lon),s=EE(r,this.heading??e.track??0);if(!Number.isFinite(r)||!Number.isFinite(s)){this.clearPredictiveRoute();return}if(this.routeDirection){const l=Math.max(-120,Math.min(120,s));this.routeDirection.hidden=!1,this.routeDirection.style.setProperty("--route-angle",`${l.toFixed(2)}deg`)}this.routeDirectionLabel&&(this.routeDirectionLabel.textContent=`DEST ${String(Math.round(r)).padStart(3,"0")}°`)}function l6(e){if(!this.weatherToggle)return;const t=!!e;this.weatherToggle.setAttribute("aria-pressed",String(t)),this.weatherToggle.setAttribute("aria-label",`${t?"Disable":"Enable"} cockpit weather effects`),this.weatherToggle.title=`${t?"Disable":"Enable"} cockpit weather effects`,this.weatherState&&(this.weatherState.textContent=t?"ON":"OFF")}function c6(e,{revealParameters:t=!1}={}){var s,a;const n=qm(e);this.visionMode=n;const i=String(((s=this.getInheritedVisionLabel)==null?void 0:s.call(this))||"NORMAL").toUpperCase(),o={optical:i,crt:"CRT",nvg:"NVG",thermal:"FLIR",noir:"NOIR"},r={optical:i,crt:"CRT",nvg:"Night vision",thermal:"Thermal",noir:"Noir"};this.visionCurrent&&(this.visionCurrent.dataset.cockpitVision=n,this.visionCurrent.setAttribute("aria-label",`Current cockpit vision style: ${r[n]}. Activate for next style.`),this.visionCurrent.title=`Current style: ${r[n]} — click for next`),this.visionCurrentLabel&&(this.visionCurrentLabel.textContent=o[n]),(a=this.onVisionChange)==null||a.call(this,n,this.active,{revealParameters:t})}function u6(e=1){const t=QE,n=Math.max(0,t.indexOf(this.visionMode)),i=e<0?-1:1,o=(n+i+t.length)%t.length;this.setVisionMode(t[o],{revealParameters:!0})}function d6(){this.routeDirection&&(this.routeDirection.hidden=!0)}function h6(e,t){var u,h,d,f,p,g,_;if(!this.context)return;const n=((h=(u=this.services.militaryAwarenessLayer).getContextSnapshot)==null?void 0:h.call(u))||null,i=e.icao24||e.id,o=L4({snapshot:n,info:e});if(!o.visible){this.context.hidden=!0,(d=this.hud)==null||d.classList.remove("context-active"),this.contextLayoutStamp=null,this.pushCockpitSignal("context-status","info","CONTEXT STANDBY","ENABLE GLOBAL CONTEXT FOR PROXIMITY PINGS");return}if(this.context.hidden=!1,(f=this.hud)==null||f.classList.add("context-active"),this.contextSubject){const m=(p=n.cohorts.find(b=>b.id==="military-installations"))==null?void 0:p.coverage;this.contextSubject.textContent=M4(n.subject.label||i,n.radiusM,m)}if(this.contextPrevious&&(this.contextPrevious.disabled=!((g=n.navigation)!=null&&g.canPrevious)),this.contextNext&&(this.contextNext.disabled=!((_=n.navigation)!=null&&_.canNext)),o.contactLost){const m=this.context.dataset.state!=="lost";this.context.dataset.state="lost",this.contextUncertainty&&(this.contextUncertainty.textContent="CONTACT LOST · LAST KNOWN READOUT · NOT AN ALL-CLEAR"),m&&this.scheduleContextLayout(),this.pushCockpitSignal("context-status","warning",`CONTACT LOST · ${n.subject.label||n.subject.id||"SUBJECT"}`,"SUBJECT LEFT ITS FEED · READOUT HOLDING LAST KNOWN");return}let r=0;const s=[];for(const m of n.cohorts){const b=this.contextCohorts.get(m.id),C=b==null?void 0:b.querySelector("strong");C&&(C.textContent=m.count===null?"?":String(m.count)),b==null||b.classList.toggle("unknown",m.relationship==="UNKNOWN"),m.count===null&&(r+=1);for(const y of m.nearest)s.push({...y,cohort:m})}s.sort((m,b)=>(m.distanceM??1/0)-(b.distanceM??1/0));const a=s[0]||null,c=this.services.formatAwarenessLabel(a);if(this.contextNearestLabel&&(this.contextNearestLabel.textContent=a?`${a.cohort.label.toUpperCase()} · ${c}`:"NO AVAILABLE EXAMPLE",this.contextNearestLabel.setAttribute("aria-label",a&&c==="—"?`${a.cohort.label}, Unavailable`:this.contextNearestLabel.textContent)),this.contextDistance){const m=a==null?void 0:a.distanceM;this.contextDistance.textContent=Number.isFinite(m)?`${m<1e4?(m/1e3).toFixed(1):Math.round(m/1e3)} KM`:"—",this.contextDistance.setAttribute("aria-label",Number.isFinite(m)?this.contextDistance.textContent:"Unavailable")}let l=null;if(o.aircraftRelative&&(a!=null&&a.position)&&Number.isFinite(e.latitude)&&Number.isFinite(e.longitude)){const m=Cesium.Cartographic.fromCartesian(a.position),b=m?Gm(e.latitude,e.longitude,Cesium.Math.toDegrees(m.latitude),Cesium.Math.toDegrees(m.longitude)):null;l=EE(b,t)}this.contextDirection&&(this.contextDirection.style.transform=`rotate(${l??0}deg)`,this.contextDirection.classList.toggle("unknown",l===null)),this.contextBearing&&(l===null?this.contextBearing.textContent="BRG —":Math.abs(l)<8?this.contextBearing.textContent="AHEAD":this.contextBearing.textContent=`${l<0?"L":"R"} ${String(Math.round(Math.abs(l))).padStart(3,"0")}°`),this.contextUncertainty&&(this.contextUncertainty.textContent=r?`${r} INPUT${r===1?"":"S"} UNKNOWN · NOT AN ALL-CLEAR`:"AVAILABLE INPUTS CURRENT · NOT AN ALL-CLEAR"),this.contextUpdated&&(this.contextUpdated.textContent=Number.isFinite(n.evaluatedAt)?new Date(n.evaluatedAt).toISOString().slice(11,19)+"Z":"--:--:--Z"),this.context.dataset.state=r?"uncertain":"current",this.updateCockpitSignals(n,r),this.contextLayoutStamp!==n.evaluatedAt&&(this.contextLayoutStamp=n.evaluatedAt,this.scheduleContextLayout())}function f6(e,{manual:t=!1}={}){if(this.destroyed)return;const n=L0.length;this.briefPageIndex=(Number(e)%n+n)%n;const i=L0[this.briefPageIndex];if(this.briefPages.forEach(o=>{o.hidden=o.dataset.cockpitBriefPage!==i.id}),this.briefTabs.forEach(o=>{const r=Number(o.dataset.cockpitBriefIndex)===this.briefPageIndex;o.setAttribute("aria-current",r?"true":"false")}),this.briefKicker){const o=this.briefKicker.querySelector("i");this.briefKicker.replaceChildren(...[o,document.createTextNode(` ${i.kicker}`)].filter(Boolean))}this.briefSubtitle&&(this.briefSubtitle.textContent=i.subtitle),this.briefPosition&&(this.briefPosition.textContent=`${this.briefPageIndex+1} / ${n}`),this.briefSource&&(this.briefSource.textContent=i.source),this.signalStream&&(this.signalStream.dataset.briefPage=i.id),t&&this.briefAutoRotateEnabled&&this.startBriefRotation({reset:!0}),this.scheduleContextLayout()}function m6(e){if(!this.destroyed){if(this.briefAutoRotateEnabled=!!e,this.briefAutoToggle){this.briefAutoToggle.setAttribute("aria-pressed",String(this.briefAutoRotateEnabled));const t=this.briefAutoRotateEnabled?"CYCLE ON":"CYCLE OFF";this.briefAutoToggle.textContent=t;const n=this.briefAutoRotateEnabled?J8:Z8;this.briefAutoToggle.setAttribute("aria-label",t),this.briefAutoToggle.title=n}this.briefAutoRotateEnabled?this.startBriefRotation({reset:!0}):this.stopBriefRotation()}}function p6({reset:e=!1}={}){this.destroyed||(e&&this.stopBriefRotation(),!(!this.briefAutoRotateEnabled||this.briefTimer||!this.active||this.signalCollapsed||document.hidden)&&(this.briefTimer=window.setTimeout(()=>{var o,r;if(this.briefTimer=null,this.destroyed)return;const t=((o=this.signalStream)==null?void 0:o.matches(":hover"))===!0,n=((r=this.signalStream)==null?void 0:r.contains(document.activeElement))===!0;t||n||this.showBriefPage(this.briefPageIndex+1),this.startBriefRotation()},Q8)))}function g6(){this.briefTimer&&window.clearTimeout(this.briefTimer),this.briefTimer=null}function _6(e){if(!this.localCoordinates)return;if(!Number.isFinite(e.latitude)||!Number.isFinite(e.longitude)){this.localCoordinates.textContent="POSITION UNAVAILABLE";return}const t=`${Math.abs(e.latitude).toFixed(3)}°${e.latitude>=0?"N":"S"}`,n=`${Math.abs(e.longitude).toFixed(3)}°${e.longitude>=0?"E":"W"}`;this.localCoordinates.textContent=`${t} · ${n}`}function b6(e){var a;if(this.destroyed||!this.active||!Number.isFinite(e.latitude)||!Number.isFinite(e.longitude))return;const t=`${e.layerId||"aircraft"}:${e.icao24||e.registration||e.callsign||"unknown"}`;t!==this.regionalBriefSubjectId&&((a=this.regionalBriefAbort)==null||a.abort(),this.regionalBriefAbort=null,this.regionalBriefRequestToken+=1,this.regionalBriefSubjectId=t,this.regionalBrief=null,this.regionalBriefAnchor=null,this.regionalBriefFetchedAt=0);const n={latitude:e.latitude,longitude:e.longitude},i=Date.now()-this.regionalBriefFetchedAt,o=this.services.regionalDistanceM(this.regionalBriefAnchor,n);if(this.regionalBriefAbort||i{!this.active||s!==this.regionalBriefRequestToken||t!==this.regionalBriefSubjectId||(this.regionalBrief=c,this.renderRegionalBrief(c,e))}).catch(c=>{(c==null?void 0:c.name)!=="AbortError"&&this.active&&s===this.regionalBriefRequestToken&&t===this.regionalBriefSubjectId&&this.renderRegionalBriefStatus("unavailable",e)}).finally(()=>{this.regionalBriefAbort===r&&(this.regionalBriefAbort=null)})}function C6(e,t){var n;this.newsStatus&&(this.newsStatus.hidden=!1,this.newsStatus.dataset.state=e,this.newsStatus.textContent=e==="loading"?"ACQUIRING REGIONAL NEWS":"REGIONAL NEWS UNAVAILABLE"),e==="unavailable"&&((n=this.newsList)==null||n.replaceChildren()),this.localPlace&&e==="loading"&&(this.localPlace.textContent="RESOLVING REGION"),this.localPlace&&e==="unavailable"&&(this.localPlace.textContent="REGION UNAVAILABLE"),this.updateLocalPosition(t)}function y6(e,t){var r,s;const n=Array.isArray(e==null?void 0:e.articles)?e.articles:[];this.newsStatus&&(this.newsStatus.hidden=n.length>0,this.newsStatus.dataset.state=(e==null?void 0:e.newsStatus)||"unavailable",this.newsStatus.textContent=(e==null?void 0:e.newsStatus)==="empty"?"NO RECENT LOCATION MATCHES":"REGIONAL NEWS UNAVAILABLE"),this.newsList&&this.newsList.replaceChildren(...n.slice(0,4).map(a=>{const c=document.createElement("li"),l=document.createElement("a");l.href=a.url,l.target="_blank",l.rel="noopener noreferrer";const u=document.createElement("strong");u.textContent=a.title;const h=document.createElement("span");return h.textContent=`${a.domain||"SOURCE"} · ${i6(a.publishedAt)}`,l.append(u,h),c.append(l),c}));const i=((r=e==null?void 0:e.place)==null?void 0:r.label)||((s=e==null?void 0:e.place)==null?void 0:s.country)||"REGION UNAVAILABLE";this.localPlace&&(this.localPlace.textContent=i.toUpperCase()),this.updateLocalPosition(t);const o=e==null?void 0:e.weather;this.localTemperature&&(this.localTemperature.textContent=Number.isFinite(o==null?void 0:o.temperatureC)?`${Math.round(o.temperatureC)}°C`:"—"),this.localWind&&(this.localWind.textContent=Number.isFinite(o==null?void 0:o.windKph)?`${Math.round(o.windKph)} KM/H`:"—"),this.localWindDirection&&(this.localWindDirection.textContent=o6(o==null?void 0:o.windDirectionDeg)),this.localCondition&&(this.localCondition.textContent=this.services.weatherCodeLabel(o==null?void 0:o.weatherCode)),this.localCloud&&(this.localCloud.textContent=Number.isFinite(o==null?void 0:o.cloudCoverPct)?`CLOUD ${Math.round(o.cloudCoverPct)}%`:"CLOUD UNKNOWN"),this.localPrecipitation&&(this.localPrecipitation.textContent=Number.isFinite(o==null?void 0:o.precipitationMm)?o.precipitationMm.toFixed(1):"—"),this.signalStream&&(this.signalStream.dataset.regionalStatus=(e==null?void 0:e.status)||"partial"),this.briefPageIndex===1&&this.briefSource&&(this.briefSource.textContent=`${String((e==null?void 0:e.newsSource)||"REGIONAL NEWS").toUpperCase()} · LOCATION QUERY`),this.scheduleContextLayout()}function v6(){var c,l;if(!this.signalList)return;const e=[...this.signalList.children],t=e.find(u=>u.contains(document.activeElement)),n=new Map;for(const u of e){const h=u.dataset.signalKey;n.has(h)||n.set(h,[]),n.get(h).push(u)}const i=(u,h)=>{u.textContent!==h&&(u.textContent=h)},o=this.signalItems.map(u=>{var b,C,y;const h=JSON.stringify([u.key,!!u.target,((b=u.target)==null?void 0:b.layerId)||"",String(((C=u.target)==null?void 0:C.id)??"")]);let d=(y=n.get(h))==null?void 0:y.shift();if(!d){d=document.createElement("li"),d.dataset.signalKey=h;const v=document.createElement("time"),M=document.createElement("div"),w=document.createElement(u.target?"button":"strong");if(u.target){w.type="button",w.className="cockpit-signal-target";const E=document.createElement("span");E.className="cockpit-signal-target-label";const k=document.createElement("span");k.className="cockpit-signal-target-rule",k.setAttribute("aria-hidden","true");const T=document.createElement("span");T.className="material-symbols-outlined cockpit-signal-target-chevron",T.setAttribute("aria-hidden","true"),T.textContent="chevron_right",w.append(E,k,T)}M.append(w,document.createElement("span")),d.append(v,M)}const[f,p]=d.children,[g,_]=p.children,m=u.target?`${u.tone} actionable`:u.tone;if(d.className!==m&&(d.className=m),i(f,new Date(u.timestamp).toISOString().slice(11,19)+"Z"),u.target){g.dataset.signalLayer=u.target.layerId,g.dataset.signalId=u.target.id;const v=`Select flight ${u.title}`;g.getAttribute("aria-label")!==v&&g.setAttribute("aria-label",v),i(g.children[0],u.title)}else i(g,u.title);return i(_,u.detail),d}),r=o.includes(t)?t:null;t&&!r&&((l=((c=this.briefTabs)==null?void 0:c[this.briefPageIndex])||this.signalToggle)==null||l.focus({preventScroll:!0}));for(const u of e)o.includes(u)||u.remove();const s=r?o.indexOf(r):-1;if(r){let u=r;for(let h=s-1;h>=0;h-=1){const d=o[h];d.nextElementSibling!==u&&this.signalList.insertBefore(d,u),u=d}}let a=r?r.nextElementSibling:this.signalList.firstElementChild;for(let u=s+1;u[a.key,a])),i=[],o=e.subject;["flights","military"].includes(o==null?void 0:o.layerId)&&(o!=null&&o.id)&&i.push({key:`flight:${o.layerId}:${o.id}`,tone:"track",title:o.label||o.id,detail:`${o.layerId==="military"?"MILITARY FLIGHT":"COMMERCIAL FLIGHT"} · CURRENT`,target:{layerId:o.layerId,id:String(o.id)},distanceM:-1});for(const a of e.cohorts)if(["flights","military"].includes(a.id))for(const c of a.nearest){const l=c.icao24||c.id;l&&i.push({key:`flight:${a.id}:${l}`,tone:a.id==="military"?"nearby military":"nearby",title:this.services.formatAwarenessLabel(c),detail:`${a.id==="military"?"MILITARY FLIGHT":"COMMERCIAL FLIGHT"} · ${Number.isFinite(c.distanceM)?`${c.distanceM<1e4?(c.distanceM/1e3).toFixed(1):Math.round(c.distanceM/1e3)} KM`:"DISTANCE UNKNOWN"}`,target:{layerId:a.id,id:String(l)},distanceM:c.distanceM??1/0})}i.sort((a,c)=>a.distanceM-c.distanceM);const r=i.slice(0,5).map(a=>{var c;return{...a,timestamp:((c=n.get(a.key))==null?void 0:c.timestamp)||e.evaluatedAt||Date.now()}});if(t){const a=e.cohorts.filter(c=>c.count===null).map(c=>c.source).join(" · ");r.splice(4,Math.max(0,r.length-4),{key:"input-status",tone:"warning",title:`${t} INPUT${t===1?"":"S"} UNKNOWN`,detail:a||"SOURCE STATUS UNAVAILABLE",target:null,timestamp:((s=n.get("input-status"))==null?void 0:s.timestamp)||e.evaluatedAt||Date.now()})}this.signalItems=r,this.signalSignatures.clear(),this.renderCockpitSignals()}function E6(e){var n,i;if(this.destroyed)return;const t=e.target.closest("button[data-signal-layer][data-signal-id]");t&&(e.preventDefault(),(i=(n=this.services.militaryAwarenessLayer).focusTarget)==null||i.call(n,t.dataset.signalLayer,t.dataset.signalId,{origin:"user"}))}function T6({recBottom:e,signalTop:t,stripHeight:n,viewportHeight:i,collapsedHeight:o=0,recGap:r=12,signalGap:s=8,minTopFloor:a=96,minTopRatio:c=.12}){const l=Math.max(0,Number(i)||0),u=Math.max(a,l*c),h=Math.max(u,(Number(e)||0)+r),d=Math.max(0,Number(n)||0),f=Number(t),p=Number.isFinite(f)?f:l,g=p-s-d,_=Math.max(u,Math.min(h,g)),m=Math.max(0,Number(o)||0)||50;return{top:_,maxHeight:Math.max(m,p-_-s)}}function k6({availableHeight:e,expandedHeight:t,collapsedHeight:n,gap:i=7,minimumExpandedHeight:o=120}){const r=Math.max(o,Number(e)||0),s=Math.max(0,Number(t)||0),a=Math.max(0,Number(n)||0),c=Math.max(0,Number(i)||0),l=s+c+a>r;return{primaryOnly:l,expandedMaxHeight:Math.max(o,r-(l?0:c+a))}}function A6(){if(this.destroyed)return!1;const e=this.context&&!this.context.hidden,t=this.signalStream&&!this.signalStream.hidden;!e&&!t||this.contextLayoutFrame!==null||(this.contextLayoutFrame=requestAnimationFrame(()=>{this.contextLayoutFrame=null,!this.destroyed&&(this.syncContextLayout(),this.syncSignalLayout())}))}function I6(e){const t=this.contextCollapsed;if(this.contextCollapsed=!!e,this.context&&(this.context.dataset.collapsed=String(this.contextCollapsed)),this.contextToggle){const n=!this.contextCollapsed;this.contextToggle.setAttribute("aria-expanded",String(n)),this.contextToggle.setAttribute("aria-label",`${n?"Collapse":"Expand"} Contact panel`),this.contextToggle.title=`${n?"Collapse":"Expand"} contact panel`;const i=this.contextToggle.querySelector(".material-symbols-outlined");i&&(i.textContent=n?"chevron_left":"chevron_right")}this.active&&t&&!this.contextCollapsed&&window.dispatchEvent(new CustomEvent("gev:cockpit-context-expanded")),this.scheduleContextLayout()}function R6(e,{user:t=!1}={}){const n=this.signalCollapsed;if(this.signalCollapsed=!!e,t&&(this.signalUserCollapsed=this.signalCollapsed),this.signalStream&&(this.signalStream.dataset.collapsed=String(this.signalCollapsed)),this.signalToggle){const i=!this.signalCollapsed;this.signalToggle.setAttribute("aria-expanded",String(i)),this.signalToggle.setAttribute("aria-label",`${i?"Collapse":"Expand"} cockpit briefing panel`),this.signalToggle.title=`${i?"Collapse":"Expand"} briefing panel`;const o=this.signalToggle.querySelector(".material-symbols-outlined");o&&(o.textContent=i?"right_panel_close":"right_panel_open")}this.signalCollapsed?this.stopBriefRotation():this.startBriefRotation({reset:!0}),this.active&&n&&!this.signalCollapsed&&window.dispatchEvent(new CustomEvent("gev:cockpit-signal-expanded")),this.scheduleContextLayout()}function L6(){if(!this.context||this.context.hidden)return;if(window.matchMedia("(max-width: 760px)").matches){this.context.dataset.layoutMode="compact-bottom",this.context.style.removeProperty("--cockpit-context-left"),this.context.style.removeProperty("--cockpit-context-top"),this.context.style.removeProperty("--cockpit-context-max-height");return}const e=Math.max(24,Math.min(58,window.innerWidth*.04));this.context.dataset.layoutMode="bottom-left",this.context.style.setProperty("--cockpit-context-left",`${e.toFixed(1)}px`),this.context.style.removeProperty("--cockpit-context-top"),this.context.style.removeProperty("--cockpit-context-max-height")}function P6(){var o,r,s,a,c,l;if(!this.signalStream||this.signalStream.hidden)return;const e=document.getElementById("cockpit-utility-controls");if(window.matchMedia("(max-width: 760px)").matches){this.signalStream.dataset.layoutMode="compact-top",e==null||e.classList.remove("layout-primary-only"),e==null||e.querySelectorAll(".cockpit-utility-control").forEach(u=>{const h=!!(e.querySelector(".cockpit-utility-control.is-expanded")&&!u.classList.contains("is-expanded"));u.setAttribute("aria-hidden",String(h))}),(o=this.hud)==null||o.style.removeProperty("--cockpit-utility-top"),(r=this.hud)==null||r.style.removeProperty("--cockpit-utility-max-height"),(s=this.hud)==null||s.style.removeProperty("--cockpit-utility-expanded-max-height"),this.signalStream.style.removeProperty("--cockpit-signal-right"),this.signalStream.style.removeProperty("--cockpit-signal-top"),this.signalStream.style.removeProperty("--cockpit-signal-max-height");return}const t=Math.max(24,Math.min(58,window.innerWidth*.04));this.signalStream.dataset.layoutMode="bottom-right",this.signalStream.style.setProperty("--cockpit-signal-right",`${t.toFixed(1)}px`),this.signalStream.style.removeProperty("--cockpit-signal-top"),this.signalStream.style.removeProperty("--cockpit-signal-max-height");const n=this.signalStream.getBoundingClientRect(),i=e==null?void 0:e.getBoundingClientRect();if(i){const u=e==null?void 0:e.querySelector(".cockpit-utility-control.is-expanded"),h=e==null?void 0:e.querySelector(".cockpit-utility-control:not(.is-expanded)"),d=h==null?void 0:h.querySelector(".cockpit-utility-launcher"),f=u?Math.max(u.scrollHeight,u.getBoundingClientRect().height):0,p=d?Math.max(K8,d.scrollHeight):0,g=document.querySelector("#intel-hud .hud-top-right"),_=n6(g)?g.getBoundingClientRect():null,m=T6({recBottom:_?_.bottom:0,signalTop:n.top,stripHeight:i.height,viewportHeight:window.innerHeight,collapsedHeight:p,recGap:z8,signalGap:j8,minTopFloor:q8,minTopRatio:W8}),b=m.maxHeight;(a=this.hud)==null||a.style.setProperty("--cockpit-utility-top",`${m.top.toFixed(1)}px`),(c=this.hud)==null||c.style.setProperty("--cockpit-utility-max-height",`${b.toFixed(2)}px`);const C=u&&h?k6({availableHeight:b,expandedHeight:f,collapsedHeight:p}):{primaryOnly:!1,expandedMaxHeight:b};e==null||e.classList.toggle("layout-primary-only",C.primaryOnly),(l=this.hud)==null||l.style.setProperty("--cockpit-utility-expanded-max-height",`${C.expandedMaxHeight.toFixed(2)}px`),e==null||e.querySelectorAll(".cockpit-utility-control").forEach(y=>{var M;const v=C.primaryOnly&&y===h;y.setAttribute("aria-hidden",String(v)),v&&y.contains(document.activeElement)&&((M=u==null?void 0:u.querySelector(".cockpit-utility-glyph"))==null||M.focus({preventScroll:!0}))})}}function x6(e){var n,i,o,r,s,a,c,l,u,h,d,f,p,g,_,m,b,C,y;if(this.destroyed)return!1;if(e.repeat||e.isComposing)return;if(e.key==="Escape"&&this.active){if((i=(n=e.target)==null?void 0:n.closest)!=null&&i.call(n,".cesium-credit-lightbox")||(o=document.getElementById("context-radio-dock"))!=null&&o.classList.contains("disclosure-open")||document.querySelector('#cockpit-utility-controls [aria-expanded="true"]'))return;if((r=this.context)!=null&&r.contains(e.target)&&!this.contextCollapsed){e.preventDefault(),e.stopImmediatePropagation(),this.setContextCollapsed(!0),e.target===this.contextToggle||(a=(s=this.contextToggle)==null?void 0:s.contains)!=null&&a.call(s,e.target)?(l=(c=this.contextToggle)==null?void 0:c.blur)==null||l.call(c):(u=this.contextToggle)==null||u.focus({preventScroll:!0});return}if((h=this.signalStream)!=null&&h.contains(e.target)&&!this.signalCollapsed){e.preventDefault(),e.stopImmediatePropagation(),this.setSignalCollapsed(!0,{user:!0}),e.target===this.signalToggle||(f=(d=this.signalToggle)==null?void 0:d.contains)!=null&&f.call(d,e.target)?(g=(p=this.signalToggle)==null?void 0:p.blur)==null||g.call(p):(_=this.signalToggle)==null||_.focus({preventScroll:!0});return}e.preventDefault(),e.stopImmediatePropagation(),this.exit();return}if((b=(m=e.target)==null?void 0:m.closest)!=null&&b.call(m,"input, textarea, select, [contenteditable]"))return;if(((C=e.key)==null?void 0:C.toLowerCase())==="c"&&!e.metaKey&&!e.ctrlKey&&!e.altKey){if(!this.active&&!!!(this.readAircraftInfo()&&((y=this.viewer.trackedEntity)!=null&&y.position))||(e.preventDefault(),e.stopImmediatePropagation(),!this.active&&!this.isEntryAllowed()))return;this.active?this.exit():this.enter();return}}class F6{constructor(t,{services:n,onVisionChange:i=null,onCameraTakeover:o=null,isEntryAllowed:r=null,onEntered:s=null,onExited:a=null,getInheritedVisionLabel:c=null,restoreTrackingFrame:l=null}={}){this.viewer=t,this.services=n,this.destroyed=!1,this.disposed=!1,this.active=!1,this.trackedEntity=null,this.trackedEntityWasShown=!0,this.heading=null,this.lastFrameMs=0,this.lastCameraUpdateMs=0,this.lastHudUpdateMs=0,this.lastContextUpdateMs=0,this.lastGroundProbeMs=0,this.contextNavigationDeadlineMs=0,this.surfaceWaitStartedMs=0,this.surfaceAcquiring=!1,this.surfaceFallback=!1,this.lastCompassSignature="",this.entry=document.getElementById("cockpit-entry"),this.tr3bToggle=document.getElementById("tr3b-toggle"),this._tr3bSignature=null,this.mapViewButton=document.getElementById("map-view-switch"),this.resetGlobeButton=document.getElementById("cockpit-reset-globe"),this.hud=document.getElementById("cockpit-hud"),this.entryFocusOrigin=null,this.callsign=document.getElementById("cockpit-callsign"),this.speed=document.getElementById("cockpit-speed-value"),this.speedRim=document.getElementById("cockpit-speed-rim"),this.speedRimValue=document.getElementById("cockpit-speed-rim-value"),this.speedRimTicks=Array.from(document.querySelectorAll("[data-speed-rim-tick]")),this.altitude=document.getElementById("cockpit-altitude-value"),this.altitudeRim=document.getElementById("cockpit-altitude-rim"),this.altitudeRimValue=document.getElementById("cockpit-altitude-rim-value"),this.altitudeRimTicks=Array.from(document.querySelectorAll("[data-altitude-rim-tick]")),this.headingValue=document.getElementById("cockpit-heading-value"),this.compassTape=document.getElementById("cockpit-compass-tape"),this.clock=document.getElementById("cockpit-clock"),this.position=document.getElementById("cockpit-position"),this.aircraftMeta=document.getElementById("cockpit-aircraft-meta"),this.route=document.getElementById("cockpit-route"),this.routeFrom=document.getElementById("cockpit-route-from"),this.routeTo=document.getElementById("cockpit-route-to"),this.routeStatus=document.getElementById("cockpit-route-status"),this.routeDirection=document.getElementById("cockpit-route-direction"),this.routeDirectionLabel=document.getElementById("cockpit-route-direction-label"),this.visionPrevious=document.getElementById("cockpit-vision-previous"),this.visionCurrent=document.getElementById("cockpit-vision-current"),this.visionCurrentLabel=document.getElementById("cockpit-vision-current-label"),this.visionNext=document.getElementById("cockpit-vision-next"),this.visionMode="optical",this.onVisionChange=i,this.onCameraTakeover=o,this.onEntered=s,this.onExited=a,this.getInheritedVisionLabel=typeof c=="function"?c:()=>"NORMAL",this.restoreTrackingFrame=typeof l=="function"?l:()=>!1,this.isEntryAllowed=typeof r=="function"?r:()=>!0,this.context=document.getElementById("cockpit-context"),this.contextSubject=document.getElementById("cockpit-context-subject"),this.contextNearestLabel=document.getElementById("cockpit-context-nearest-label"),this.contextBearing=document.getElementById("cockpit-context-bearing"),this.contextDistance=document.getElementById("cockpit-context-distance"),this.contextDirection=document.getElementById("cockpit-context-direction"),this.contextUncertainty=document.getElementById("cockpit-context-uncertainty"),this.contextUpdated=document.getElementById("cockpit-context-updated"),this.contextCohorts=new Map(Array.from(document.querySelectorAll("[data-context-cohort]")).map(u=>[u.dataset.contextCohort,u])),this.contextPrevious=document.getElementById("cockpit-context-previous"),this.contextNext=document.getElementById("cockpit-context-next"),this.contextToggle=document.getElementById("cockpit-context-toggle"),this.weatherToggle=document.getElementById("cockpit-weather-toggle"),this.weatherState=document.getElementById("cockpit-weather-state"),this.contextCollapsed=!1,this.signalStream=document.getElementById("cockpit-signal-stream"),this.signalList=document.getElementById("cockpit-signal-list"),this.signalToggle=document.getElementById("cockpit-signal-toggle"),this.briefKicker=document.getElementById("cockpit-brief-kicker"),this.briefSubtitle=document.getElementById("cockpit-brief-subtitle"),this.briefPrevious=document.getElementById("cockpit-brief-previous"),this.briefNext=document.getElementById("cockpit-brief-next"),this.briefAutoToggle=document.getElementById("cockpit-brief-auto"),this.briefPosition=document.getElementById("cockpit-brief-position"),this.briefSource=document.getElementById("cockpit-brief-source"),this.briefPages=Array.from(document.querySelectorAll("[data-cockpit-brief-page]")),this.briefTabs=Array.from(document.querySelectorAll("[data-cockpit-brief-index]")),this.newsStatus=document.getElementById("cockpit-news-status"),this.newsList=document.getElementById("cockpit-news-list"),this.localPlace=document.getElementById("cockpit-local-place"),this.localCoordinates=document.getElementById("cockpit-local-coordinates"),this.localTemperature=document.getElementById("cockpit-local-temperature"),this.localWind=document.getElementById("cockpit-local-wind"),this.localWindDirection=document.getElementById("cockpit-local-wind-direction"),this.localCondition=document.getElementById("cockpit-local-condition"),this.localCloud=document.getElementById("cockpit-local-cloud"),this.localPrecipitation=document.getElementById("cockpit-local-precipitation"),this.signalCollapsed=!1,this.signalUserCollapsed=!1,this.signalItems=[],this.signalSignatures=new Map,this.briefPageIndex=0,this.briefAutoRotateEnabled=!1,this.briefTimer=null,this.lastAircraftInfo=null,this.regionalBrief=null,this.regionalBriefAnchor=null,this.regionalBriefFetchedAt=0,this.regionalBriefAbort=null,this.regionalBriefRequestToken=0,this.regionalBriefSubjectId=null,this.contextLayoutFrame=null,this.contextLayoutStamp=null,this.scratchTarget=new Cesium.Cartesian3,this.cockpitAnchor=new Cesium.Cartesian3,this.cockpitAnchorValid=!1,this.scratchCamera=new Cesium.Cartesian3,this.scratchAdvance=new Cesium.Cartesian3,this.scratchCorrection=new Cesium.Cartesian3,this.scratchForward=new Cesium.Cartesian3,this.scratchHorizontal=new Cesium.Cartesian3,this.scratchUp=new Cesium.Cartesian3,this.scratchLocal=new Cesium.Cartesian3,this.scratchEnu=new Cesium.Matrix4,this.scratchAnchorCartographic=new Cesium.Cartographic,this.scratchCameraCartographic=new Cesium.Cartographic,this.scratchTargetCartographic=new Cesium.Cartographic,this._listenerRemovers=[],this._listenerRemovers.push(t.scene.preUpdate.addEventListener(()=>this.update()),t.trackedEntityChanged.addEventListener(()=>{this.active?this._adoptTrackedEntity(performance.now()):this.syncEntry()})),this._listen(this.entry,"click",()=>this.enter()),this._listen(this.tr3bToggle,"click",()=>this.toggleTrackedTr3b()),this._listen(this.mapViewButton,"click",()=>this.exit()),this._listen(this.visionPrevious,"click",()=>this.cycleVisionMode(-1)),this._listen(this.visionCurrent,"click",()=>this.cycleVisionMode(1)),this._listen(this.visionNext,"click",()=>this.cycleVisionMode(1)),this._listen(this.contextPrevious,"click",()=>this.navigateContext(-1,{origin:"user"})),this._listen(this.contextNext,"click",()=>this.navigateContext(1,{origin:"user"})),this._listen(this.contextToggle,"click",()=>this.setContextCollapsed(!this.contextCollapsed)),this._listen(this.weatherToggle,"click",()=>{const u=this.weatherToggle.getAttribute("aria-pressed")!=="true";this.syncWeatherToggle(u),window.dispatchEvent(new CustomEvent("gev:cockpit-weather-toggle",{detail:{enabled:u}}))}),this._listen(window,"gev:cockpit-weather-state",u=>{var h;this.syncWeatherToggle(((h=u==null?void 0:u.detail)==null?void 0:h.enabled)!==!1)}),this._listen(this.signalToggle,"click",()=>this.setSignalCollapsed(!this.signalCollapsed,{user:!0})),this._listen(this.signalList,"click",u=>this.handleSignalClick(u)),this._listen(this.briefPrevious,"click",()=>this.showBriefPage(this.briefPageIndex-1,{manual:!0})),this._listen(this.briefNext,"click",()=>this.showBriefPage(this.briefPageIndex+1,{manual:!0})),this._listen(this.briefAutoToggle,"click",()=>{this.setBriefAutoRotate(!this.briefAutoRotateEnabled)}),this.briefTabs.forEach(u=>this._listen(u,"click",()=>{this.showBriefPage(Number(u.dataset.cockpitBriefIndex),{manual:!0})})),this._listen(document,"visibilitychange",()=>{document.hidden?this.stopBriefRotation():this.briefAutoRotateEnabled&&this.startBriefRotation()}),this._listen(window,"resize",()=>this.scheduleContextLayout()),this._listen(document,"keydown",u=>this.onKeyDown(u),!0)}_listen(t,n,i,o){t!=null&&t.addEventListener&&(t.addEventListener(n,i,o),this._listenerRemovers.push(()=>t.removeEventListener(n,i,o)))}readAircraftInfo(){return L8.call(this)}dispatchCockpitModeChanged(t,n){return P8.call(this,t,n)}toggleTrackedTr3b(){return x8.call(this)}syncTr3bToggle(t){return F8.call(this,t)}syncEntry(){return S8.call(this)}navigateContext(t,n){return N8.call(this,t,n)}_adoptTrackedEntity(t,n){return D8.call(this,t,n)}enter(){return O8.call(this)}exit(t){return B8.call(this,t)}update(){return r6.call(this)}updateHud(t,n,i){return s6.call(this,t,n,i)}updateRoute(t){return a6.call(this,t)}syncWeatherToggle(t){return l6.call(this,t)}setVisionMode(t,n){return c6.call(this,t,n)}cycleVisionMode(t){return u6.call(this,t)}clearPredictiveRoute(){return d6.call(this)}updateContext(t,n){return h6.call(this,t,n)}showBriefPage(t,n){return f6.call(this,t,n)}setBriefAutoRotate(t){return m6.call(this,t)}startBriefRotation(t){return p6.call(this,t)}stopBriefRotation(){return g6.call(this)}updateLocalPosition(t){return _6.call(this,t)}maybeRefreshRegionalBrief(t){return b6.call(this,t)}renderRegionalBriefStatus(t,n){return C6.call(this,t,n)}renderRegionalBrief(t,n){return y6.call(this,t,n)}renderCockpitSignals(){return v6.call(this)}pushCockpitSignal(t,n,i,o,r){return M6.call(this,t,n,i,o,r)}updateCockpitSignals(t,n){return w6.call(this,t,n)}scheduleContextLayout(){return A6.call(this)}setContextCollapsed(t){return I6.call(this,t)}setSignalCollapsed(t,n){return R6.call(this,t,n)}syncContextLayout(){return L6.call(this)}syncSignalLayout(){return P6.call(this)}onKeyDown(t){return x6.call(this,t)}handleSignalClick(t){return E6.call(this,t)}stop(){var t;if(!this.destroyed){this.destroyed=!0,(t=this.regionalBriefAbort)==null||t.abort(),this.regionalBriefAbort=null,this.regionalBriefRequestToken+=1,this.stopBriefRotation(),this.contextLayoutFrame!==null&&cancelAnimationFrame(this.contextLayoutFrame),this.contextLayoutFrame=null;for(const n of this._listenerRemovers.splice(0))n==null||n()}}dispose(){this.disposed||(this.disposed=!0,this.stop(),this.exit({restoreTracking:!1}))}}class S6{constructor({standardPanel:t,cockpitPanel:n,groups:i,layout:o}){this.standardPanel=t,this.cockpitPanel=n,this.layout=o,this.active=!1,this.destroyed=!1,this.stopped=!1,this.restoreOwner=null,this.generation=0,this.frames=new Set,this.listeners=new AbortController,this.records=i.flatMap(([s,a])=>{const c=n==null?void 0:n.querySelector(`[data-cockpit-display-slot="${s}"]`);if(!a||!c||!a.parentNode)return[];const l=document.createComment(`cockpit-display-home:${s}`);return a.before(l),[{name:s,group:a,slot:c,anchor:l}]}),this.standardScrollTop=(t==null?void 0:t.scrollTop)||0,this.cockpitScrollTop=(n==null?void 0:n.scrollTop)||0;const r={passive:!0,signal:this.listeners.signal};t==null||t.addEventListener("scroll",()=>{this.active||(this.standardScrollTop=t.scrollTop)},r),n==null||n.addEventListener("scroll",()=>{this.active&&(this.cockpitScrollTop=n.scrollTop)},r),window.addEventListener("gev:cockpit-mode-changed",s=>{var a;this.setActive(((a=s==null?void 0:s.detail)==null?void 0:a.active)===!0)},{signal:this.listeners.signal}),this.setActive(document.body.classList.contains("cockpit-mode"))}_frame(t,n){const i=requestAnimationFrame(()=>{this.frames.delete(i),!this.stopped&&t===this.generation&&n()});this.frames.add(i)}_cancelFrames(){for(const t of this.frames)cancelAnimationFrame(t);this.frames.clear(),this.generation+=1}setActive(t,{settle:n=!0}={}){var c;if(this.stopped)return;const i=t===!0;if(this.active===i)return;this._cancelFrames();const o=this.generation,s=this.records.find(l=>l.group.contains(document.activeElement))?document.activeElement:null;this.restoreOwner=i?"cockpit":"standard",this.active=i;for(const l of this.records)i?l.slot.append(l.group):l.anchor.parentNode&&l.anchor.after(l.group);(c=this.cockpitPanel)==null||c.classList.toggle("uses-shared-display-controls",i);const a=()=>{i&&this.cockpitPanel&&(this.cockpitPanel.scrollTop=this.cockpitScrollTop),!i&&this.standardPanel&&(this.standardPanel.scrollTop=this.standardScrollTop)};if(!n){a(),this.restoreOwner=null;return}this._frame(o,()=>{var l;a(),(l=s==null?void 0:s.focus)==null||l.call(s,{preventScroll:!0}),this._frame(o,()=>{a(),this.restoreOwner=null})}),this.layout()}stop(){this.stopped||(this.stopped=!0,this._cancelFrames(),this.listeners.abort())}destroy(){var t;if(!this.destroyed){this.stop(),this.destroyed=!0,this.active=!1;for(const n of this.records)n.anchor.parentNode&&n.anchor.after(n.group),n.anchor.remove();(t=this.cockpitPanel)==null||t.classList.remove("uses-shared-display-controls"),this.standardPanel&&(this.standardPanel.scrollTop=this.standardScrollTop),this.records=[],this.restoreOwner=null}}}const N6=new Set(["contacts","space-missions","cockpit"]);function P0({action:e,explicitUserAction:t,succeeded:n,restoring:i=!1}){return!!(N6.has(e)&&t&&n&&!i)}function D6(){const e=[this._globalContextFlightsBtn,this._globalContextMissionsBtn].filter(Boolean);e.forEach((t,n)=>this.listen(t,"keydown",i=>{let o=null;i.key==="ArrowRight"?o=(n+1)%e.length:i.key==="ArrowLeft"?o=(n-1+e.length)%e.length:i.key==="Home"?o=0:i.key==="End"&&(o=e.length-1),o!==null&&(i.preventDefault(),e[o].focus({preventScroll:!0}),e[o].click())})),this.listen(this._globalContextFlightsBtn,"click",()=>{if(this.destroyed||this._contextModeChanging||this._clearSelectedLayersPromise)return;const t=this._contextMode==="flights"?null:"flights";this._claimContextVisualAuthority(),this._runUserFacingContextAction(n=>this._selectContextMode(t,{notificationToken:n}),"Contacts could not complete the requested transition; try again").then(n=>{!this.destroyed&&t&&P0({action:"contacts",explicitUserAction:!0,succeeded:n===!0})&&this.actions.setPanelCollapsed("global-context-panel",!1,{explicit:!0})})}),this.listen(this._globalContextMissionsBtn,"click",()=>{if(this.destroyed||this._contextModeChanging||this._clearSelectedLayersPromise)return;const t=this._contextMode==="space-missions"?null:"space-missions";this._claimContextVisualAuthority(),this._runUserFacingContextAction(n=>this._selectContextMode(t,{notificationToken:n}),"Space Missions could not complete the requested transition; try again").then(n=>{!this.destroyed&&t&&P0({action:"space-missions",explicitUserAction:!0,succeeded:n===!0})&&this.actions.setPanelCollapsed("global-context-panel",!1,{explicit:!0})})}),this.listen(this._installationsSearchBtn,"click",()=>{var n,i;if(this.destroyed||!((i=(n=this._dataManager)==null?void 0:n.layers)!=null&&i.has("military-installations")))return;const t=this._installationsSearchBtn;t.getAttribute("aria-busy")!=="true"&&(t.setAttribute("aria-disabled","true"),t.setAttribute("aria-busy","true"),this._runUserFacingContextAction(async o=>{var c,l,u,h;const r=await this._dataManager.setEnabled("military-installations",!0,{origin:"user",notificationToken:o});if(this.destroyed||r===!1||!this._dataManager.isEnabled("military-installations"))return!1;const s=await((l=(c=this.installations).searchNearby)==null?void 0:l.call(c));if(this.destroyed||s===!1)return!1;const a=(h=(u=this.installations).getStats)==null?void 0:h.call(u);return this.showToast((a==null?void 0:a.statusMessage)||((a==null?void 0:a.status)==="zoom-in"?"Zoom in to search mapped installations":"Nearby installations refreshed")),!0},"Nearby installations could not be refreshed; try again").finally(()=>{this.destroyed||(t.setAttribute("aria-disabled","false"),t.setAttribute("aria-busy","false"))}))})}function O6(){var o,r,s,a,c;if(this.destroyed)return;const e=this._contextMode==="flights",t=this._contextMode==="space-missions",n=this._globalContextPanel;n==null||n.classList.toggle("context-enabled",e||t),n==null||n.setAttribute("data-context-mode",this._contextMode||"none"),(o=this._globalContextFlightsBtn)==null||o.classList.toggle("active",e),(r=this._globalContextFlightsBtn)==null||r.setAttribute("aria-selected",String(e)),(s=this._globalContextMissionsBtn)==null||s.classList.toggle("active",t),(a=this._globalContextMissionsBtn)==null||a.setAttribute("aria-selected",String(t));const i=!!this._contextModeChanging;for(const l of[this._globalContextFlightsBtn,this._globalContextMissionsBtn])l&&(l.disabled=!1,l.tabIndex=0,l.setAttribute("aria-disabled",String(i)),l.setAttribute("aria-busy",String(i)));this._contextModeStandby&&(this._contextModeStandby.hidden=e||t),this._contextFlightsView&&(this._contextFlightsView.hidden=!e),this._contextMissionsView&&(this._contextMissionsView.hidden=!t),(c=this.cockpitView)==null||c.syncEntry(),this.actions.syncDetection(),this.actions.scheduleLayout()}const iT=Object.freeze({flights:new Set(["military-awareness","flights","military","ais-live-vessels","military-installations"]),"space-missions":new Set(["rocket-launches","satellites"])}),Xm=new Set(["radio"]);function Uo(e,t=null){return e==="user"||e==="voice"}function B6({restoreState:e,change:t}){return!(e!=null&&e.enabledLayerIds)||(t==null?void 0:t.type)!=="visibility"||!Uo(t.origin,t.layerId)?!1:(e.explicitLayerStates||(e.explicitLayerStates=new Map),e.explicitLayerStates.set(t.layerId,!!t.enabled),t.enabled?e.enabledLayerIds.add(t.layerId):e.enabledLayerIds.delete(t.layerId),!0)}async function V6({restoreState:e,setEnabled:t,notificationToken:n=null}){if(e!=null&&e.cancelled)return null;const i=[...(e==null?void 0:e.explicitLayerStates)||[]],o=await Promise.allSettled(i.map(([l,u])=>t(l,u,{origin:"context-intent-replay",...n?{notificationToken:n}:{}}))),r=o.flatMap((l,u)=>l.status==="rejected"||l.value===!1?[u]:[]);if(r.length===0)return null;const s=r.map(l=>i[l][0]),a=r.map(l=>o[l]).find(l=>l.status==="rejected"),c=(a==null?void 0:a.reason)instanceof Error?a.reason:new Error(`Context intent replay failed for ${s.map(l=>`"${l}"`).join(", ")}`);return c.failedLayerIds=[...new Set([...Array.isArray(c.failedLayerIds)?c.failedLayerIds:[],...s])],c}function Tc(e,t){return e?(t&&(e.failedLayerIds=[...new Set([...Array.isArray(e.failedLayerIds)?e.failedLayerIds:[],...Array.isArray(t.failedLayerIds)?t.failedLayerIds:[]])]),e):t||null}async function H6({operation:e,onFailure:t,falseIsFailure:n=!0}){try{const i=await e();if(n&&i===!1)throw new Error("Context transition did not complete");return i}catch(i){try{t==null||t(i)}catch{}return!1}}const oT=Object.freeze(["military-awareness","rocket-launches"]);function rT(e,t=!1){var i;if(!e)return;const n=!!e._contextModeChanging;e._contextModeChanging=!!t,n&&!e._contextModeChanging&&((i=e._syncContextModeButtons)==null||i.call(e))}async function $6(e,t){const n=!!(e!=null&&e._contextModeChanging);e._contextModeChanging=!0;try{return await t()}finally{rT(e,n)}}function G6({contextMode:e,globalContextEnabled:t,change:n}){if((n==null?void 0:n.type)!=="visibility"||!Uo(n.origin,n.layerId)||n.layerId==="military-awareness"||Xm.has(n.layerId)||!!!(t||e))return!1;const o=iT[e]||new Set(["military-awareness"]);return n.enabled?!1:!!(e&&o.has(n.layerId))}function Qm(e){return new Set([...iT[e]||["military-awareness"],...Xm])}function x0(e){return!!(["visibility-requested","visibility-will-change"].includes(e==null?void 0:e.type)&&Uo(e.origin,e.layerId)&&e.enabled&&oT.includes(e.layerId))}function U6({change:e,clearInFlight:t}){return!!(t&&(e==null?void 0:e.type)==="visibility-requested"&&e.layerId==="rocket-launches"&&e.enabled===!0&&Uo(e.origin,e.layerId)&&Number.isInteger(e.intentEpoch))}function z6({snapshot:e,change:t,effectiveContextMode:n=null}){var r;if(!(e!=null&&e.userAdded)||(t==null?void 0:t.type)!=="visibility"||!Uo(t.origin,t.layerId))return!1;const i=Xm.has(t.layerId);if(t.enabled)return oT.includes(t.layerId)?!1:t.adoptedFromSelection?(e.userAdded.add(t.layerId),!0):Qm(n).has(t.layerId)&&!i?!1:(e.userAdded.add(t.layerId),i&&((r=e.userRemoved)==null||r.delete(t.layerId)),!0);const o=e.userAdded.delete(t.layerId);if(i&&e.userRemoved){const s=e.userRemoved.has(t.layerId);return e.userRemoved.add(t.layerId),o||!s}return o}function j6(e,t=null,n=[]){const i=new Set(t||e||[]);for(const o of n||[])i.delete(o);return i}function sT({contextMode:e,change:t,layerName:n=null}){return e!=="space-missions"||(t==null?void 0:t.enabled)!==!0||Qm("space-missions").has(t.layerId)?null:`Space Missions isolates replay data. Exit the mode to enable ${String(n||t.layerId||"that layer")}.`}function q6({change:e}){return(e==null?void 0:e.type)!=="visibility-cancelled"||e.layerId!=="rocket-launches"||e.enabled!==!0?"ignore":e.cancellationReason==="superseded"&&Number.isInteger(e.successorIntentEpoch)&&e.successorIntentEpoch>e.intentEpoch&&e.successorEnabled===!0?"replacement":"restore"}function W6(e={}){const t=new Set([...e.enabledLayerIds||[],...e.userAdded||[]]);for(const n of e.userRemoved||[])t.delete(n);return t}function aT({contextMode:e,contextModeChanging:t,flightsEnabled:n,militaryEnabled:i}){return e==="flights"&&!t&&!!n&&!!i}const K6=Object.freeze({flights:"contacts","space-missions":"space-missions"});function lT(e,{emptyAs:t="off"}={}){return e?K6[e]||e:t}function Y6(e){const t=Promise.resolve(e);return this._contextLayerReactionPromises.add(t),t.then(()=>this._contextLayerReactionPromises.delete(t),()=>this._contextLayerReactionPromises.delete(t)),t}async function X6(){for(;this._contextLayerReactionPromises.size>0;)await Promise.allSettled([...this._contextLayerReactionPromises])}function Q6({excludeLayerIds:e=[]}={}){var n;if(!this._dataManager||this._contextSessionSnapshot)return;const t={};for(const i of["military-awareness","satellites"]){const o=this._dataManager.getLayerParams(i);o&&(t[i]=o)}this._contextSessionSnapshot={enabledLayerIds:j6(this._dataManager.getEnabledLayerIds(),(n=this._contextRestoreState)==null?void 0:n.enabledLayerIds,e),userAdded:new Set,userRemoved:new Set,params:t}}async function Z6({excludeLayerIds:e=[],notificationToken:t=null,signal:n=null}={}){const i=this._contextSessionSnapshot;if(!i||!this._dataManager)return;this._contextSessionSnapshot=null;const o={enabledLayerIds:W6(i),explicitLayerStates:new Map};this._contextRestoreState=o;for(const[l,u]of Object.entries(i.params))this._dataManager.setLayerParams(l,u);let r=null;const s=async(l=null)=>{const u="military-awareness",h=!o.enabledLayerIds.has(u)&&this._dataManager.isEffectivelyEnabled(u);if(h&&await this._dataManager.setEnabled(u,!1,{origin:"context-restore",...t?{notificationToken:t}:{},...l?{signal:l}:{}})===!1){const f=new Error("Failed to settle Contacts before restoring Context");throw f.failedLayerIds=[u],f}await this._dataManager.restoreEnabledLayerIds(o.enabledLayerIds,{origin:"context-restore",excludeLayerIds:h?[...e,u]:e,notificationToken:t,...l?{signal:l}:{}})};try{await s(n)}catch(l){if(r=l,n!=null&&n.aborted&&!o.cancelled)try{await s(null),r=null}catch(u){r=Tc(r,u)}}finally{this._contextRestoreState===o&&(this._contextRestoreState=null)}if(o.cancelled)return;const a=n!=null&&n.aborted?null:n,c=await V6({restoreState:o,setEnabled:(l,u,h={})=>this._dataManager.setEnabled(l,u,{...h,...a?{signal:a}:{}}),notificationToken:t});if(r=Tc(r,c),r&&!this._contextSessionSnapshot&&(this._contextSessionSnapshot={enabledLayerIds:new Set(o.enabledLayerIds),userAdded:new Set,userRemoved:new Set,params:i.params}),r)throw r}async function J6(e,{notificationToken:t=null}={}){var n,i;return await((i=(n=this._dataManager)==null?void 0:n.waitForLayerSettled)==null?void 0:i.call(n,e)),this._restoreContextSession({notificationToken:t})}async function ej(e,{notificationToken:t=null,signal:n=null}={}){var r,s,a,c,l,u;if(this.destroyed||!this._dataManager||this._clearSelectedLayersPromise)return!1;this._contextTransitionFailedLayerIds=[];const i=++this._contextModeGeneration,o=()=>!this.destroyed&&i===this._contextModeGeneration;this._contextModeEntryIntent=null,this._contextModeReplacementIntent=null,this._contextModeChanging=!0,this._syncContextModeButtons();try{if(e!=="flights"&&((r=this.cockpitView)!=null&&r.active)&&this.cockpitView.exit({restoreTracking:!1}),!e)return this._contextMode=null,this._syncContextModeButtons(),await this._restoreContextSession({notificationToken:t,signal:n}),o();if(!!(this._contextMode&&this._contextMode!==e)&&(this._contextMode=null,await this._restoreContextSession({notificationToken:t,signal:n}),!o()||n!=null&&n.aborted))return!1;this._captureContextSessionSnapshot(),this._contextMode=e,this._syncContextModeButtons();try{await this._clearLayersOutsideContextMode(e,{notificationToken:t,signal:n})}catch(b){if(!o())return!1;let C=b;console.warn(`[Context] ${e} isolation failed`,b),this._contextMode=null,this._syncContextModeButtons();try{await this._restoreContextSession({notificationToken:t})}catch(y){throw C=Tc(C,y),this._contextTransitionFailedLayerIds=[...C.failedLayerIds||[]],C}return this._contextTransitionFailedLayerIds=[...(C==null?void 0:C.failedLayerIds)||[]],!1}if(!o())return!1;const d=e==="flights"?"military-awareness":"rocket-launches";e==="flights"&&this._dataManager.setLayerParams("military-awareness",{passive:!1});let f=!1,p=null,g=null,_=null;try{g=this._dataManager._setEnabledWithIntent(d,!0,{notificationToken:t,...n?{signal:n}:{}}),this._contextModeEntryIntent={generation:i,layerId:d,intentEpoch:g.intentEpoch},f=await g.promise,_=await((a=(s=this._dataManager)._waitForVisibilityIntent)==null?void 0:a.call(s,d,g.intentEpoch))}catch(b){p=b}if(!o())return!1;let m=e==="space-missions"&&((c=this._contextModeReplacementIntent)==null?void 0:c.generation)===i&&this._contextModeReplacementIntent.layerId===d?this._contextModeReplacementIntent:null;for(;m;){const b=await((u=(l=this._dataManager)._waitForVisibilityIntent)==null?void 0:u.call(l,d,m.intentEpoch));if(_=b,!o())return!1;if((b==null?void 0:b.intentEpoch)===m.intentEpoch&&b.enabled===!0&&b.succeeded===!0)return this._contextModeEntering=null,this._contextModeEntryIntent=null,this._contextModeReplacementIntent=null,this._syncContextModeButtons(),!0;const y=(b==null?void 0:b.cancellationReason)==="superseded"&&b.successorEnabled===!0&&Number.isInteger(b.successorIntentEpoch)&&b.successorIntentEpoch>m.intentEpoch?b.successorIntentEpoch:null;m=y===null?null:{generation:i,layerId:d,intentEpoch:y}}if(p||f===!1||!this._dataManager.isEnabled(d)){const b=(_==null?void 0:_.succeeded)===!1&&["caller-abort","resource-abort","superseded"].includes(_.cancellationReason);let C=null;b||(C=p instanceof Error?p:new Error(`Context activation failed for: ${d}`),C.failedLayerIds=[...new Set([...C.failedLayerIds||[],d])],this._contextTransitionFailedLayerIds=[...C.failedLayerIds],console.warn(`[Context] ${e} activation failed; restoring previous layers`,p||"not enabled")),this._contextMode=null,this._contextModeEntryIntent=null,this._contextModeReplacementIntent=null,this._syncContextModeButtons();try{await this._restoreContextSession({excludeLayerIds:[d],notificationToken:t})}catch(y){throw C=Tc(C,y),this._contextTransitionFailedLayerIds=[...(C==null?void 0:C.failedLayerIds)||[]],C}return b?null:!1}return this._contextModeEntryIntent=null,!0}finally{o()&&(this._contextModeChanging=!1,this._syncContextModeButtons())}}async function tj({notificationToken:e=null}={}){var t;this._contextModeGeneration+=1,this._contextModeChanging=!0,this._contextMode=null,this._contextModeEntryIntent=null,this._contextModeReplacementIntent=null,(t=this.cockpitView)!=null&&t.active&&this.cockpitView.exit({restoreTracking:!1}),this._syncContextModeButtons();try{await this._restoreContextSession({notificationToken:e})}finally{this._contextModeChanging=!1,this._syncContextModeButtons()}}async function nj(e=null,{notificationToken:t=null,signal:n=null}={}){const i=Qm(e),o=[];for(const[a]of this._dataManager.layers||[])!i.has(a)&&this._dataManager.isEffectivelyEnabled(a)&&o.push({layerId:a,transition:this._dataManager.setEnabled(a,!1,{notificationToken:t,...n?{signal:n}:{}})});const r=await Promise.all(o.map(({transition:a})=>a)),s=o.filter(({layerId:a},c)=>r[c]===!1||this._dataManager.isEnabled(a)).map(({layerId:a})=>a);if(s.length>0){const a=new Error(`Context isolation failed for: ${s.join(", ")}`);throw a.failedLayerIds=s,a}}function ij(e){var n,i,o,r,s;if(this.destroyed||((e==null?void 0:e.layerId)==="radio"&&["visibility-transition","visibility","visibility-cancelled","visibility-failed"].includes(e.type)&&this.actions.refreshRadio(),(e==null?void 0:e.type)==="visibility-transition"))return;const t=this._contextModeEntering||this._contextMode;if((e==null?void 0:e.type)==="visibility-cancelled"){const a=q6({change:e});if(((n=this._contextModeDeferredEntryIntent)==null?void 0:n.layerId)===e.layerId&&this._contextModeDeferredEntryIntent.intentEpoch===e.intentEpoch&&a!=="replacement"&&(this._contextModeDeferredEntryIntent=null),a==="replacement"){this._contextModeEntering="space-missions";const c=this._contextModeEntryIntent;(c==null?void 0:c.generation)===this._contextModeGeneration&&c.layerId===e.layerId&&c.intentEpoch===e.intentEpoch&&(this._contextModeReplacementIntent={generation:c.generation,layerId:e.layerId,intentEpoch:e.successorIntentEpoch})}else a==="restore"&&(this._contextModeEntering=null,this._contextModeEntryIntent=null,this._contextModeReplacementIntent=null,this._contextSessionSnapshot&&!this._contextModeChanging&&(this._contextMode=null,this._trackContextLayerReaction(this._runUserFacingContextAction(async c=>(await this._restoreContextSessionAfterLayerSettles(e.layerId,{notificationToken:c}),!0),"Space Missions cancellation could not restore the previous layer state"))));this._syncContextModeButtons();return}if((e==null?void 0:e.layerId)==="rocket-launches"&&["visibility","visibility-blocked","visibility-failed"].includes(e.type)&&(this._contextModeEntering=null),(e==null?void 0:e.type)==="visibility-blocked"){this._userFacingContextNotificationTokens.has(e.notificationToken)||this.showToast(e.reason||"That layer is unavailable in the current Context mode"),this._syncContextModeButtons();return}if((e==null?void 0:e.type)==="visibility-failed"){const a=`${e.layerId} could not ${e.enabled?"start":"stop"} cleanly`;["military-awareness","rocket-launches"].includes(e.layerId)&&e.enabled&&this._contextSessionSnapshot&&!this._contextModeChanging?(this._contextMode=null,this._trackContextLayerReaction(this._runUserFacingContextAction(async l=>(await this._restoreContextSessionAfterLayerSettles(e.layerId,{notificationToken:l}),this.showToast(a),!0),a))):this._userFacingContextNotificationTokens.has(e.notificationToken)||this.showToast(a),this._syncContextModeButtons();return}if((e==null?void 0:e.type)!=="visibility-will-change"){if(z6({snapshot:this._contextSessionSnapshot,change:e,effectiveContextMode:t}),B6({restoreState:this._contextRestoreState,change:e}),G6({contextMode:this._contextMode,globalContextEnabled:!!((i=this._dataManager)!=null&&i.isEnabled("military-awareness")),change:e})){this._trackContextLayerReaction(this._runUserFacingContextAction(a=>this._deactivateContextForLayerChange({notificationToken:a})));return}if(!this._contextModeChanging)if(e.layerId==="military-awareness")this._contextMode=e.enabled||this._contextMode==="flights"?null:this._contextMode,e.enabled?this._syncContextModeButtons():this._contextSessionSnapshot&&this._trackContextLayerReaction(this._runUserFacingContextAction(a=>this._deactivateContextForLayerChange({notificationToken:a})));else if(e.layerId==="rocket-launches"){if(!(Uo(e.origin,e.layerId)||this._contextMode==="space-missions"||t==="space-missions"))return;this._contextMode=e.enabled?"space-missions":this._contextMode==="space-missions"?null:this._contextMode,e.enabled?this._syncContextModeButtons():this._contextSessionSnapshot&&this._trackContextLayerReaction(this._runUserFacingContextAction(c=>this._deactivateContextForLayerChange({notificationToken:c})))}else this._contextMode==="flights"&&["flights","military","ais-live-vessels","military-installations"].includes(e.layerId)&&!e.enabled&&this._trackContextLayerReaction(this._runUserFacingContextAction(a=>this._deactivateContextForLayerChange({notificationToken:a})));(o=this.cockpitView)!=null&&o.active&&!aT({contextMode:this._contextMode,contextModeChanging:this._contextModeChanging,flightsEnabled:!!((r=this._dataManager)!=null&&r.isEnabled("flights")),militaryEnabled:!!((s=this._dataManager)!=null&&s.isEnabled("military"))})&&this.cockpitView.exit({restoreTracking:!1}),this._syncContextModeButtons()}}async function oj(e,t="Context could not restore every layer; try again",{falseIsFailure:n=!0}={}){if(this.destroyed)return!1;const i=Symbol("user-facing-context-action");this._userFacingContextNotificationTokens.add(i);try{return await H6({operation:()=>e(i),falseIsFailure:n,onFailure:o=>{this.destroyed||(console.warn("[Context] user-facing transition failed",o),this.showToast(t))}})}finally{this._userFacingContextNotificationTokens.delete(i)}}function rj(){this.actions.claimVisualAuthority()}function sj(){return{mode:this._contextMode||null,active:!!this._contextMode,changing:!!this._contextModeChanging,entering:this._contextModeEntering||null,canContact:!this._contextMode||this._contextMode==="flights",canMission:!this._contextMode||this._contextMode==="space-missions",snapshotCaptured:!!this._contextSessionSnapshot}}async function aj(e,{notificationToken:t=null,signal:n=null,isCurrent:i=null,claimVisualAuthority:o=!0}={}){var a,c;const r=()=>!this.destroyed&&!(n!=null&&n.aborted)&&(typeof i!="function"||i()),s=()=>{var l;return{ok:!1,action:"set_context_mode",cancelled:!0,error:"Context request was superseded by a newer voice turn",...this.getContextModeState(),...(l=this._contextTransitionFailedLayerIds)!=null&&l.length?{failedLayerIds:[...this._contextTransitionFailedLayerIds]}:{}}};if(!r())return s();try{if(!e||e==="off"){o&&this._claimContextVisualAuthority();const p=await this._selectContextMode(null,{notificationToken:t,signal:n});if(p===null||!r()&&p!==!0)return s();const g=this.getContextModeState();return{ok:p===!0,action:"set_context_mode",mode:g.mode,...g,...p===!0?{}:{error:"Context mode transition did not complete"},...(a=this._contextTransitionFailedLayerIds)!=null&&a.length?{failedLayerIds:[...this._contextTransitionFailedLayerIds]}:{}}}const l=e==="contacts"?"flights":e;if(!["flights","space-missions"].includes(l))return{ok:!1,action:"set_context_mode",error:`Unknown context mode: ${e}`,mode:this._contextMode,...this.getContextModeState()};const u=this._contextMode;o&&this._claimContextVisualAuthority();const h=await this._selectContextMode(l,{notificationToken:t,signal:n});if(h===null||!r()&&h!==!0)return s();const d=this.getContextModeState(),f=h!==!0&&!!u&&u!==l&&!d.mode;return{ok:h===!0,action:"set_context_mode",mode:d.mode,...d,...h===!0?{}:{error:f?`Switch to ${lT(l)} did not complete — Context is now off`:"Context mode transition did not complete",...f?{contextOff:!0,priorMode:u}:{}},...(c=this._contextTransitionFailedLayerIds)!=null&&c.length?{failedLayerIds:[...this._contextTransitionFailedLayerIds]}:{}}}catch(l){return r()?{ok:!1,action:"set_context_mode",error:(l==null?void 0:l.message)||"Context mode transition failed",...Array.isArray(l==null?void 0:l.failedLayerIds)?{failedLayerIds:[...l.failedLayerIds]}:{},...this.getContextModeState()}:{...s(),...Array.isArray(l==null?void 0:l.failedLayerIds)?{failedLayerIds:[...l.failedLayerIds]}:{}}}}function lj(){var o;if(this.destroyed)return Promise.resolve({targetIds:[],items:[],clearedIds:[],notClearedIds:[],cancelled:!0});if(this._clearSelectedLayersPromise)return this._clearSelectedLayersPromise;if(!((o=this._dataManager)!=null&&o.clearSelectedLayers))return Promise.resolve({targetIds:[],items:[],clearedIds:[],notClearedIds:[]});const e=++this._contextModeGeneration,t=Symbol("clear-selected-layers");this._contextRestoreState&&(this._contextRestoreState.cancelled=!0),this._contextModeChanging=!0,this._contextMode=null,this._contextModeEntering=null,this._contextModeEntryIntent=null,this._contextModeReplacementIntent=null,this._contextSessionSnapshot=null,this._contextRestoreState=null,this._preservePanelStateDuringLayerClear=!0,this._syncContextModeButtons(),this._userFacingContextNotificationTokens.add(t),this.setClearBusy(!0);const n=this._dataManager.clearSelectedLayers({origin:"user",notificationToken:t});this._clearSelectedLayersManagerPromise=n;const i=n.then(r=>(r.targetIds.length===0?this.showToast("No selected data layers"):r.notClearedIds.length>0?this.showToast(`${r.notClearedIds.length} data layer${r.notClearedIds.length===1?"":"s"} could not be cleared`):this.showToast(`Cleared ${r.clearedIds.length} data layer${r.clearedIds.length===1?"":"s"}`),r)).catch(r=>(console.warn("[Data] clear selected layers failed",r),this.showToast("Selected data layers could not be cleared"),{targetIds:[],items:[],clearedIds:[],notClearedIds:[],error:r})).finally(()=>{this._userFacingContextNotificationTokens.delete(t),e===this._contextModeGeneration&&(this._contextModeChanging=!1,this._syncContextModeButtons()),this.setClearBusy(!1),this._preservePanelStateDuringLayerClear=!1,this._clearSelectedLayersManagerPromise=null,this._clearSelectedLayersPromise=null});return this._clearSelectedLayersPromise=i,i}function cj(e){var t,n,i,o,r;this.disconnect(),!this.destroyed&&(this._dataManager=e||null,this._contextManagerUnsubscribe=(n=(t=this._dataManager)==null?void 0:t.subscribe)==null?void 0:n.call(t,s=>{String((s==null?void 0:s.type)||"").startsWith("visibility")&&this._handleContextLayerChange(s)}),typeof((i=this._dataManager)==null?void 0:i.subscribeVisibilityRequests)=="function"&&(this._dataManagerVisibilityRequestUnsubscribe=this._dataManager.subscribeVisibilityRequests(s=>{this.destroyed||(x0(s)?(this._captureContextSessionSnapshot({excludeLayerIds:[s.layerId]}),U6({change:s,clearInFlight:!!this._clearSelectedLayersPromise})&&(this._contextModeDeferredEntryIntent={layerId:s.layerId,intentEpoch:s.intentEpoch,origin:s.origin},this._contextModeEntering="space-missions",this._syncContextModeButtons())):(s==null?void 0:s.layerId)==="rocket-launches"&&s.enabled===!1&&Uo(s.origin,s.layerId)&&(this._contextModeDeferredEntryIntent=null,this._clearSelectedLayersPromise&&(this._contextSessionSnapshot=null,this._contextModeEntering=null,this._syncContextModeButtons())))})),typeof((o=this._dataManager)==null?void 0:o.addVisibilityGuard)=="function"&&(this._dataManagerVisibilityGuardUnsubscribe=this._dataManager.addVisibilityGuard(async s=>{var l,u,h,d,f,p,g;if(this.destroyed)return null;const a=((d=(h=(u=(l=this._dataManager)==null?void 0:l.layers)==null?void 0:u.get(s.layerId))==null?void 0:h.module)==null?void 0:d.name)||s.layerId,c=sT({contextMode:this._contextModeEntering||this._contextMode,change:s,layerName:a});if(c)return c;if(s.enabled&&["military-awareness","rocket-launches"].includes(s.layerId)&&x0(s)&&(!this._contextModeChanging||s.layerId==="rocket-launches"&&((f=this._contextModeDeferredEntryIntent)==null?void 0:f.intentEpoch)===s.intentEpoch)){const _=s.layerId==="rocket-launches"?"space-missions":null,m=((p=this._contextModeDeferredEntryIntent)==null?void 0:p.intentEpoch)===s.intentEpoch,b=m?!1:this._contextModeChanging,C=s.notificationToken||Symbol("direct-context-shell-entry"),y=!s.notificationToken;y&&this._userFacingContextNotificationTokens.add(C),this._contextModeEntering=_,this._contextModeChanging=!0;try{if(m){if(await this._clearSelectedLayersManagerPromise,this.destroyed||((g=this._contextModeDeferredEntryIntent)==null?void 0:g.intentEpoch)!==s.intentEpoch)return!1;this._contextModeDeferredEntryIntent=null}if(await this._clearLayersOutsideContextMode(_,{notificationToken:C}),this.destroyed)return!1}catch(v){this._contextModeEntering=null,console.warn(`[Context] ${s.layerId} isolation failed`,v);try{await this._restoreContextSession({excludeLayerIds:[s.layerId],notificationToken:C})}catch(M){console.warn(`[Context] ${s.layerId} rollback failed`,M)}return`${_==="space-missions"?"Space Missions":"Context"} could not start because another layer did not stop cleanly`}finally{y&&this._userFacingContextNotificationTokens.delete(C),this.destroyed||rT(this,b)}}return null})),typeof((r=this._dataManager)==null?void 0:r.subscribeBeforeDestroy)=="function"&&(this._dataManagerBeforeDestroyUnsubscribe=this._dataManager.subscribeBeforeDestroy(async({layerId:s}={})=>{this.destroyed||!this._contextSessionSnapshot||await $6(this,async()=>{var a;this._contextMode=null,(a=this.cockpitView)==null||a.exit({restoreTracking:!1}),this._syncContextModeButtons(),await this._restoreContextSession({excludeLayerIds:s?[s]:[]})})})),this._syncContextModeButtons())}class uj{constructor({elements:t,installations:n,actions:i}){Object.assign(this,t),this.installations=n,this.actions=i,this.listeners=new AbortController,this.destroyed=!1,this._dataManager=null,this._contextMode=null,this._contextModeChanging=!1,this._contextModeGeneration=0,this._contextModeEntering=null,this._contextModeEntryIntent=null,this._contextModeReplacementIntent=null,this._contextModeDeferredEntryIntent=null,this._contextSessionSnapshot=null,this._contextRestoreState=null,this._contextLayerReactionPromises=new Set,this._preservePanelStateDuringLayerClear=!1,this._userFacingContextNotificationTokens=new Set,this._clearSelectedLayersPromise=null,this._clearSelectedLayersManagerPromise=null,this._initGlobalContextPanel()}showToast(...t){this.destroyed||this.actions.showToast(...t)}setClearBusy(...t){this.destroyed||this.actions.setClearBusy(...t)}get cockpitView(){return this.actions.getCockpit()}listen(t,n,i,o={}){t==null||t.addEventListener(n,i,{...o,signal:this.listeners.signal})}connect(t){return cj.call(this,t)}disconnect(){var t;for(const n of["_contextManagerUnsubscribe","_dataManagerBeforeDestroyUnsubscribe","_dataManagerVisibilityGuardUnsubscribe","_dataManagerVisibilityRequestUnsubscribe"])(t=this[n])==null||t.call(this),this[n]=null}stop(){this.destroyed||(this.destroyed=!0,this._contextModeGeneration++,this.listeners.abort())}async restoreForDisposal(){this._contextModeChanging=!0,this._contextMode=null,await this._restoreContextSession()}_initGlobalContextPanel(...t){return D6.call(this,...t)}_syncContextModeButtons(...t){return O6.call(this,...t)}_trackContextLayerReaction(...t){return Y6.call(this,...t)}_waitForContextLayerSettlement(...t){return X6.call(this,...t)}_captureContextSessionSnapshot(...t){return Q6.call(this,...t)}_restoreContextSession(...t){return Z6.call(this,...t)}_restoreContextSessionAfterLayerSettles(...t){return J6.call(this,...t)}_selectContextMode(...t){return ej.call(this,...t)}_deactivateContextForLayerChange(...t){return tj.call(this,...t)}_clearLayersOutsideContextMode(...t){return nj.call(this,...t)}_handleContextLayerChange(...t){return ij.call(this,...t)}_runUserFacingContextAction(...t){return oj.call(this,...t)}_claimContextVisualAuthority(...t){return rj.call(this,...t)}getContextModeState(...t){return sj.call(this,...t)}setContextMode(...t){return aj.call(this,...t)}clearSelectedLayers(...t){return lj.call(this,...t)}}function dj(){var e;this._cctvFrameRequestToken+=1,this._cctvFramePreloader&&(this._cctvFramePreloader.onload=null,this._cctvFramePreloader.onerror=null),this._cctvFramePreloader=null,this._cctvFrame&&(this._cctvFrame.classList.remove("active"),this._cctvFrame.removeAttribute("src"),this._cctvFrame.dataset.cameraId="",this._cctvFrame.dataset.currentSrc="",this._cctvFrame.dataset.loading="",this._cctvFrame.dataset.error=""),(e=this._cctvFrameWrap)==null||e.classList.remove("loading","has-frame")}function hj(e,t,n){var r,s,a;if(this.destroyed||!this._cctvFrame||!e)return;n&&(this._cctvFrame.classList.remove("active"),this._cctvFrame.removeAttribute("src"),(r=this._cctvFrameWrap)==null||r.classList.remove("has-frame")),this._cctvFramePreloader&&(this._cctvFramePreloader.onload=null,this._cctvFramePreloader.onerror=null);const i=++this._cctvFrameRequestToken;this._cctvFrame.dataset.cameraId=t,this._cctvFrame.dataset.currentSrc=e,this._cctvFrame.dataset.loading="true",this._cctvFrame.dataset.error="",(a=this._cctvFrameWrap)==null||a.classList.toggle("loading",!((s=this._cctvFrameWrap)!=null&&s.classList.contains("has-frame")));const o=new Image;this._cctvFramePreloader=o,o.onload=()=>this._settleCctvFrame(i,e,!0),o.onerror=()=>this._settleCctvFrame(i,e,!1),o.src=e}function fj(e,t,n){var o,r;if(this.destroyed||!this._cctvFrame||e!==this._cctvFrameRequestToken)return;this._cctvFramePreloader&&(this._cctvFramePreloader.onload=null,this._cctvFramePreloader.onerror=null),this._cctvFramePreloader=null,this._cctvFrame.dataset.loading="",(o=this._cctvFrameWrap)==null||o.classList.remove("loading");const i=()=>{var s,a;return this._syncCctvSourceBadge((s=this._cctvState)==null?void 0:s.activeCamera,!!((a=this._cctvState)!=null&&a.enabled)&&!!this.actions.isEnabled())};if(!n){this._cctvFrame.dataset.error="true",i();return}this._cctvFrame.dataset.error="",this._cctvFrame.src=t,this._cctvFrame.classList.add("active"),(r=this._cctvFrameWrap)==null||r.classList.add("has-frame"),i()}function mj(e,t){var r,s,a;if(!this._cctvSourceBadge)return;if(!t||!e){this._cctvSourceBadge.textContent="SOURCE · UNKNOWN",this._cctvSourceBadge.dataset.frameState="idle";return}const n=(r=this._cctvFrameWrap)==null?void 0:r.classList.contains("has-frame");if(((s=this._cctvFrame)==null?void 0:s.dataset.loading)==="true"&&!n){this._cctvSourceBadge.textContent="FRAME · LOADING",this._cctvSourceBadge.dataset.frameState="loading";return}if(((a=this._cctvFrame)==null?void 0:a.dataset.error)==="true"&&!n){this._cctvSourceBadge.textContent="FRAME · UNAVAILABLE",this._cctvSourceBadge.dataset.frameState="error";return}const i=String(e.sourceKind||e.feedType||"unknown").toUpperCase(),o=String(e.sourceStatus||"unknown").toUpperCase();this._cctvSourceBadge.textContent=`${i} · ${o}`,this._cctvSourceBadge.dataset.frameState="ready"}const pj=e=>((e+180)%360+360)%360-180,cT={heading:{label:"HDG",unit:"°",decimals:1,get:e=>e.headingDeg,toPatch:(e,t)=>({headingDeg:pj(e-t.headingDeg)})},pitch:{label:"PITCH",unit:"°",decimals:1,get:e=>e.pitchDeg,toPatch:(e,t)=>({pitchDeg:e-t.pitchDeg})},fov:{label:"FOV",unit:"°",decimals:0,get:e=>e.fovDeg,toPatch:(e,t)=>({fovDeg:e-t.fovDeg})},range:{label:"RANGE",unit:"m",decimals:0,get:e=>e.rangeM,toPatch:(e,t)=>({rangeScale:t.rangeM>0?e/t.rangeM:1})},height:{label:"HGT",unit:"m",decimals:0,get:e=>e.mountHeightM,toPatch:(e,t)=>({heightM:e-t.mountHeightM})},north:{label:"ΔN",unit:"m",decimals:1,get:e=>{var t;return((t=e.calibration)==null?void 0:t.offsetNorthM)||0},toPatch:e=>({offsetNorthM:e})},east:{label:"ΔE",unit:"m",decimals:1,get:e=>{var t;return((t=e.calibration)==null?void 0:t.offsetEastM)||0},toPatch:e=>({offsetEastM:e})}};function gj(){var e,t;return((e=this._cctvState)==null?void 0:e.activeCameraId)||((t=this._cctvSelect)==null?void 0:t.value)||""}function _j(){const e=this._activeCctvCameraId();!e||!this.actions.setParams||(this.actions.setParams({selectedCameraId:e,calibration:{cameraId:e,reset:!0}},{origin:"user"}),this.actions.showToast("CCTV calibration reset"))}function bj(e){var u,h;if(this.destroyed)return;(u=this._calibrationEdit)==null||u.call(this,!1);const t=cT[e.dataset.calField],n=(h=this._cctvState)==null?void 0:h.activeCamera;if(!t||!(n!=null&&n.basePose))return;const i=this._activeCctvCameraId(),o={...n.basePose},r=new AbortController,s=t.get(n),a=document.createElement("input");a.type="number",a.step=t.decimals>0?"0.1":"1",a.value=Number(s).toFixed(t.decimals),a.className="cctv-cal-input",e.textContent=`${t.label} `,e.appendChild(a),a.focus(),a.select();let c=!1;const l=d=>{var p,g,_;if(c)return;c=!0,r.abort(),this._calibrationEdit=null;const f=parseFloat(a.value);if(a.remove(),d&&!this.destroyed&&Number.isFinite(f)&&((p=this._cctvState)!=null&&p.enabled)&&this.actions.isEnabled()&&i===this._activeCctvCameraId()&&i&&this.actions.setParams){this.actions.setParams({selectedCameraId:i,calibration:{cameraId:i,patch:t.toPatch(f,o)}},{origin:"user"});return}this._syncCctvCalReadout(!!((g=this._cctvState)!=null&&g.enabled),((_=this._cctvState)==null?void 0:_.activeCamera)||null)};this._calibrationEdit=l,a.addEventListener("keydown",d=>{d.key==="Enter"?l(!0):d.key==="Escape"&&(d.preventDefault(),l(!1)),d.stopPropagation()},{signal:r.signal}),a.addEventListener("blur",()=>l(!0),{signal:r.signal}),a.addEventListener("click",d=>d.stopPropagation(),{signal:r.signal})}function Cj(e,t){var i;const n=!!e&&!!t;if(this._cctvAdjustBtn){const o=!!((i=this._cctvState)!=null&&i.calibrationMode);this._cctvAdjustBtn.classList.toggle("active",o&&n),this._cctvAdjustBtn.textContent=o?"ADJUST ON":"ADJUST",this._cctvAdjustBtn.disabled=!n}if(this._cctvCalReadout)for(const o of this._cctvCalReadout.querySelectorAll(".cctv-cal-value")){if(o.querySelector("input"))continue;const r=cT[o.dataset.calField];if(!r)continue;const s=n?r.get(t):null;o.textContent=Number.isFinite(s)?`${r.label} ${Number(s).toFixed(r.decimals)}${r.unit}`:`${r.label} --`,o.disabled=!n}for(const o of[this._cctvCalibSaveBtn,this._cctvCalibResetBtn])o&&(o.disabled=!n)}function yj(e){switch(e){case"calibrated":return"CALIBRATED";case"curated":return"CURATED";case"raw-prior":return"RAW PRIOR";default:return"--"}}function vj(e){var a,c;if(this.destroyed)return;(!(e!=null&&e.enabled)||!this.actions.isEnabled()||(e==null?void 0:e.activeCameraId)!==((a=this._cctvState)==null?void 0:a.activeCameraId))&&((c=this._calibrationEdit)==null||c.call(this,!1)),this._cctvState=e||null;const t=(e==null?void 0:e.cameras)||[],n=!!(e!=null&&e.enabled)&&!!this.actions.isEnabled(),i=(e==null?void 0:e.activeCameraId)||"",o=(e==null?void 0:e.activeCamera)||null,r=n&&i||null,s=this._lastSeenCctvActiveId===null;if(r&&r!==this._lastSeenCctvActiveId&&(!(e!=null&&e.autoHop)||s)&&this.actions.setPanelCollapsed("cctv-panel",!1,{explicit:!!(e!=null&&e.explicitSelection)}),this._lastSeenCctvActiveId=r,this._updateCctvSyncChip(e==null?void 0:e.loading,n),this._cctvEnableBtn&&(this._cctvEnableBtn.classList.toggle("active",n),this._cctvEnableBtn.textContent=n?"CCTV ON":"CCTV OFF"),this._cctvSelect){if(this._cctvSelect.options.length!==t.length||t.some((u,h)=>{var d;return((d=this._cctvSelect.options[h])==null?void 0:d.value)!==u.id})){this._cctvSelect.innerHTML="";for(const u of t){const h=document.createElement("option");h.value=u.id,h.textContent=`${u.city} · ${u.name}`,this._cctvSelect.appendChild(h)}}this._cctvSelect.disabled=!n||t.length===0,i&&Array.from(this._cctvSelect.options).some(u=>u.value===i)?this._cctvSelect.value=i:i||(this._cctvSelect.selectedIndex=-1)}for(const l of[this._cctvNearestBtn,this._cctvPrevBtn,this._cctvNextBtn])l&&(l.disabled=!n||t.length===0);if(this._cctvFocusBtn&&(this._cctvFocusBtn.disabled=!n||t.length===0||!i),this._cctvCoverageBtn){const l=(e==null?void 0:e.coverageMode)||(e!=null&&e.showCoverage?"on":"off");this._cctvCoverageBtn.classList.toggle("active",l!=="off"),this._cctvCoverageBtn.textContent=l==="viewshed"?"VIEWSHED ON":l==="on"?"COVERAGE ON":"COVERAGE OFF",this._cctvCoverageBtn.disabled=!n}if(this._cctvAutoHopBtn){const l=!!(e!=null&&e.autoHop);this._cctvAutoHopBtn.classList.toggle("active",l),this._cctvAutoHopBtn.textContent=l?"AUTO HOP ON":"AUTO HOP OFF",this._cctvAutoHopBtn.disabled=!n}if(this._cctvProjectionBtn){const l=(e==null?void 0:e.showProjection)!==!1;this._cctvProjectionBtn.classList.toggle("active",l),this._cctvProjectionBtn.textContent=l?"PROJECTION ON":"PROJECTION OFF",this._cctvProjectionBtn.disabled=!n}if(this._cctvQualityChip){const l=(o==null?void 0:o.calBadge)||null,u=!!(o!=null&&o.calDirty);this._cctvQualityChip.textContent=u?"CAL · EDITED (UNSAVED)":`CAL · ${this._calBadgeLabel(l)}`,this._cctvQualityChip.dataset.calBadge=u?"edited":l||""}if(this._syncCctvCalReadout(n,o),this._cctvMeta)if(o){const l=o.sourceLabel||o.provider||"Configured Source",u=o.sourceMessage?` · ${o.sourceMessage}`:"",h=o.credit?` · ${o.credit}`:"",d=o.calBadge?this._calBadgeLabel(o.calBadge):"",f=(e==null?void 0:e.showProjection)!==!1?"MONITOR":"OFF";this._cctvMeta.textContent=`${o.city} · HDG ${Math.round(o.headingDeg)}° · FOV ${Math.round(o.fovDeg)}° · RANGE ${Math.round(o.rangeM)}m · ${f}${d?` · ${d}`:""} · ${l}${h}${u}`}else t.length>0?this._cctvMeta.textContent=n?`${t.length} cameras loaded · click a camera to activate`:`${t.length} cameras loaded · enable CCTV to activate`:this._cctvMeta.textContent="Enable CCTV to load camera intersections";if(this._cctvFrame){const l=n?o==null?void 0:o.frameUrl:null,u=n&&(o==null?void 0:o.id)||"",h=this._cctvFrame.dataset.cameraId!==u,d=this._cctvFrame.dataset.loading==="true";l&&(h||!d&&this._cctvFrame.dataset.currentSrc!==l)&&this._queueCctvFrame(l,u,h),l||this._clearCctvFrame()}this._syncCctvSourceBadge(o,n),this._typeCctvSummary((e==null?void 0:e.summary)||"Enable CCTV to start camera-linked intelligence summaries.")}function Mj(e){if(this.destroyed||!this._cctvSummary)return;const t=String(e||"").trim()||"No summary available.";if(t===this._lastCctvSummaryText)return;this._lastCctvSummaryText=t,clearInterval(this._cctvSummaryTypingTimer),this._cctvSummary.textContent="";let n=0;this._cctvSummaryTypingTimer=setInterval(()=>{if(!this.destroyed){if(n+=3,n>=t.length){this._cctvSummary.textContent=t,clearInterval(this._cctvSummaryTypingTimer),this._cctvSummaryTypingTimer=null;return}this._cctvSummary.textContent=t.slice(0,n)}},20)}function wj(e,t){if(this.destroyed||!this._cctvSyncChip||!this._cctvSyncLabel||!this._cctvSyncProgress)return;const n=Number(e==null?void 0:e.total)||0,i=Math.max(0,Math.min(Number(e==null?void 0:e.loaded)||0,n));if(!!t&&!!(e!=null&&e.active)&&n>0){clearTimeout(this._cctvChipHideTimer),this._cctvChipHideTimer=null,this._cctvChipWasBusy=!0,this.actions.setSplitFlapText(this._cctvSyncLabel,"loading frames"),this._cctvSyncProgress.textContent=`${i}/${n}`,this._cctvSyncChip.classList.add("visible");return}if(this._cctvChipWasBusy&&t&&n>0){this._cctvChipWasBusy=!1,this.actions.setSplitFlapText(this._cctvSyncLabel,"camera grid ready"),this._cctvSyncProgress.textContent=`${n}/${n}`,this._cctvSyncChip.classList.add("visible"),clearTimeout(this._cctvChipHideTimer),this._cctvChipHideTimer=window.setTimeout(()=>{this.destroyed||(this._cctvChipHideTimer=null,this._cctvSyncChip.classList.remove("visible"))},1500);return}this._cctvChipHideTimer||(this._cctvChipWasBusy=!1,this._cctvSyncChip.classList.remove("visible"))}function Ej(){this._cctvPanel&&(this.listen(this._cctvEnableBtn,"click",async()=>{this._actionGeneration++,await this.actions.toggleEnabled()}),this.listen(this._cctvNearestBtn,"click",async()=>{var n,i;const e=++this._actionGeneration,t=(n=this._cctvState)==null?void 0:n.activeCameraId;await this.actions.toggleEnabled(!0)&&(this.destroyed||e!==this._actionGeneration||!this.actions.isEnabled()||t&&t!==((i=this._cctvState)==null?void 0:i.activeCameraId)||this.actions.runExplicitFocus(()=>this.cctv.focusNearest({focus:!1}),o=>this.cctv.focusCamera(o,1.8)))}),this.listen(this._cctvPrevBtn,"click",async()=>{var n,i;const e=++this._actionGeneration,t=(n=this._cctvState)==null?void 0:n.activeCameraId;await this.actions.toggleEnabled(!0)&&(this.destroyed||e!==this._actionGeneration||!this.actions.isEnabled()||t&&t!==((i=this._cctvState)==null?void 0:i.activeCameraId)||this.actions.runExplicitFocus(()=>this.cctv.cycleCamera(-1),o=>this.cctv.focusCamera(o,1.4)))}),this.listen(this._cctvNextBtn,"click",async()=>{var n,i;const e=++this._actionGeneration,t=(n=this._cctvState)==null?void 0:n.activeCameraId;await this.actions.toggleEnabled(!0)&&(this.destroyed||e!==this._actionGeneration||!this.actions.isEnabled()||t&&t!==((i=this._cctvState)==null?void 0:i.activeCameraId)||this.actions.runExplicitFocus(()=>this.cctv.cycleCamera(1),o=>this.cctv.focusCamera(o,1.4)))}),this.listen(this._cctvSelect,"change",async()=>{var i,o;const e=++this._actionGeneration,t=(i=this._cctvState)==null?void 0:i.activeCameraId,n=this._cctvSelect.value;n&&await this.actions.toggleEnabled(!0)&&(this.destroyed||e!==this._actionGeneration||!this.actions.isEnabled()||t&&t!==((o=this._cctvState)==null?void 0:o.activeCameraId)||(this.actions.runExplicitFocus(()=>this.cctv.selectCamera(n)?n:null,r=>this.cctv.focusCamera(r,2.2)),this.actions.setParams({selectedCameraId:n},{origin:"user"})))}),this.listen(this._cctvFocusBtn,"click",async()=>{var i,o,r,s;const e=++this._actionGeneration,t=(i=this._cctvState)==null?void 0:i.activeCameraId,n=((o=this._cctvState)==null?void 0:o.activeCameraId)||((r=this._cctvSelect)==null?void 0:r.value);n&&await this.actions.toggleEnabled(!0)&&(this.destroyed||e!==this._actionGeneration||!this.actions.isEnabled()||t&&t!==((s=this._cctvState)==null?void 0:s.activeCameraId)||(this.actions.runExplicitFocus(()=>n,a=>this.cctv.focusCamera(a,1.9)),this.actions.setParams({selectedCameraId:n},{origin:"user"})))}),this.listen(this._cctvCoverageBtn,"click",()=>{var n,i;const e=((n=this._cctvState)==null?void 0:n.coverageMode)||((i=this._cctvState)!=null&&i.showCoverage?"on":"off"),t=e==="off"?"on":e==="on"?"viewshed":"off";this.actions.setParams({coverageMode:t},{origin:"user"})}),this.listen(this._cctvAutoHopBtn,"click",()=>{var t;const e=!!((t=this._cctvState)!=null&&t.autoHop);this.actions.setParams({autoHop:!e},{origin:"user"})}),this.listen(this._cctvProjectionBtn,"click",()=>{var t;const e=((t=this._cctvState)==null?void 0:t.showProjection)!==!1;this.actions.setParams({showProjection:!e},{origin:"user"})}),this.listen(this._cctvAdjustBtn,"click",()=>{var t;const e=!!((t=this._cctvState)!=null&&t.calibrationMode);this.actions.setParams({calibrationMode:!e},{origin:"user"})}),this.listen(this._cctvCalReadout,"click",e=>{var n,i;const t=(i=(n=e.target).closest)==null?void 0:i.call(n,".cctv-cal-value");!t||t.disabled||t.querySelector("input")||this._beginCctvCalValueEdit(t)}),this.listen(this._cctvCalibSaveBtn,"click",()=>{const e=this._activeCctvCameraId();!e||!this.actions.setParams||(this.actions.setParams({selectedCameraId:e,calibration:{cameraId:e,save:!0}},{origin:"user"}),this.actions.showToast("CCTV calibration saved"))}),this.listen(this._cctvCalibResetBtn,"click",()=>{this._resetCctvCalibration()}),this._renderCctvState(null),this.actions.syncViewport())}class Tj{constructor({elements:t,cctv:n,actions:i}){Object.assign(this,t),this.cctv=n,this.actions=i,this.destroyed=!1,this.listeners=new AbortController,this._cctvUnsubscribe=null,this._cctvState=null,this._cctvSummaryTypingTimer=null,this._lastCctvSummaryText="",this._lastSeenCctvActiveId=null,this._cctvChipHideTimer=null,this._cctvChipWasBusy=!1,this._cctvFrameRequestToken=0,this._cctvFramePreloader=null,this._calibrationEdit=null,this._actionGeneration=0,this._initCctvPanel()}listen(t,n,i,o={}){t==null||t.addEventListener(n,i,{...o,signal:this.listeners.signal})}getState(){return this._cctvState}connect(){var t,n,i;(t=this._cctvUnsubscribe)==null||t.call(this),this._cctvUnsubscribe=null,!this.destroyed&&(this._cctvUnsubscribe=(i=(n=this.cctv).subscribe)==null?void 0:i.call(n,o=>this._renderCctvState(o)),this.cctv.getUIState&&this._renderCctvState(this.cctv.getUIState()))}_clearCctvFrame(...t){return dj.call(this,...t)}_queueCctvFrame(...t){return hj.call(this,...t)}_settleCctvFrame(...t){return fj.call(this,...t)}_syncCctvSourceBadge(...t){return mj.call(this,...t)}_activeCctvCameraId(...t){return gj.call(this,...t)}_resetCctvCalibration(...t){return _j.call(this,...t)}_beginCctvCalValueEdit(...t){return bj.call(this,...t)}_syncCctvCalReadout(...t){return Cj.call(this,...t)}_calBadgeLabel(...t){return yj.call(this,...t)}_renderCctvState(...t){return vj.call(this,...t)}_typeCctvSummary(...t){return Mj.call(this,...t)}_updateCctvSyncChip(...t){return wj.call(this,...t)}_initCctvPanel(...t){return Ej.call(this,...t)}destroy(){var t,n,i;this.destroyed||(this.destroyed=!0,this._actionGeneration++,this.listeners.abort(),(t=this._cctvUnsubscribe)==null||t.call(this),this._cctvUnsubscribe=null,(n=this._calibrationEdit)==null||n.call(this,!1),this._clearCctvFrame(),clearInterval(this._cctvSummaryTypingTimer),clearTimeout(this._cctvChipHideTimer),this._cctvSummaryTypingTimer=null,this._cctvChipHideTimer=null,(i=this._cctvSyncChip)==null||i.classList.remove("visible"))}}function kj(){if(!this._radioPanel)return;const e={},t=(f,{returnFocus:p=!1}={})=>{var _,m;if(this.destroyed)return;const g=!!f;(_=this._contextRadioDock)==null||_.classList.toggle("disclosure-open",g),this._contextRadioMini&&(this._contextRadioMini.hidden=!g),this._syncContextRadioLauncherState(),!g&&p&&((m=this._contextRadioToggleBtn)==null||m.focus({preventScroll:!0}))};this._setRadioDisclosure=t;const n=(f,p,{returnFocus:g=!1}={})=>{var b,C,y,v,M,w,E;if(this.destroyed)return;const _=f==="display"&&!!p,m=f==="radio"&&!!p;if((_||m)&&this.actions.setSignalCollapsed(!0),this._cockpitDisplayPanel&&(this._cockpitDisplayPanel.hidden=!_),this._cockpitRadioPanel&&(this._cockpitRadioPanel.hidden=!m),(C=(b=this._cockpitDisplayToggleBtn)==null?void 0:b.closest(".cockpit-utility-control"))==null||C.classList.toggle("is-expanded",_),(v=(y=this._cockpitRadioToggleBtn)==null?void 0:y.closest(".cockpit-utility-control"))==null||v.classList.toggle("is-expanded",m),(M=this._cockpitDisplayToggleBtn)==null||M.setAttribute("aria-expanded",String(_)),(w=this._cockpitRadioToggleBtn)==null||w.setAttribute("aria-expanded",String(m)),_&&this.actions.revealStyleParameters(),this._cockpitDisplayToggleBtn){const k=_?"Collapse":"Expand";this._cockpitDisplayToggleBtn.textContent=_?"▶":"◀",this._cockpitDisplayToggleBtn.setAttribute("aria-label",`${k} Cockpit display options`),this._cockpitDisplayToggleBtn.title=`${k} Cockpit display options`}if(this._cockpitRadioToggleBtn){const k=m?"Collapse":"Expand";this._cockpitRadioToggleBtn.textContent=m?"▶":"◀",this._cockpitRadioToggleBtn.setAttribute("aria-label",`${k} Cockpit Radio controls`),this._cockpitRadioToggleBtn.title=`${k} Cockpit Radio controls`}!p&&g&&((E=f==="display"?this._cockpitDisplayToggleBtn:this._cockpitRadioToggleBtn)==null||E.focus({preventScroll:!0})),!_&&!m&&this.actions.isCockpitActive()&&!this.actions.signalUserCollapsed()&&this.actions.setSignalCollapsed(!1),this.actions.layoutCockpit()};this._setCockpitDisclosure=n;const i=f=>{var m,b,C;const p=(m=this._radioTuner)==null?void 0:m.querySelector(".radio-tuner-scale"),g=(b=this._radioTuner)==null?void 0:b.querySelector(".radio-tuner-dial");if(!p||!g)return null;const _=ZD(f,this._radioTunerStations.length,g.getBoundingClientRect().width);for(;p.children.length<_.ticks.length;){const y=document.createElement("span");y.className="radio-tuner-tick",p.append(y)}for(;p.children.length>_.ticks.length;)(C=p.lastElementChild)==null||C.remove();return _.ticks.forEach((y,v)=>{const M=p.children[v];M.style.left=`${y.xPx}px`,M.textContent=y.label,M.dataset.stationIndex=String(y.stationIndex),M.classList.toggle("is-current",y.current)}),p.style.setProperty("--radio-tuner-tick-pitch",`${_.pitchPx}px`),_},o=({coordinate:f=this._radioTunerCoordinate,syncStatic:p=!0,rotate:g=!0}={})=>{var y,v,M,w;const _=pi((y=this._radioTunerSlider)==null?void 0:y.value,this._radioTunerStations.length),m=_.locked&&this._radioTunerStations[_.stationIndex]||null,b=this._radioTunerStations.length<=1?0:Math.min(this._radioTunerStations.length-1,Math.max(0,Number(f)||0)),C=this._radioTunerStations.length===1?.5:b/Math.max(1,this._radioTunerStations.length-1);return this._radioTunerCoordinate=b,(v=this._radioTuner)==null||v.style.setProperty("--radio-tuner-ratio",String(C)),(w=this._radioTuner)==null||w.classList.toggle("is-static",p?!1:!!((M=this._radioState)!=null&&M.tuningStatic)),i(b),this._radioTunerValue&&(this._radioTunerValue.textContent=m?`CH ${String(_.stationIndex+1).padStart(2,"0")} / ${String(this._radioTunerStations.length).padStart(2,"0")}`:"NO STATIONS"),this._radioTunerStation&&(this._radioTunerStation.textContent=(m==null?void 0:m.name)||"NO STATION AVAILABLE"),this._radioTunerSlider&&this._radioTunerSlider.setAttribute("aria-valuetext",m?`${m.name}, station ${_.stationIndex+1} of ${this._radioTunerStations.length}`:"No station available"),p&&this.radio.previewTuningStation((m==null?void 0:m.id)||null,{rotate:g}),m},r=f=>{this._radioTunerPool=[...f],this._radioTunerStations=[...f],this._radioTunerBandSignature=this._radioTunerStations.map(p=>p.id).join("|"),this._radioTunerSlider&&(this._radioTunerSlider.min="0",this._radioTunerSlider.max=String(Math.max(0,this._radioTunerStations.length-1)),this._radioTunerSlider.step="1")},s=({force:f=!1}={})=>{var y,v,M,w;if(this._radioTunerDragging||(y=this._radioTuner)!=null&&y.hidden||(v=this._radioTunerSlider)!=null&&v.disabled)return!1;const p=((w=(M=this._radioState)==null?void 0:M.selected)==null?void 0:w.id)||null,g=this.radio.getTunerStations(750),_=g.map(E=>E.id).join("|"),m=this._radioTunerPool.map(E=>E.id).join("|");if(!f&&_===m&&p===this._radioTunerSelectedId)return!1;r(g),this._radioTunerSelectedId=p;const b=g.findIndex(E=>E.id===p),C=pi(b>=0?b:0,this._radioTunerStations.length);return this._radioTunerSlider.value=String(C.slot),this._radioTunerCoordinate=C.stationIndex>=0?C.stationIndex:0,o({coordinate:this._radioTunerCoordinate,syncStatic:!1}),!0};this._refreshRadioTunerBand=s;const a=()=>{var g,_;if(this._radioTunerDragging||(g=this._radioTunerSlider)!=null&&g.disabled||(s(),!this._radioTunerStations.length||!this.radio.beginTuning()))return!1;this._radioTunerBandPinnedForNavigation=!0,this._radioTunerDragging=!0,(_=this._radioTuner)==null||_.classList.add("is-dragging");const f=this._radioTunerStations.findIndex(m=>{var b,C;return m.id===((C=(b=this._radioState)==null?void 0:b.selected)==null?void 0:C.id)}),p=pi(f>=0?f:0,this._radioTunerStations.length);return this._radioTunerSlider.value=String(p.slot),this._radioTunerCoordinate=p.stationIndex>=0?p.stationIndex:0,this._radioTunerDragStartSlot=p.slot,this._radioTunerDragSnapshot={stations:[...this._radioTunerStations],bandSignature:this._radioTunerBandSignature,selectedId:this._radioTunerSelectedId,slot:p.slot,coordinate:this._radioTunerCoordinate},this._radioTunerLastSlot=p.slot,this._radioTunerDragDirection=0,o({coordinate:this._radioTunerCoordinate}),!0},c=f=>{var m,b,C;if(!this._radioTunerDragging)return;const p=this._radioTunerDragSnapshot;if(!f&&p){if(this._radioTunerStations=[...p.stations],this._radioTunerPool=[...p.stations],this._radioTunerBandSignature=p.bandSignature,this._radioTunerSelectedId=p.selectedId,this._radioTunerSlider){const y=pi(p.slot,this._radioTunerStations.length);this._radioTunerSlider.max=String(y.max),this._radioTunerSlider.value=String(y.slot)}this._radioTunerCoordinate=Number.isFinite(p.coordinate)?p.coordinate:p.slot}else!f&&this._radioTunerSlider&&(this._radioTunerSlider.value=String(this._radioTunerDragStartSlot),this._radioTunerCoordinate=this._radioTunerDragStartSlot);let g=o({coordinate:this._radioTunerCoordinate,rotate:f});if(f&&!g&&this._radioTunerSlider){const y=XD(this._radioTunerSlider.value,this._radioTunerStations.length);this._radioTunerSlider.value=String(y.slot),this._radioTunerCoordinate=y.stationIndex,g=o({coordinate:this._radioTunerCoordinate})}let _=null;f&&g?(this._radioTunerBandPinnedForNavigation=!0,_=this.radio.commitTuningStation(g.id,{origin:"user"})):f?this.radio.endTuning():this.radio.cancelTuning(),this._radioTunerDragging=!1,this._radioTunerPointerId=null,this._radioTunerKeyboardKey=null,f&&(!_||_.ok)&&s(),this._radioTunerDragSnapshot=null,(m=this._radioTunerNeedle)==null||m.offsetLeft,(b=this._radioTuner)==null||b.classList.remove("is-dragging"),_&&!_.ok&&(this._radioTunerBandPinnedForNavigation=!1,_.reason==="station-unavailable"&&(this._radioTunerValue&&(this._radioTunerValue.textContent="OFF AIR"),this._radioTunerStation&&(this._radioTunerStation.textContent="STATION UNAVAILABLE"),(C=this._radioTunerSlider)==null||C.setAttribute("aria-valuetext","Station unavailable after directory refresh")))},l=(f,{rotate:p=!0}={})=>{this._radioTunerBandPinnedForNavigation=!0;const g=this._radioTunerPool.length?this._radioTunerPool:this._radioTunerStations;if(!this.radio.cycleStation(f,{rotate:p,stationIds:g.map(m=>m.id),origin:"user"})){this._radioTunerBandPinnedForNavigation=!1;return}},u=async f=>{var _;if(!this.actions.isRegistered()||f.getAttribute("aria-busy")==="true")return;const p=!this.actions.isEnabled(),g=p&&f===this._radioEnableBtn;f.setAttribute("aria-disabled","true"),f.setAttribute("aria-busy","true");try{const m=await this.actions.runUserAction(b=>this.actions.setEnabled(p,{origin:"user",notificationToken:b}),`Radio could not ${p?"start":"stop"} cleanly`);if(this.destroyed||m===!1)return;p&&f===this._radioEnableBtn&&!((_=document.getElementById("global-context-panel"))!=null&&_.classList.contains("collapsed"))&&this.actions.setPanelCollapsed("radio-panel",!1,{explicit:!0}),g&&await this._revealRadioControlsAfterExplicitEnable(f)}finally{this.destroyed||(f.setAttribute("aria-disabled","false"),f.setAttribute("aria-busy","false"),g&&f.isConnected&&f.focus({preventScroll:!0}))}};this.listen(this._radioEnableBtn,"click",()=>void u(this._radioEnableBtn)),this.listen(this._contextRadioMiniEnableBtn,"click",()=>void u(this._contextRadioMiniEnableBtn)),this.listen(this._cockpitRadioEnableBtn,"click",()=>void u(this._cockpitRadioEnableBtn)),this.listen(this._contextRadioToggleBtn,"click",()=>{var p,g;const f=document.getElementById("global-context-panel");if(f&&!f.classList.contains("collapsed")){t(!1),this.actions.setPanelCollapsed("radio-panel",!1,{explicit:!0}),this._revealRadioPanelInsideContext({focusTarget:(p=this._radioPanel)==null?void 0:p.querySelector('[data-collapse-target="radio-panel"]')});return}t(!((g=this._contextRadioDock)!=null&&g.classList.contains("disclosure-open")))}),this.listen(this._contextRadioMiniCloseBtn,"click",()=>{t(!1,{returnFocus:!0})}),this.listen(this._contextRadioDetailsBtn,"click",()=>{var f;this.actions.isCockpitActive()||this.actions.setPanelCollapsed("global-context-panel",!1,{explicit:!0}),this.actions.setPanelCollapsed("radio-panel",!1,{explicit:!0}),t(!1),(f=this._radioEnableBtn)==null||f.focus({preventScroll:!0})}),this.listen(this._cockpitRadioToggleBtn,"click",()=>{const f=this._cockpitRadioToggleBtn.getAttribute("aria-expanded")==="true";n("radio",!f)}),this.listen(document,"pointerdown",f=>{var p,g,_;(p=this._contextRadioDock)!=null&&p.classList.contains("disclosure-open")&&((_=(g=f.target)==null?void 0:g.closest)!=null&&_.call(g,"#context-radio-dock")||t(!1))},e),this.listen(document,"pointerdown",f=>{var p,g,_,m,b,C;!this._cockpitUtilityControls||(g=(p=f.target)==null?void 0:p.closest)!=null&&g.call(p,"#cockpit-utility-controls")||(m=(_=f.target)==null?void 0:_.closest)!=null&&m.call(_,".cockpit-vision-controls")||(C=(b=f.target)==null?void 0:b.closest)!=null&&C.call(b,"#left-panel-stack, #cockpit-context")||(n("display",!1),n("radio",!1))},e),this.listen(document,"keydown",f=>{var g,_,m,b,C;if(f.key!=="Escape"||!((g=this._contextRadioDock)!=null&&g.classList.contains("disclosure-open")))return;f.preventDefault(),f.stopImmediatePropagation();const p=f.target===this._contextRadioToggleBtn||((m=(_=this._contextRadioToggleBtn)==null?void 0:_.contains)==null?void 0:m.call(_,f.target));t(!1,{returnFocus:!p}),p&&((C=(b=this._contextRadioToggleBtn)==null?void 0:b.blur)==null||C.call(b))},{capture:!0}),this.listen(document,"keydown",f=>{var y,v,M,w,E,k;if(f.key!=="Escape")return;const p=((y=this._cockpitDisplayToggleBtn)==null?void 0:y.getAttribute("aria-expanded"))==="true",g=((v=this._cockpitRadioToggleBtn)==null?void 0:v.getAttribute("aria-expanded"))==="true";if(!p&&!g||((w=(M=f.target)==null?void 0:M.closest)==null?void 0:w.call(M,".panel-collapsible:not(.collapsed), #param-slider-panel:not(.collapsed)")))return;f.preventDefault(),f.stopImmediatePropagation();const m=p?"display":"radio",b=p?this._cockpitDisplayToggleBtn:this._cockpitRadioToggleBtn,C=f.target===b||((E=b==null?void 0:b.contains)==null?void 0:E.call(b,f.target));n(m,!1,{returnFocus:!C}),C&&((k=b==null?void 0:b.blur)==null||k.call(b))},{capture:!0}),this.listen(window,"gev:cockpit-mode-changed",f=>{var p;(p=f==null?void 0:f.detail)!=null&&p.active||(n("display",!1),n("radio",!1))},e),this.listen(window,"gev:cockpit-signal-expanded",()=>{n("display",!1)},e),this.listen(window,"gev:cockpit-context-expanded",()=>{this.actions.setPanelCollapsed("data-panel",!0)},e),this.listen(this._radioFilter,"change",()=>{const f=this.radio.getUIState();if(!f.presentationActive){this._radioFilter.value=f.filter;return}if(this._radioTunerDragging&&c(!1),!this.actions.setParams({filter:this._radioFilter.value},{origin:"user"})){this._radioFilter.value=this.radio.getUIState().filter;return}this._radioTunerBandPinnedForNavigation=!1,this._radioTunerPool=[],s({force:!0})}),this.listen(this._radioPrevBtn,"click",()=>l(-1)),this.listen(this._radioNextBtn,"click",()=>l(1)),this.listen(this._radioPlayBtn,"click",()=>void this.radio.togglePlayback({origin:"user"})),this.listen(this._radioStopBtn,"click",()=>this.radio.stopPlayback({origin:"user"})),this.listen(this._radioVolume,"input",()=>{const f=Number(this._radioVolume.value);this._radioVolumeValue&&(this._radioVolumeValue.textContent=`${f}%`),this.actions.setParams({volume:f/100},{origin:"user"})}),this.listen(this._contextRadioMiniPrevBtn,"click",()=>l(-1)),this.listen(this._contextRadioMiniNextBtn,"click",()=>l(1)),this.listen(this._contextRadioMiniPlayBtn,"click",()=>void this.radio.togglePlayback({origin:"user"})),this.listen(this._cockpitRadioPrevBtn,"click",()=>l(-1,{rotate:!1})),this.listen(this._cockpitRadioNextBtn,"click",()=>l(1,{rotate:!1})),this.listen(this._cockpitRadioPlayBtn,"click",()=>void this.radio.togglePlayback({origin:"user"})),this.listen(this._contextRadioMiniVolume,"input",()=>{const f=Number(this._contextRadioMiniVolume.value);this._contextRadioMiniVolumeValue&&(this._contextRadioMiniVolumeValue.textContent=`${f}%`),this.actions.setParams({volume:f/100},{origin:"user"})}),this.listen(this._cockpitRadioVolume,"input",()=>{const f=Number(this._cockpitRadioVolume.value);this._cockpitRadioVolumeValue&&(this._cockpitRadioVolumeValue.textContent=`${f}%`),this.actions.setParams({volume:f/100},{origin:"user"})});const h=f=>{var _;const p=(_=this._radioTunerSlider)==null?void 0:_.getBoundingClientRect();if(!p||!this._radioTunerStations.length)return!1;const g=QD(f.clientX,p.left,p.width,this._radioTunerStations.length);return g.stationIndex>this._radioTunerLastSlot?this._radioTunerDragDirection=1:g.stationIndex{if(a()){this._radioTunerPointerId=f.pointerId,this._radioTunerSlider.focus({preventScroll:!0});try{this._radioTunerSlider.setPointerCapture(f.pointerId)}catch{}h(f),f.preventDefault()}},e),this.listen(this._radioTunerSlider,"pointermove",f=>{!this._radioTunerDragging||this._radioTunerPointerId!==f.pointerId||(h(f),f.preventDefault())},e),this.listen(this._radioTunerSlider,"input",()=>{if(this._radioTunerPointerId!==null||this._radioTunerKeyboardKey||!this._radioTunerDragging&&!a())return;const f=pi(this._radioTunerSlider.value,this._radioTunerStations.length);f.slot>this._radioTunerLastSlot?this._radioTunerDragDirection=1:f.slot{this._radioTunerPointerId===null&&!this._radioTunerKeyboardKey&&c(!0)},e),this.listen(this._radioTunerSlider,"pointerup",f=>{if(this._radioTunerPointerId===f.pointerId){h(f),c(!0);try{this._radioTunerSlider.releasePointerCapture(f.pointerId)}catch{}f.preventDefault()}},e),this.listen(this._radioTunerSlider,"pointercancel",f=>{if(!(this._radioTunerPointerId!==null&&this._radioTunerPointerId!==f.pointerId)){try{this._radioTunerSlider.releasePointerCapture(f.pointerId)}catch{}c(!1)}},e),this.listen(this._radioTunerSlider,"lostpointercapture",f=>{this._radioTunerDragging&&this._radioTunerPointerId===f.pointerId&&c(!1)},e),this.listen(this._radioTunerSlider,"keydown",f=>{if(f.key==="Escape"&&this._radioTunerDragging){f.preventDefault(),c(!1);return}if(!["ArrowLeft","ArrowRight","Home","End","PageUp","PageDown"].includes(f.key)||!this._radioTunerDragging&&!a())return;f.preventDefault(),this._radioTunerKeyboardKey=f.key;const p=Math.max(0,this._radioTunerStations.length-1),g=pi(this._radioTunerSlider.value,this._radioTunerStations.length).slot,_=Math.max(1,Math.round(p/10)),m=f.key==="Home"?0:f.key==="End"?p:f.key==="PageUp"?g+_:f.key==="PageDown"?g-_:g+(f.key==="ArrowRight"?1:-1),b=pi(m,this._radioTunerStations.length);b.slot>this._radioTunerLastSlot?this._radioTunerDragDirection=1:b.slot{!this._radioTunerKeyboardKey||f.key!==this._radioTunerKeyboardKey||(f.preventDefault(),c(!0))},e),this.listen(this._radioTunerSlider,"blur",()=>c(!0),e);const d=()=>{this._radioTunerBandPinnedForNavigation=!1};this.listen(this.canvas,"pointerdown",d,e),this.listen(this.canvas,"wheel",d,e),this._radioSelectedHandler=()=>this.actions.setPanelCollapsed("radio-panel",!1),this.listen(document,"gev:radio-selected",this._radioSelectedHandler)}function Aj(e){var h,d,f,p,g,_;if(this.destroyed||!e||!this._radioPanel)return;const t=this.actions.getLifecycle()||null,n=(t==null?void 0:t.lifecycleState)||(e.enabled?"enabled":"disabled");e={...e,enabled:t?t.enabled:e.enabled,lifecycleState:n,lifecycleUncertain:(t==null?void 0:t.uncertain)||!1},this._radioState=e;const i=!!e.enabled,o=n==="enabling"||n==="disabling",r=!!e.lifecycleUncertain,s=i&&!o&&!r,a=e.selected||null,c=e.filteredCount>0,l=["playing","buffering"].includes(e.audioState);if((h=document.getElementById("title-bar"))==null||h.classList.toggle("radio-broadcasting",e.audioState==="playing"),this._radioPanel.classList.toggle("radio-enabled",i),this._radioPanel.classList.toggle("lifecycle-uncertain",r),(d=this._contextRadioDock)==null||d.classList.toggle("active",i),this._contextRadioToggleBtn&&this._contextRadioToggleBtn.classList.toggle("active",i),this._syncContextRadioLauncherState(),(f=this._radioLayerState)==null||f.classList.toggle("active",i),this._radioLayerState&&(this._radioLayerState.textContent=o?n.toUpperCase():r?"UNCERTAIN":e.loading?"SYNC":i?`${e.filteredCount}/${e.stationCount}`:"OFF"),this._radioEnableBtn&&(this._radioEnableBtn.classList.toggle("active",i),this._radioEnableBtn.setAttribute("aria-pressed",String(i)),this._radioEnableBtn.textContent=o?n.toUpperCase():r?"RECONCILE":i?"DISABLE":"ENABLE",this._radioEnableBtn.setAttribute("aria-label",r?"Reconcile Radio — lifecycle uncertain":`${i?"Disable":"Enable"} Radio`),this._radioEnableBtn.disabled=!1,this._radioEnableBtn.setAttribute("aria-disabled",String(o)),this._radioEnableBtn.setAttribute("aria-busy",String(o))),this._contextRadioMiniEnableBtn&&(this._contextRadioMiniEnableBtn.classList.toggle("active",i),this._contextRadioMiniEnableBtn.setAttribute("aria-pressed",String(i)),this._contextRadioMiniEnableBtn.textContent=o?n.toUpperCase():r?"RECONCILE":i?"DISABLE":"ENABLE",this._contextRadioMiniEnableBtn.setAttribute("aria-label",r?"Reconcile Radio — lifecycle uncertain":`${i?"Disable":"Enable"} Radio`),this._contextRadioMiniEnableBtn.disabled=!1,this._contextRadioMiniEnableBtn.setAttribute("aria-disabled",String(o)),this._contextRadioMiniEnableBtn.setAttribute("aria-busy",String(o))),this._cockpitRadioEnableBtn&&(this._cockpitRadioEnableBtn.classList.toggle("active",i),this._cockpitRadioEnableBtn.setAttribute("aria-pressed",String(i)),this._cockpitRadioEnableBtn.textContent=o?n.toUpperCase():r?"RECONCILE":i?"DISABLE":"ENABLE",this._cockpitRadioEnableBtn.setAttribute("aria-label",r?"Reconcile Radio — lifecycle uncertain":`${i?"Disable":"Enable"} Radio`),this._cockpitRadioEnableBtn.disabled=!1,this._cockpitRadioEnableBtn.setAttribute("aria-disabled",String(o)),this._cockpitRadioEnableBtn.setAttribute("aria-busy",String(o))),this._radioFilter){const m=e.filter||"all",b=e.categories.map(y=>`${y.id}:${y.count}:${y.color}`).join("|");b!==this._radioCategorySignature&&(this._radioFilter.replaceChildren(...e.categories.map(y=>{const v=document.createElement("option");return v.value=y.id,v.textContent=`● ${y.label} (${y.count})`,v.dataset.radioColor=y.color,v.style.color=y.color,v.setAttribute("aria-label",`${y.label} (${y.count})`),v})),this._radioCategorySignature=b),this._radioFilter.value=m;const C=e.categories.find(y=>y.id===m);this._radioFilter.style.color=(C==null?void 0:C.color)||"",this._radioFilter.disabled=!s||!e.stationCount}const u=s&&e.filteredCount>0;if(this._radioTuner&&(this._radioTuner.hidden=!u),this._radioTunerSlider&&(this._radioTunerSlider.disabled=!u),this._radioTunerBandLabel){const m=e.categories.find(b=>b.id===e.filter);this._radioTunerBandLabel.textContent=e.filter==="all"?"DIRECTORY BAND":`${String((m==null?void 0:m.label)||e.filter).toUpperCase()} BAND`}if((p=this._radioTuner)==null||p.classList.toggle("is-static",!!e.tuningStatic),u&&((g=this._refreshRadioTunerBand)==null||g.call(this)),!u&&this._radioTunerDragging&&(this._radioTunerDragging=!1,this._radioTunerDragSnapshot=null,this._radioTunerStations=[],(_=this._radioTuner)==null||_.classList.remove("is-static","is-dragging")),u||(this._radioTunerStations=[],this._radioTunerPool=[],this._radioTunerBandSignature="",this._radioTunerSelectedId=null),this._radioStationName&&(this._radioStationName.textContent=(a==null?void 0:a.name)||"NO STATION SELECTED"),this._radioStationMeta){const m=a?[a.state,a.countryCode].filter(Boolean).join(" · "):"",b=a?[a.codec,a.bitrate?`${a.bitrate} kbps`:""].filter(Boolean).join(" · "):"";this._radioStationMeta.textContent=a?[m,b].filter(Boolean).join(" / ")||"Directory metadata only":e.loading?"Loading station directory…":"Choose a globe marker or use next."}if(this._radioStationTags){const m=Array.isArray(a==null?void 0:a.tags)?a.tags.slice(0,8):[];this._radioStationTags.textContent=m.length?`TAGS · ${m.join(" · ")}`:""}if(this._radioStationHomepage){const m=(a==null?void 0:a.homepage)||"";this._radioStationHomepage.hidden=!m,m?this._radioStationHomepage.href=m:this._radioStationHomepage.removeAttribute("href")}if(this._radioPrevBtn&&(this._radioPrevBtn.disabled=!s||!c),this._radioNextBtn&&(this._radioNextBtn.disabled=!s||!c),this._contextRadioMiniPrevBtn&&(this._contextRadioMiniPrevBtn.disabled=!s||!c),this._contextRadioMiniNextBtn&&(this._contextRadioMiniNextBtn.disabled=!s||!c),this._cockpitRadioPrevBtn&&(this._cockpitRadioPrevBtn.disabled=!s||!c),this._cockpitRadioNextBtn&&(this._cockpitRadioNextBtn.disabled=!s||!c),this._radioPlayBtn){const m=l?"Pause":e.audioState==="paused"?"Resume":"Play";this._radioPlayBtn.disabled=!s||!c,this._radioPlayBtn.classList.toggle("active",l),this._radioPlayBtn.textContent=m.toUpperCase(),this._radioPlayBtn.setAttribute("aria-label",`${m} ${a?"selected":"nearest"} radio station`)}if(this._contextRadioMiniPlayBtn){const m=l?"Pause":e.audioState==="paused"?"Resume":"Play";this._contextRadioMiniPlayBtn.disabled=!s||!c,this._contextRadioMiniPlayBtn.classList.toggle("active",l),this._contextRadioMiniPlayBtn.textContent=l?"Ⅱ":"▶",this._contextRadioMiniPlayBtn.setAttribute("aria-label",`${m} ${a?"selected":"nearest"} radio station`),this._contextRadioMiniPlayBtn.title=m}if(this._cockpitRadioPlayBtn){const m=l?"Pause":e.audioState==="paused"?"Resume":"Play";this._cockpitRadioPlayBtn.disabled=!s||!c,this._cockpitRadioPlayBtn.classList.toggle("active",l),this._cockpitRadioPlayBtn.textContent=l?"Ⅱ":"▶",this._cockpitRadioPlayBtn.setAttribute("aria-label",`${m} ${a?"selected":"nearest"} radio station`),this._cockpitRadioPlayBtn.title=m}if(this._radioStopBtn&&(this._radioStopBtn.disabled=!s||e.audioState==="stopped"),this._radioVolume&&(this._radioVolume.disabled=!s),this._radioVolume&&document.activeElement!==this._radioVolume&&(this._radioVolume.value=String(Math.round(e.volume*100)),this._radioVolumeValue&&(this._radioVolumeValue.textContent=`${Math.round(e.volume*100)}%`)),this._contextRadioMiniVolume&&document.activeElement!==this._contextRadioMiniVolume&&(this._contextRadioMiniVolume.value=String(Math.round(e.volume*100))),this._contextRadioMiniVolume&&(this._contextRadioMiniVolume.disabled=!s),this._contextRadioMiniVolumeValue&&(this._contextRadioMiniVolumeValue.textContent=`${Math.round(e.volume*100)}%`),this._cockpitRadioVolume&&document.activeElement!==this._cockpitRadioVolume&&(this._cockpitRadioVolume.value=String(Math.round(e.volume*100))),this._cockpitRadioVolume&&(this._cockpitRadioVolume.disabled=!s),this._cockpitRadioVolumeValue&&(this._cockpitRadioVolumeValue.textContent=`${Math.round(e.volume*100)}%`),this._contextRadioMiniStation&&(this._contextRadioMiniStation.textContent=r?"RADIO STATE UNCERTAIN":(a==null?void 0:a.name)||(e.loading?"SYNCING DIRECTORY":"RADIO READY")),this._cockpitRadioStation&&(this._cockpitRadioStation.textContent=r?"UNCERTAIN":(a==null?void 0:a.name)||(e.loading?"SYNCING":"READY")),this._radioPlaybackState){const m=e.degraded?e.stale?" · stale/degraded directory":" · degraded directory":e.stale?" · stale directory":"",b=a&&e.selectedIndex<0?" · outside current filter":"",C={stopped:i?"Ready — playback starts only from your action":"Radio off",loading:"Connecting directly to broadcaster…",buffering:"Buffering broadcaster stream…",playing:`Playing ${(a==null?void 0:a.name)||"station"}`,paused:`Paused ${(a==null?void 0:a.name)||"station"}`,error:e.audioError||"Broadcaster stream unavailable"},y=e.voiceDucked?" · muted during voice interaction":e.voiceRestoring?" · restoring volume after voice":"",v=e.tuningAwaitingStationId?e.audioState==="error"?" · static indicates no broadcaster audio":" · tuning static until broadcaster starts":"",M=e.tuningUnavailableStationId?"Station unavailable after directory refresh — choose another channel":null,w=o?n==="enabling"?"Radio is enabling…":"Radio is disabling…":null,E=r?"Radio lifecycle is uncertain — use Enable or Disable to reconcile":null;this._radioPlaybackState.textContent=`${E||M||w||e.error||C[e.audioState]||"Ready"}${v}${y}${m}${b}`,this._radioPlaybackState.classList.toggle("error",!!(E||M||e.error||e.audioState==="error"))}!i&&!o&&!this.actions.preservePanelStateDuringClear()&&!this._radioPanel.classList.contains("collapsed")&&this.actions.setPanelCollapsed("radio-panel",!0),this.actions.scheduleLayout()}class Ij{constructor({elements:t,radio:n,actions:i,canvas:o}){Object.assign(this,t),this.radio=n,this.actions=i,this.canvas=o,this.destroyed=!1,this.listeners=new AbortController,this._radioUnsubscribe=null,this._radioState=null,this._radioCategorySignature="",this._radioTunerStations=[],this._radioTunerPool=[],this._radioTunerDragging=!1,this._radioTunerDragStartSlot=0,this._radioTunerDragSnapshot=null,this._radioTunerLastSlot=0,this._radioTunerDragDirection=0,this._radioTunerCoordinate=0,this._radioTunerPointerId=null,this._radioTunerKeyboardKey=null,this._radioTunerBandSignature="",this._radioTunerSelectedId=null,this._radioTunerBandPinnedForNavigation=!1,this._refreshRadioTunerBand=null,kj.call(this)}listen(t,n,i,o={}){t==null||t.addEventListener(n,i,{...o,signal:this.listeners.signal})}connect(){var t,n,i;(t=this._radioUnsubscribe)==null||t.call(this),this._radioUnsubscribe=null,!this.destroyed&&(this._radioUnsubscribe=(i=(n=this.radio).subscribe)==null?void 0:i.call(n,o=>this._renderRadioState(o)))}_renderRadioState(t){Aj.call(this,t)}async _revealRadioControlsAfterExplicitEnable(t){var g,_,m,b,C,y;const n=document.getElementById("global-context-panel"),i=n==null?void 0:n.querySelector(".global-context-panel-inner"),o=(g=this._radioPanel)==null?void 0:g.querySelector(".radio-directory-row"),r=(_=this._radioPanel)==null?void 0:_.querySelector(".radio-transport");if(!n||n.classList.contains("collapsed")||!i||!o||!r||!((m=this._radioState)!=null&&m.enabled)||(await new Promise(v=>requestAnimationFrame(()=>requestAnimationFrame(v))),this.destroyed||!((b=this._radioState)!=null&&b.enabled)||!(t!=null&&t.isConnected)))return!1;const s=i.getBoundingClientRect(),a=o.getBoundingClientRect(),c=r.getBoundingClientRect(),l=10,u=i.scrollTop+c.bottom-(s.bottom-l),h=i.scrollTop+a.top-(s.top+l),d=u<=h?Math.min(Math.max(i.scrollTop,u),h):u,f=Math.min(Math.max(0,i.scrollHeight-i.clientHeight),Math.max(0,d));if(Math.abs(f-i.scrollTop)<1)return!1;const p=(y=(C=window.matchMedia)==null?void 0:C.call(window,"(prefers-reduced-motion: reduce)"))==null?void 0:y.matches;return i.scrollTo({top:f,behavior:p?"auto":"smooth"}),!0}async _revealRadioPanelInsideContext({focusTarget:t=null}={}){var l,u,h;const n=document.getElementById("global-context-panel"),i=n==null?void 0:n.querySelector(".global-context-panel-inner");if(!n||n.classList.contains("collapsed")||!i||!this._radioPanel||this._radioPanel.classList.contains("collapsed")||(await new Promise(d=>requestAnimationFrame(()=>requestAnimationFrame(d))),this.destroyed||n.classList.contains("collapsed")||this._radioPanel.classList.contains("collapsed")))return!1;const o=i.getBoundingClientRect(),r=this._radioPanel.getBoundingClientRect(),s=i.scrollTop+r.top-o.top-10,a=Math.min(Math.max(0,i.scrollHeight-i.clientHeight),Math.max(0,s)),c=Math.abs(a-i.scrollTop)>=1;if(c){const d=(u=(l=window.matchMedia)==null?void 0:l.call(window,"(prefers-reduced-motion: reduce)"))==null?void 0:u.matches;i.scrollTo({top:a,behavior:d?"auto":"smooth"})}return(h=t==null?void 0:t.focus)==null||h.call(t,{preventScroll:!0}),c}_syncContextRadioLauncherState(){var r;if(this.destroyed||!this._contextRadioToggleBtn)return;const t=document.getElementById("global-context-panel");if(!!(t&&!t.classList.contains("collapsed"))){const s=!!(this._radioPanel&&!this._radioPanel.classList.contains("collapsed"));this._contextRadioToggleBtn.setAttribute("aria-controls","radio-panel"),this._contextRadioToggleBtn.setAttribute("aria-expanded",String(s));const a=s?"Go to expanded Radio section":"Expand Radio section in Context";this._contextRadioToggleBtn.setAttribute("aria-label",a),this._contextRadioToggleBtn.title=a;return}const i=!!((r=this._contextRadioDock)!=null&&r.classList.contains("disclosure-open"));this._contextRadioToggleBtn.setAttribute("aria-controls","context-radio-mini"),this._contextRadioToggleBtn.setAttribute("aria-expanded",String(i));const o=i?"Close":"Open";this._contextRadioToggleBtn.setAttribute("aria-label",`${o} compact Radio controls`),this._contextRadioToggleBtn.title=`${o} compact Radio controls`}destroy(){var n,i,o,r;if(this.destroyed)return;this.destroyed=!0,this.listeners.abort(),(n=this._radioUnsubscribe)==null||n.call(this),this._radioUnsubscribe=null;const t=this._radioTunerPointerId;this._radioTunerPointerId=null,this._radioTunerDragging=!1,this._radioTunerKeyboardKey=null,this._radioTunerDragSnapshot=null,this._radioTunerPool=[],this._radioTunerStations=[],this._radioTunerBandPinnedForNavigation=!1;try{t!==null&&((i=this._radioTunerSlider)==null||i.releasePointerCapture(t))}catch{}(o=this._radioTuner)==null||o.classList.remove("is-dragging","is-static"),(r=document.getElementById("title-bar"))==null||r.classList.remove("radio-broadcasting"),this.radio.endTuning()}}const Rj=Object.freeze({city:"📍 Location: --",poi:"Landmark: --"});function Lj(e){return String(e??"").split(",").map(t=>t.trim()).filter(Boolean)}function Pj({city:e=null,currentPoi:t=null,searchedLabel:n=""}={}){var o;if(e!=null&&e.name){const r=((o=e.pois)==null?void 0:o[0])||null;return{city:`📍 ${e.name}`,poi:(t==null?void 0:t.name)||(r==null?void 0:r.name)||"--"}}const i=Lj(n);return i.length?{city:`📍 ${i[0]}`,poi:i.length>1?i.slice(1).join(", "):"Searched location"}:{...Rj}}const F0=["Q","W","E","R","T"];class xj{constructor({elements:t,cities:n,getExpandedCity:i,onCity:o,onPoi:r,onSearch:s,onReset:a,doc:c=document,requestFrame:l=h=>requestAnimationFrame(h),cancelFrame:u=h=>cancelAnimationFrame(h)}){Object.assign(this,{elements:t,cities:n,getExpandedCity:i,onCity:o,onPoi:r,onSearch:s,onReset:a,doc:c,requestFrame:l,cancelFrame:u}),this.removers=[],this.poiRemovers=[],this.frame=null,this.destroyed=!1,this.rowGeneration=0,t.pills.replaceChildren();for(const[h,d]of Object.entries(n)){const f=c.createElement("button");f.type="button",f.className="location-pill",f.dataset.locationId=h,f.textContent=d.name,this.bind(f,"click",()=>o(h)),t.pills.appendChild(f)}this.bind(c,"keydown",h=>{var p,g,_;const d=i();if(!d||(g=(p=h.target)==null?void 0:p.matches)!=null&&g.call(p,"select, input, textarea")||h.target===t.search)return;const f=F0.indexOf(h.key.toUpperCase());f!==-1&&f<(((_=n[d])==null?void 0:_.pois.length)||0)&&r(d,f)}),this.bind(t.searchToggle,"click",()=>{t.search.classList.toggle("expanded"),t.search.classList.contains("expanded")&&t.search.focus()}),this.bind(t.search,"keydown",h=>{h.key==="Enter"&&s(t.search.value)});for(const h of t.resetButtons)this.bind(h,"click",a)}bind(t,n,i,o=this.removers){if(!t)return;const r=(...s)=>{if(!this.destroyed)return i(...s)};t.addEventListener(n,r),o.push(()=>t.removeEventListener(n,r))}cancelExpansion(){this.rowGeneration++,this.frame!==null&&this.cancelFrame(this.frame),this.frame=null}showPois(t){if(this.destroyed)return;const n=this.cities[t];if(!n)return;this.cancelExpansion();const i=this.rowGeneration;for(const o of this.poiRemovers.splice(0))o();this.elements.poiRow.replaceChildren(),n.pois.forEach((o,r)=>{const s=this.doc.createElement("button");s.type="button",s.className="poi-pill",s.dataset.poiIndex=r;const a=this.doc.createElement("span");a.className="poi-pill-key",a.textContent=F0[r]||r+1;const c=this.doc.createElement("span");c.className="poi-pill-name",c.textContent=o.name,s.append(a,c),this.bind(s,"click",()=>this.onPoi(t,r),this.poiRemovers),this.elements.poiRow.appendChild(s)}),this.frame=this.requestFrame(()=>{this.destroyed||i!==this.rowGeneration||(this.frame=null,this.elements.poiRow.classList.add("expanded"),this.elements.divider.classList.add("visible"))})}hidePois(){this.destroyed||(this.cancelExpansion(),this.elements.poiRow.classList.remove("expanded"),this.elements.divider.classList.remove("visible"))}highlightPoi(t){if(!this.destroyed)for(const n of this.elements.poiRow.querySelectorAll(".poi-pill"))n.classList.toggle("active",Number(n.dataset.poiIndex)===t)}highlightCity(t){if(!this.destroyed)for(const n of this.elements.pills.querySelectorAll(".location-pill"))n.classList.toggle("active",n.dataset.locationId===t)}renderStatus(t){if(this.destroyed||!this.elements.statusCity||!this.elements.statusPoi)return;const n=Pj(t);this.elements.statusCity.textContent=n.city,this.elements.statusPoi.textContent=n.poi}createOrbitIndicator(){if(this.destroyed)return null;if(!this.orbitIndicator){this.orbitIndicator=this.doc.createElement("div"),this.orbitIndicator.id="orbit-indicator";const t=this.doc.createElement("span");t.className="orbit-icon",t.textContent="↻",this.orbitIndicator.append(t," ORBIT"),this.doc.body.appendChild(this.orbitIndicator)}return this.orbitIndicator}destroy(){var t;if(!this.destroyed){this.destroyed=!0,this.cancelExpansion();for(const n of[...this.poiRemovers.splice(0),...this.removers.splice(0)])n();(t=this.orbitIndicator)==null||t.remove()}}}class Fj{constructor({input:t,begin:n,isCurrent:i,beforeFly:o,search:r,onStart:s,onResult:a,onMissing:c,onError:l,onSettled:u}){Object.assign(this,{input:t,begin:n,isCurrent:i,beforeFly:o,search:r,onStart:s,onResult:a,onMissing:c,onError:l,onSettled:u}),this.controller=null,this.generation=0,this.destroyed=!1,this.state={status:"idle",searching:!1,query:"",generation:null,requestId:0,destination:null,error:null},this.channel=wc(()=>this.state)}getState(){return this.channel.getSnapshot()}subscribe(t,n){return this.channel.subscribe(t,n)}async run(t){var a,c,l,u,h,d;if(t=String(t||"").trim(),!t||this.destroyed)return;const n=this.begin();if(n===!1){this.input.classList.remove("searching"),this.input.blur();return}(a=this.controller)==null||a.abort();const i=new AbortController;this.controller=i;const o=++this.generation,r=()=>!this.destroyed&&o===this.generation&&this.isCurrent(n),s=f=>({type:f,generation:n,requestId:o,query:t});this.state={status:"searching",searching:!0,query:t,generation:n,requestId:o,destination:null,error:null};try{if((c=this.onStart)==null||c.call(this,n),!r()||i.signal.aborted||(this.input.classList.add("searching"),this.channel.publish(s("started")),!r()||i.signal.aborted))return;const f=await this.search(t,{signal:i.signal,beforeFly:()=>r()&&this.beforeFly(n)});if(!r()||i.signal.aborted||f!=null&&f.cancelled)return;if(f){if((l=this.onResult)==null||l.call(this,f,t),!r()||i.signal.aborted)return;this.state={...this.state,status:"found",destination:{...f}},this.channel.publish(s("found"))}else{if((u=this.onMissing)==null||u.call(this),!r()||i.signal.aborted)return;this.state={...this.state,status:"missing"},this.channel.publish(s("missing"))}}catch(f){if(i.signal.aborted||!r()||((h=this.onError)==null||h.call(this,f),!r()||i.signal.aborted))return;this.state={...this.state,status:"failed",error:{message:String((f==null?void 0:f.message)||f)}},this.channel.publish(s("failed"))}finally{this.controller===i&&(this.controller=null),this.destroyed||(o===this.generation&&(this.state={...this.state,searching:!1,status:this.state.status==="searching"?"cancelled":this.state.status}),(d=this.onSettled)==null||d.call(this,n),this.channel.publish(s("settled")))}}destroy(){var t;this.destroyed||(this.destroyed=!0,this.generation++,(t=this.controller)==null||t.abort(),this.controller=null,this.state={...this.state,status:"disposed",searching:!1},this.channel.getSnapshot(),this.channel.destroy())}}function sf(e={}){const t=e||{},n=typeof t.status=="string"?t.status.toLowerCase():"",i=`${t.source||""} ${t.coverage||""}`,o=typeof t.fallback=="boolean",r=Number(t.count)>0||!!t.lastUpdate,s=t.error||t.lastError||t.managerRefreshError;return["unavailable","offline","down","error"].includes(n)||(s||t.unavailable===!0||t.available===!1)&&!r&&!vc.includes(n)?"unavailable":t.loading?"loading":vc.includes(n)?t.stale?"stale":"nominal":t.fallback===!0||n==="fallback"||t.mode==="sim"||/\bfallback\b/i.test(i)||!o&&/\badsb\.lol\b/i.test(i)?"fallback":t.stale||n==="stale"?"stale":t.degraded||s||t.unavailable===!0||t.available===!1?"degraded":"nominal"}const md=Object.freeze({nominal:"ON",loading:"LOADING",degraded:"DEGRADED",stale:"STALE",fallback:"FALLBACK",unavailable:"UNAVAILABLE"}),Sj=[{label:"Movement",ids:["satellites","flights","military","ais-live-vessels","traffic","bikeshare"]},{label:"Cameras",ids:["cctv","alpr-cameras"]},{label:"Infrastructure",ids:["military-installations","local-datacenters","telegeography-submarine-cables","local-dams"]},{label:"Events",ids:["rocket-launches","earthquakes","local-firms"]},{label:"Utilities",ids:["directions","radio"]}],vl=Sj.flatMap(({label:e,ids:t})=>t.map(n=>({id:n,label:e}))),pd=new Map(vl.map(({id:e},t)=>[e,t])),Nj={"ais-live-vessels":"Live Vessels",bikeshare:"Bike Share",cctv:"Cameras","alpr-cameras":"Mapped ALPR Cameras","local-datacenters":"Data Centers","local-firms":"Active Fires"};function gd(e){return Nj[e.id]||e.name}function Dj(e={}){var n;if(((n=e==null?void 0:e.stats)==null?void 0:n.keyRequired)!==!0)return"";const t=String(e.requiresKeyId||"").trim();return t?lu(t):""}class Oj{constructor({getLayers:t,isEnabled:n,setEnabled:i,setLayerParams:o,getRowControls:r,hasRowControls:s,subscribeRowControls:a,onHiddenRefresh:c=()=>{}}){this.getAll=t,this.isEnabled=n,this.setEnabled=i,this.setLayerParams=o,this._rowControlsFor=r,this.hasRowControls=s,this.subscribeRowControls=a,this.onHiddenRefresh=c,this._generation=0,this._removers=[],this._destroyed=!1}mount(t){this._destroyed||(this._releaseBindings(),this._toggleContainer=t,this._renderToggles())}_bind(t,n,i){t.addEventListener(n,i),this._removers.push(()=>t.removeEventListener(n,i))}_releaseBindings(){this._generation++;for(const t of this._removers.splice(0))t()}destroy(){this._destroyed||(this._destroyed=!0,this._releaseBindings(),this._toggleContainer=null)}_renderToggles(){var o;if(this._destroyed||!this._toggleContainer)return;this._releaseBindings(),this._toggleContainer.innerHTML="";const t=this._generation,n=this.getAll().slice().sort((r,s)=>(pd.get(r.id)??vl.length)-(pd.get(s.id)??vl.length));let i="";for(const r of n){if(!r.showInTogglePanel)continue;const s=((o=vl[pd.get(r.id)])==null?void 0:o.label)??"Other layers";if(s&&s!==i){const _=document.createElement("h3");_.className="data-layer-group-heading",_.textContent=s,this._toggleContainer.appendChild(_)}i=s;const a=document.createElement("div");a.className="data-toggle-row",a.dataset.layerId=r.id;const c=document.createElement("div");c.className="data-toggle-top";const l=document.createElement("div");l.className="data-toggle-left";const u=document.createElement("span");u.className="data-icon",u.textContent=r.icon;const h=document.createElement("span");h.className="data-name",h.textContent=gd(r),l.appendChild(u),l.appendChild(h);const d=document.createElement("div");d.className="data-toggle-right";const f=document.createElement("span");f.className="data-count",f.textContent=this._layerCountText(r.stats);const p=document.createElement("button");p.type="button",p.className=`data-toggle-btn${r.enabled?" active":""}`,this._syncToggleButton(p,r),this._bind(p,"click",async()=>{if(!(this._destroyed||this._generation!==t||p.getAttribute("aria-disabled")==="true")){p.setAttribute("aria-disabled","true"),p.setAttribute("aria-busy","true");try{await this.setEnabled(r.id,!this.isEnabled(r.id),{origin:"user"})}catch(_){console.warn(`[Data] ${r.id} toggle error:`,_)}finally{const _=this.getAll().find(({id:m})=>m===r.id);!this._destroyed&&_&&this._generation===t&&this._syncToggleButton(p,_)}}}),d.appendChild(f),d.appendChild(p),c.appendChild(l),c.appendChild(d);const g=document.createElement("div");if(g.className="data-toggle-meta",g.textContent=this._buildMetaText(r),a.appendChild(c),a.appendChild(g),this.hasRowControls(r.id)){const _=this.subscribeRowControls(r.id,()=>this._refreshTogglePanel());_&&this._removers.push(_);const m=document.createElement("div");m.className="data-toggle-controls",this._bind(m,"click",C=>{var M,w,E,k;const y=(w=(M=C.target)==null?void 0:M.closest)==null?void 0:w.call(M,".data-toggle-chip");if(!y||y.disabled)return;const v=(k=(E=this._rowControlsFor(r.id))==null?void 0:E.chips)==null?void 0:k.find(T=>T.id===y.dataset.chipId);!v||v.disabled||!this.isEnabled(r.id)||(typeof v.onClick=="function"?v.onClick():v.params&&this.setLayerParams(r.id,v.params,{origin:"user"}))}),a.appendChild(m);const b=document.createElement("ol");b.className="data-row-list",b.hidden=!0,this._bind(b,"click",C=>{var M,w,E,k,T;const y=(w=(M=C.target)==null?void 0:M.closest)==null?void 0:w.call(M,".data-row-list-item");if(!y||y.disabled)return;const v=(T=(k=(E=this._rowControlsFor(r.id))==null?void 0:E.list)==null?void 0:k.items)==null?void 0:T.find(I=>I.id===y.dataset.listItemId);v!=null&&v.params&&this.setLayerParams(r.id,v.params,{origin:"user"})}),a.appendChild(b),this._syncRowControls(m,r,b)}this._toggleContainer.appendChild(a)}}_layerCountText(t){return typeof t.countLabel=="string"&&t.countLabel.trim()?t.countLabel:t.count?this._formatCount(t.count):"—"}_syncRowControls(t,n,i=null){var c;if(!t)return;const o=n.enabled?this._rowControlsFor(n.id):null,r=(o==null?void 0:o.chips)||[],s=(o==null?void 0:o.legend)||[];this._syncRowList(i,(o==null?void 0:o.list)||null),t.hidden=r.length===0&&s.length===0;for(const l of[...t.children])String(l.className).split(/\s+/).includes("data-toggle-legend-item")&&l.remove();const a=new Map;for(const l of[...t.children])(c=l.dataset)!=null&&c.chipId&&a.set(l.dataset.chipId,l);for(const l of r){let u=a.get(l.id);a.delete(l.id),u||(u=document.createElement("button"),u.type="button",u.dataset.chipId=l.id,t.appendChild(u));const h=l.state||(l.active?"active":"idle");u.className=`data-toggle-chip chip-${h}${l.active?" active":""}`,u.textContent!==l.label&&(u.textContent=l.label),u.title=l.title||"",u.disabled=!!l.disabled,u.setAttribute("aria-pressed",l.active?"true":"false"),u.setAttribute("aria-busy",l.busy?"true":"false")}for(const l of a.values())l.remove();for(const l of s){const u=document.createElement("span");u.className="data-toggle-legend-item",l.blurb&&(u.title=l.blurb);const h=document.createElement("span");h.className="data-toggle-legend-swatch",h.style.background=l.color;const d=document.createElement("span");d.textContent=`${l.label} ${this._formatCount(l.count)}`,u.append(h,d),t.appendChild(u)}}_syncRowList(t,n){var a,c;if(!t)return;const i=(n==null?void 0:n.items)||[];t.hidden=i.length===0,n!=null&&n.ariaLabel&&t.setAttribute("aria-label",n.ariaLabel);const o=new Map;for(const l of[...t.children])(a=l.dataset)!=null&&a.listItemId&&o.set(l.dataset.listItemId,l);let r=null,s=null;for(const l of i){let u=o.get(l.id);o.delete(l.id);let h;if(u)h=u.querySelector(".data-row-list-item");else{u=document.createElement("li"),u.dataset.listItemId=l.id,h=document.createElement("button"),h.type="button",h.className="data-row-list-item",h.dataset.listItemId=l.id;const m=document.createElement("span");m.className="data-row-list-lead";const b=document.createElement("span");b.className="data-row-list-text",h.append(m,b),u.appendChild(h)}const d=r?r.nextSibling:t.firstChild;if(u!==d&&t.insertBefore(u,d),r=u,!h)continue;const f=h.querySelector(".data-row-list-lead"),p=h.querySelector(".data-row-list-text"),g=String(l.lead??""),_=String(l.text??"");f&&f.textContent!==g&&(f.textContent=g),p&&p.textContent!==_&&(p.textContent=_),h.disabled=!!l.disabled,h.classList.toggle("note",!!l.disabled),h.classList.toggle("active",!!l.active),h.classList.toggle("current",!!l.current),h.setAttribute("aria-current",l.current?"step":"false"),h.setAttribute("aria-pressed",l.active?"true":"false"),h.title=_,l.current&&(s=h)}for(const l of o.values())l.remove();s&&t.dataset.currentId!==s.dataset.listItemId?(t.dataset.currentId=s.dataset.listItemId,(c=s.scrollIntoView)==null||c.call(s,{block:"nearest"})):s||delete t.dataset.currentId}_refreshTogglePanel(){if(!(this._destroyed||!this._toggleContainer)){if(typeof document<"u"&&document.hidden){this.onHiddenRefresh();return}for(const t of this.getAll()){const n=this._toggleContainer.querySelector(`[data-layer-id="${t.id}"]`);if(!n)continue;const i=n.querySelector(".data-toggle-btn");i&&this._syncToggleButton(i,t);const o=n.querySelector(".data-count");o&&(o.textContent=this._layerCountText(t.stats));const r=n.querySelector(".data-toggle-meta");r&&(r.textContent=this._buildMetaText(t)),this._syncRowControls(n.querySelector(".data-toggle-controls"),t,n.querySelector(".data-row-list"))}}}_buildMetaText(t){const n=t.stats||{},i=sf(n),o=md[i],r=n.source||t.source,s=t.lifecycleState||(t.enabled?"enabled":"disabled");if(s==="enabling"||s==="disabling")return`${s.toUpperCase()} · ${r}`;if(t.lifecycleUncertain)return`UNCERTAIN · ${r} · lifecycle state requires reconciliation`;const a=n.error||n.lastError||n.managerRefreshError;if(a)return typeof n.retryInSec=="number"&&n.retryInSec>0?`${o} · ${r} · ${a} · retry ${n.retryInSec}s`:`${o} · ${r} · ${a}`;if(vc.includes(String(n.status||"").toLowerCase())&&typeof n.statusMessage=="string"&&n.statusMessage.trim())return`${r} · ${n.statusMessage.trim()}`;const c=n.lastUpdate?this._timeAgo(n.lastUpdate):"never";if(n.loading){const l=typeof n.loadingLabel=="string"&&n.loadingLabel.trim()?n.loadingLabel.trim():"loading...";return`${r} · ${l}`}if(i==="fallback"){const l=typeof n.loadingLabel=="string"&&n.loadingLabel.trim()?n.loadingLabel.trim():n.coverage||c;return`${o} · ${r} · ${l}`}if(i==="stale"){const l=typeof n.retryInSec=="number"&&n.retryInSec>0?` · retrying in ${n.retryInSec}s`:"";return`${o} · ${r} · ${c}${l}`}return typeof n.loadingLabel=="string"&&n.loadingLabel.trim()?`${r} · ${n.loadingLabel.trim()}`:`${r} · ${c}`}_syncToggleButton(t,n){const i=n.enabled?sf(n.stats):"off",o=n.lifecycleState==="enabling"||n.lifecycleState==="disabling",r=!!n.lifecycleUncertain;t.classList.toggle("active",n.enabled),t.classList.toggle("transitioning",o),t.classList.toggle("enabling",n.lifecycleState==="enabling"),t.classList.toggle("disabling",n.lifecycleState==="disabling"),t.classList.toggle("lifecycle-uncertain",r);for(const a of Object.keys(md))t.classList.toggle(`feed-${a}`,n.enabled&&!r&&i===a);t.dataset.feedState=o?n.lifecycleState:r?"uncertain":i,t.disabled=!1,t.setAttribute("aria-disabled",String(o)),t.setAttribute("aria-busy",String(o)),t.textContent=o?n.lifecycleState.toUpperCase():r?"UNCERTAIN":n.enabled?md[i]:"OFF";const s=Dj(n);t.title=s,t.setAttribute("aria-label",s?`${gd(n)}: ${t.textContent}. ${s}`:`${gd(n)}: ${t.textContent}`)}_formatCount(t){return t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}_timeAgo(t){const n=Math.floor((Date.now()-t)/1e3);return n<5?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:`${Math.floor(n/3600)}h ago`}}function Bj(e,t){let n=!1;const i=()=>{n||t()};return e==null||e.addEventListener("click",i),{setBusy(o){n||!e||(e.setAttribute("aria-disabled",String(o)),e.setAttribute("aria-busy",String(o)),e.setAttribute("aria-label",o?"Clearing selected data layers":"Clear selected data layers"))},destroy(){n=!0,e==null||e.removeEventListener("click",i)}}}function uT(e){var n,i,o;const t=e.trackedEntity;return((n=t==null?void 0:t.gevDisplayPosition)==null?void 0:n.call(t))||((o=t==null?void 0:t.position)==null?void 0:o.getValue((i=e.clock)==null?void 0:i.currentTime))}const Vj=Cesium.Math.toRadians(-35),Hj=Cesium.Math.toRadians(-89),$j=Cesium.Math.toRadians(-60);function Zm(e){const t=Cesium.Math.zeroToTwoPi(Number.isFinite(e)?e:0);return Math.abs(t-Cesium.Math.TWO_PI)$j:!1}function Uj(e){return Cesium.Math.toDegrees(Zm(e==null?void 0:e.heading))}function zj(e,{now:t=()=>performance.now(),duration:n=650}={}){let i=null,o=null;const r=()=>{i==null||i(),i=null,o=null};function s(a,c){var d,f,p,g;if(r(),!((f=(d=e.scene)==null?void 0:d.preUpdate)!=null&&f.addEventListener)||n<=0)return S0(e,{...a,...c});const l=e.trackedEntity;o=c;const u=t(),h=Cesium.Math.negativePiToPi(c.heading-a.heading);return i=e.scene.preUpdate.addEventListener(()=>{var C;if((C=e.isDestroyed)!=null&&C.call(e)||e.trackedEntity!==l){r();return}const _=Cesium.Math.clamp((t()-u)/n,0,1),m=Cesium.EasingFunction.CUBIC_IN_OUT(_),b=l?uT(e):a.target;if(!zt(b)||!S0(e,{...a,target:b,heading:a.heading+h*m,pitch:Cesium.Math.lerp(a.pitch,c.pitch,m)})){r();return}_===1&&r()}),(g=(p=e.scene).requestRender)==null||g.call(p),!0}return{animate:s,cancel:r,get destination(){return o}}}function jj({viewer:e,elements:t,runNavigation:n,showToast:i}){var g,_,m,b;const o=t==null?void 0:t.tiltButton,r=t==null?void 0:t.northButton,s=[];let a=!1,c=null,l=!1;const u=zj(e),h=()=>{a||(l=N0(_d(e)),d())};function d(){var y;if(a)return;const C={tilted:l,heading:Math.round(Uj(e==null?void 0:e.camera))%360};c&&c.tilted===C.tilted&&c.heading===C.heading||((!c||c.tilted!==C.tilted)&&(o==null||o.setAttribute("aria-pressed",String(C.tilted)),o==null||o.setAttribute("aria-label",C.tilted?"Return map to straight-down view":"Tilt map to oblique view")),(!c||c.heading!==C.heading)&&((y=r==null?void 0:r.style)==null||y.setProperty("--camera-heading",`${C.heading}deg`),r==null||r.setAttribute("aria-label",`Reset map to north up. Current heading ${C.heading} degrees`)),c=C)}const f=(C,y)=>{C&&(C.addEventListener("click",y),s.push(()=>C.removeEventListener("click",y)))};f(o,()=>{const C=u.destination,y=n("camera",()=>{const v=_d(e);if(!v)return!1;const M=!N0(C||v),w=M?Vj:Hj;return u.animate(v,{heading:(C==null?void 0:C.heading)??v.heading,pitch:w})?{tilted:M,pitch:w}:!1});y&&(i==null||i(y.tilted?"Tilted view":"Straight-down view"),l=y.tilted),d()}),f(r,()=>{const C=u.destination;n("camera",()=>{const v=_d(e);return v&&u.animate(v,{heading:0,pitch:(C==null?void 0:C.pitch)??v.pitch})})&&(i==null||i("North up")),d()});const p=(C,y)=>{var M;const v=(M=C==null?void 0:C.addEventListener)==null?void 0:M.call(C,y);typeof v=="function"&&s.push(v)};p((g=e==null?void 0:e.scene)==null?void 0:g.preRender,d),p((_=e==null?void 0:e.camera)==null?void 0:_.moveEnd,h),p(e==null?void 0:e.trackedEntityChanged,u.cancel);for(const C of["pointerdown","wheel"]){const y=(m=e==null?void 0:e.scene)==null?void 0:m.canvas;(b=y==null?void 0:y.addEventListener)==null||b.call(y,C,u.cancel,{passive:!0}),s.push(()=>{var v;return(v=y==null?void 0:y.removeEventListener)==null?void 0:v.call(y,C,u.cancel)})}return h(),{sync:d,refreshTilt:h,cancel:u.cancel,destroy(){if(!a){a=!0,u.cancel();for(const C of s.splice(0))C()}}}}const qj="map-stack-chip",Wj=Object.freeze(["photoreal","bing-aerial","bing-labels","esri-imagery","osm"]);function Kj(e,t){const n=(e==null?void 0:e.available)!==!1,i=String((e==null?void 0:e.label)??(e==null?void 0:e.id)??""),o=(e==null?void 0:e.requiresIon)===!0,r=o?lu("cesium-ion"):`${i||"This map stack"} is unavailable`,s=n?"":String((e==null?void 0:e.unavailableReason)||r);return{id:String((e==null?void 0:e.id)??""),label:i,available:n,active:!!(e!=null&&e.id)&&e.id===t,requiresIon:o,requirement:!n&&o?"ION":"",unavailableHint:s,title:n?i:s}}function Yj(e,t){const n=new Map((Array.isArray(e)?e:[]).map(i=>[i==null?void 0:i.id,i]));return Wj.map(i=>n.get(i)).filter(Boolean).map(i=>Kj(i,t))}function Xj(e,t,{activeId:n=null,onSelect:i=null,doc:o,bind:r=(s,a,c)=>s.addEventListener(a,c)}={}){if(!e)return[];const s=o||e.ownerDocument||globalThis.document;if(!(s!=null&&s.createElement))return[];e.innerHTML="";const a=Yj(t,n);for(const c of a){const l=s.createElement("button");l.type="button",l.className=[qj,c.active?"active":"",c.available?"":"unavailable"].filter(Boolean).join(" "),l.dataset.stackId=c.id,l.title=c.title,l.setAttribute("aria-pressed",String(c.active)),l.setAttribute("aria-disabled",String(!c.available)),c.available||l.setAttribute("aria-label",`${c.label} unavailable: ${c.unavailableHint}`);const u=s.createElement("span");if(u.className="map-stack-chip-label",u.textContent=c.label,l.appendChild(u),c.requirement){const h=s.createElement("span");h.className="map-stack-chip-req",h.textContent=c.requirement,l.appendChild(h)}r(l,"click",()=>{c.available&&(i==null||i(c.id))}),e.appendChild(l)}return a}function Qj(e,t){var i,o,r;const n=e==null?void 0:e.children;if(n)for(const s of Array.from(n)){const a=(i=s==null?void 0:s.dataset)==null?void 0:i.stackId;if(!a)continue;const c=a===t;(o=s.classList)==null||o.toggle("active",c),(r=s.setAttribute)==null||r.call(s,"aria-pressed",String(c))}}function Zj({container:e,statusElement:t,controller:n,subscribe:i,claimSelection:o=()=>{},onStateChanged:r=()=>{},onError:s=()=>{}}){let a=!1,c=0;const l=[],u=(g,_,m)=>{g.addEventListener(_,m),l.push(()=>g.removeEventListener(_,m))};function h(g){if(!(a||!g)&&(Qj(e,g.activeId),t)){const _=g.activeStack;t.textContent=g.status==="switching"?"...":(_==null?void 0:_.shortLabel)||(_==null?void 0:_.label)||"MAP",t.classList.toggle("warn",!!g.lastError)}}async function d(g,{syncShare:_=!0}={}){if(a)return null;const m=++c;_&&o();const b=n.getActiveId();h(n.getState("switching"));let C;try{C=await n.setStack(g)}catch(y){throw!a&&m===c&&(h(n.getState()),s((y==null?void 0:y.message)||String(y))),y}return a||m!==c||(h(n.getState()),(C==null?void 0:C.activeId)===b&&g!==b&&(C!=null&&C.lastError)&&s(C.lastError),_&&r()),C}function f(){if(!a){for(const g of l.splice(0))g();Xj(e,n.getStacks(),{activeId:n.getActiveId(),onSelect:g=>{d(g).catch(()=>{})},bind:u}),h(n.getState())}}const p=i(()=>{a||(h(n.getState()),r())});return f(),{render:h,select:d,refresh:f,destroy(){if(!a){a=!0,c++,p==null||p();for(const g of l.splice(0))g()}}}}function Jj({elements:e,actions:t}){const n=[],i=(r,s,a,c)=>{if(!r)return;const l=()=>t[a](...c?[c(r)]:[]);r.addEventListener(s,l),n.push(()=>r.removeEventListener(s,l))},o=r=>parseInt(r.value,10);for(const[r,s]of[["bloomButton","toggleBloom"],["sharpenButton","toggleSharpen"],["scopeButton","toggleScope"],["cleanViewButton","toggleCleanView"],["cleanViewExitButton","exitCleanView"],["celestialButton","toggleCelestial"],["hudButton","toggleHud"],["detectionButton","cycleDetection"],["modelsButton","toggleModels"]])i(e[r],"click",s);for(const[r,s]of[["bloomSlider","setBloomIntensity"],["sharpenSlider","setSharpenIntensity"],["scopeFeatherSlider","setScopeFeather"]])i(e[r],"input",s,o);i(e.densitySlider,"input","setDensity",r=>r.value),i(e.hudLayout,"change","setHudLayout",r=>r.value);for(const r of e.styleButtons||[])i(r,"click","setStyle",s=>s.dataset.style);for(const r of e.allocationButtons||[])i(r,"click","setAllocation",s=>s.dataset.allocation);for(const r of e.modelModeButtons||[])i(r,"click","setModelsMode",s=>s.dataset.mode==="all"?"all":"proximity");for(const r of e.fadeSliders||[])i(r,"input","setFade");return{destroy(){for(const r of n.splice(0))r()}}}function eq(e,t,{origin:n="programmatic"}={}){var i;return!(e!=null&&e.trackById)||!t?!1:((i=e.stopTracking)==null||i.call(e,{origin:n}),!!e.trackById(t,{origin:n}))}function dT(e){return!(e!=null&&e.layerId)||!(e.icao24||e.id)?null:{layerId:e.layerId,id:String(e.icao24||e.id)}}function tq({cockpitView:e,selectedLayer:t=null,selectedTarget:n=null,currentLayer:i=null,rollbackLayer:o=null,rollbackTarget:r=void 0,selectionOrigin:s="programmatic"}){var g,_,m,b;const a=dT((g=e==null?void 0:e.readAircraftInfo)==null?void 0:g.call(e)),c=r===void 0?a:r,l=C=>C!=null&&C.layerId&&(C!=null&&C.id)?`${C.layerId}:${C.id}`:null;let u=i,h=a,d=null,f=!1,p=!1;try{!!(t&&(n!=null&&n.id))&&(u=t,h=n,(_=t.trackById)!=null&&_.call(t,n.id,{origin:s})||(d=new Error("Selected aircraft could not be tracked for Cockpit entry"))),d||(f=!!e.enter())}catch(C){p=!0,d=C instanceof Error?C:new Error(String(C))}if(!f&&l(h)!==l(c))try{(m=u==null?void 0:u.stopTracking)==null||m.call(u,{origin:s}),c&&!eq(o,c.id,{origin:s})&&(d||(d=new Error("Prior aircraft tracking could not be restored")))}catch(C){d||(d=C instanceof Error?C:new Error(String(C)))}if(p)try{(b=e.exit)==null||b.call(e,{restoreTracking:!1})}catch{}return{entered:f,error:f?null:(d==null?void 0:d.message)||"Cockpit entry was unavailable"}}class nq{constructor({readLayers:t}){this.readLayers=t,this.destroyed=!1,this._loadingFeedbackState=yl(),this._trafficSyncFeedbackState=tf(),this._loadingFeedbackEvent=null,this._globalStatusNotice=null,this._loadingFeedbackTicker=this._trafficChipTicker=this._toastTimer=null,this._loadingVisibilityHandler=null,this._lastLoadingFeedbackUpdateAt=0,this._globalLoadingStatus=document.getElementById("global-loading-status"),this._globalLoadingLabel=document.getElementById("global-loading-label"),this._globalLoadingDetail=document.getElementById("global-loading-detail"),this._trafficSyncChip=document.getElementById("traffic-sync-chip"),this._trafficSyncLabel=document.getElementById("traffic-sync-label"),this._trafficSyncProgress=document.getElementById("traffic-sync-progress"),this._toast=document.getElementById("toast")}observeVisibility(){this.destroyed||this._loadingVisibilityHandler||(this._loadingVisibilityHandler=()=>{document.hidden?this._stopLoadingFeedbackTicker():this._updateGlobalLoadingFeedback()},document.addEventListener("visibilitychange",this._loadingVisibilityHandler))}_updateTrafficSyncChip(t=!1,n=performance.now()){if(this.destroyed||!this._trafficSyncChip||!this._trafficSyncLabel||!this._trafficSyncProgress)return;const i=this.readLayers(),o=Array.isArray(i)?i.find(s=>s.id==="traffic"):null;this._trafficSyncFeedbackState=u8(this._trafficSyncFeedbackState,{enabled:(o==null?void 0:o.enabled)===!0,stats:(o==null?void 0:o.stats)||{},forceShow:t},n);const r=this._trafficSyncFeedbackState;r.label&&rf(this._trafficSyncLabel,r.label),this._trafficSyncProgress.textContent!==r.progressText&&(this._trafficSyncProgress.textContent=r.progressText),this._trafficSyncChip.classList.toggle("visible",r.visible)}_updateGlobalLoadingFeedback(t=performance.now()){var r,s,a,c;if(this.destroyed||!this._globalLoadingStatus)return;const n=s8(this.readLayers()||[]);this._loadingFeedbackState=d8(this._loadingFeedbackState,n,t,this._loadingFeedbackEvent),this._loadingFeedbackEvent=null;const i=c8(this._globalStatusNotice,this._loadingFeedbackState,n,t);((r=this._globalStatusNotice)==null?void 0:r.persistent)!==!0&&Number.isFinite((s=this._globalStatusNotice)==null?void 0:s.hideAt)&&t>=this._globalStatusNotice.hideAt&&(this._globalStatusNotice=null);const o=Number.isFinite((a=this._globalStatusNotice)==null?void 0:a.hideAt);if((((c=this._loadingFeedbackState)==null?void 0:c.phase)!=="idle"||o)&&this._armLoadingFeedbackTicker(),this._globalLoadingStatus.hidden=!i,!i){delete this._globalLoadingStatus.dataset.state;return}this._globalLoadingStatus.dataset.state=i.state,rf(this._globalLoadingLabel,i.label),this._globalLoadingDetail.textContent=i.detail}_showGlobalStatusNotice(t,n={}){if(this.destroyed)return;const i=performance.now();this._globalStatusNotice=a8(t,i,n),this._updateGlobalLoadingFeedback(i)}_startTrafficChipTicker(){this.destroyed||this._trafficChipTicker||(this._trafficChipTicker=setInterval(()=>{document.hidden||(this._updateTrafficSyncChip(),this._updateGlobalLoadingFeedback())},500))}_armLoadingFeedbackTicker(){this.destroyed||this._loadingFeedbackTicker||document.hidden||(this._loadingFeedbackTicker=setInterval(()=>{var i,o;if(document.hidden){this._stopLoadingFeedbackTicker();return}const t=performance.now();this._lastLoadingFeedbackUpdateAt=t,this._updateGlobalLoadingFeedback(t);const n=Number.isFinite((i=this._globalStatusNotice)==null?void 0:i.hideAt);((o=this._loadingFeedbackState)==null?void 0:o.phase)==="idle"&&!n&&this._stopLoadingFeedbackTicker()},60))}_stopLoadingFeedbackTicker(){this._loadingFeedbackTicker&&(clearInterval(this._loadingFeedbackTicker),this._loadingFeedbackTicker=null)}_showToast(t){this.destroyed||(this._toast.textContent=t,this._toast.classList.add("visible"),clearTimeout(this._toastTimer),this._toastTimer=setTimeout(()=>{this._toast.classList.remove("visible")},2e3))}destroy(){var t;this.destroyed||(this.destroyed=!0,this._stopLoadingFeedbackTicker(),clearInterval(this._trafficChipTicker),clearTimeout(this._toastTimer),this._trafficChipTicker=this._toastTimer=null,this._loadingVisibilityHandler&&document.removeEventListener("visibilitychange",this._loadingVisibilityHandler),this._loadingVisibilityHandler=null,k0(this._globalLoadingLabel),k0(this._trafficSyncLabel),(t=this._toast)==null||t.classList.remove("visible"),this._globalLoadingStatus&&(this._globalLoadingStatus.hidden=!0))}}function iq({trackedEntity:e=null,cockpitActive:t=!1,activate:n,fly:i}={}){const o=n==null?void 0:n();return o?e||t?o:i==null?void 0:i(o):!1}function oq(e={},t={}){return{trackedEntity:e.trackedEntity||t.trackedEntity||null,cockpitActive:!!(e.cockpitActive||t.cockpitActive)}}async function rq({target:e,setEnabled:t,readOwnership:n,shouldFocus:i,activate:o,fly:r,debug:s=console.debug}){var l,u;const a=(n==null?void 0:n())||{};e===!0&&(s==null||s("[UI:CCTV] ownership before setEnabled await",{trackedId:((l=a.trackedEntity)==null?void 0:l.id)??null,cockpitActive:!!a.cockpitActive})),await(t==null?void 0:t(e));const c=(n==null?void 0:n())||{};return e===!0&&(s==null||s("[UI:CCTV] ownership after setEnabled await",{trackedId:((u=c.trackedEntity)==null?void 0:u.id)??null,cockpitActive:!!c.cockpitActive})),!e||!(i!=null&&i())?null:iq({...oq(a,c),activate:o,fly:r})}let sq=class{constructor(t,{mapStackController:n=null,placeSearch:i,services:o,requestServices:r}={}){const{IntelHUD:s,ShareLinkManager:a,OrbitController:c,CelestialRing:l,initTrackedReadout:u,initWorldOverlay:h,initDetection:d,setDetectionStyle:f,trafficLayer:p,flightsLayer:g,militaryFlightsLayer:_,isTr3b:m,toggleTr3b:b,satellitesLayer:C,cctvLayer:y,bikeshareLayer:v,transitLayer:M,aisLiveVesselsLayer:w,militaryAwarenessLayer:E,cachedGroundFloor:k,cachedMeshFloor:T,GROUND_FLOOR_LIFT_M:I,meshFloorPreferred:R,warmGroundFloor:S,sampleMeshFloorCells:A,holdContinuousRender:L,releaseContinuousRender:F,governorRequestRender:P,setScopeMaskEnabled:O,setScopeMaskFeather:D,setScopeTerminusOverride:$,clampScopeTerminusPct:x,fetchRegionalBrief:N,regionalDistanceM:G,weatherCodeLabel:W}=o;this.services=o,this._lifetime=new cu,this._recording=new I8({syncShareState:()=>this._syncShareState()}),Object.assign(this,R8()),this._panelChrome=new $z({elements:{_contextRadioDetailsBtn:this._contextRadioDetailsBtn,_contextRadioDock:this._contextRadioDock,_leftPanelStack:this._leftPanelStack,_locationSearch:this._locationSearch,_ppToggles:this._ppToggles,_rightPanelStack:this._rightPanelStack},operations:{_setRadioDisclosure:(...V)=>this._setRadioDisclosure(...V),_syncCctvPanelViewport:(...V)=>this._syncCctvPanelViewport(...V),_syncContextRadioLauncherState:(...V)=>this._syncContextRadioLauncherState(...V),_showToast:(...V)=>this._showToast(...V)},readHud:()=>this.hud,readCockpit:()=>this.cockpitView,readShareLinks:()=>this.shareLinkManager,readInitialShare:()=>this._initialShareState,readScrollRestoreOwner:()=>this._displayPortalScrollRestoreOwner,readDisplayScrollTop:()=>this._standardDisplayScrollTop}),this._feedback=new nq({readLayers:()=>{var V,H;return((H=(V=this._dataManager)==null?void 0:V.getAll)==null?void 0:H.call(V))||[]}}),this.viewer=t,this.mapStackController=n,this.placeSearch=i,this._navigation=new Jz({viewer:t,tracking:{flightsLayer:g,militaryFlightsLayer:_,satellitesLayer:C,aisLiveVesselsLayer:w,militaryAwarenessLayer:E,rocketLaunchesLayer:o.rocketLaunchesLayer},searchInput:this._locationSearch,interruptCameraMotion:o.interruptCameraMotion,isCockpitActive:()=>{var V;return!!((V=this.cockpitView)!=null&&V.active)},clearLocation:()=>this.clearSearchedLocation(),cancelShareSelection:()=>this._shareRestoration.cancelSelection(),getDataManager:()=>this._dataManager,stopOrbit:()=>this._stopOrbit(),cancelOrientation:()=>{var V;return(V=this._cameraOrientationControls)==null?void 0:V.cancel()},showToast:V=>this._showToast(V)}),this._shareRestoration=new f8({viewer:t,navigation:this._navigation,syncShareState:()=>this._syncShareState(),syncModels3d:V=>this._syncModels3dFromLayerState(V),showStatus:(V,H)=>this._showGlobalStatusNotice(V,H),feedback:this._feedback,updateFeedback:()=>this._updateGlobalLoadingFeedback()}),this._visualSettings=new Zz({viewer:t,mapStackController:n,services:{getDetectionMode:o.getDetectionMode,getDetectionTuning:o.getDetectionTuning,getKeyholeFadeTuning:o.getKeyholeFadeTuning,getScopeMaskFeather:o.getScopeMaskFeather,getScopeTerminusOverride:o.getScopeTerminusOverride,governorRequestRender:o.governorRequestRender,holdContinuousRender:o.holdContinuousRender,isCelestialRingStyleSupported:o.isCelestialRingStyleSupported,isScopeMaskEnabled:o.isScopeMaskEnabled,readDetectionDiagnostics:o.readDetectionDiagnostics,releaseContinuousRender:o.releaseContinuousRender,setDetectionModeByLabel:o.setDetectionModeByLabel,setDetectionStyle:o.setDetectionStyle,setDetectionTuning:o.setDetectionTuning,setKeyholeFadeTuning:o.setKeyholeFadeTuning,setScopeMaskEnabled:o.setScopeMaskEnabled,setScopeMaskFeather:o.setScopeMaskFeather},elements:{_bloomBtn:this._bloomBtn,_bloomSlider:this._bloomSlider,_bloomSliderRow:this._bloomSliderRow,_bloomSliderValue:this._bloomSliderValue,_celestialBtn:this._celestialBtn,_cockpitDisplayToggleBtn:this._cockpitDisplayToggleBtn,_detectionAllocationRow:this._detectionAllocationRow,_detectionBtn:this._detectionBtn,_detectionDensitySlider:this._detectionDensitySlider,_detectionDensityValue:this._detectionDensityValue,_detectionFadeRow:this._detectionFadeRow,_detectionFadeSlider:this._detectionFadeSlider,_detectionFadeValue:this._detectionFadeValue,_detectionOpacityRow:this._detectionOpacityRow,_detectionOpacitySlider:this._detectionOpacitySlider,_detectionOpacityValue:this._detectionOpacityValue,_detectionSliderRow:this._detectionSliderRow,_hudBtn:this._hudBtn,_hudLayoutRow:this._hudLayoutRow,_hudLayoutSelect:this._hudLayoutSelect,_ppToggles:this._ppToggles,_scopeBtn:this._scopeBtn,_scopeFeatherSlider:this._scopeFeatherSlider,_scopeFeatherValue:this._scopeFeatherValue,_sharpenBtn:this._sharpenBtn,_sharpenSlider:this._sharpenSlider,_sharpenSliderRow:this._sharpenSliderRow,_sharpenSliderValue:this._sharpenSliderValue,_sliderContainer:this._sliderContainer,_sliderPanel:this._sliderPanel,_styleIndicator:this._styleIndicator,_styleMiniValue:this._styleMiniValue},operations:{_layoutRightPanels:(...V)=>this._layoutRightPanels(...V),_scheduleAdaptivePanelLayout:(...V)=>this._scheduleAdaptivePanelLayout(...V),_scheduleRightPanelLayout:(...V)=>this._scheduleRightPanelLayout(...V),_setCockpitDisclosure:(...V)=>this._setCockpitDisclosure(...V),_setMapStack:(...V)=>this._setMapStack(...V),_syncPanelCollapseButton:(...V)=>this._syncPanelCollapseButton(...V),_syncShareState:(...V)=>this._syncShareState(...V),setPanelCollapsed:(...V)=>this.setPanelCollapsed(...V)},readHud:()=>this.hud,readCockpit:()=>this.cockpitView,readDataManager:()=>this._dataManager,readShareLinks:()=>this.shareLinkManager,readCelestialRing:()=>this.celestialRing,readContextMode:()=>this._contextMode,readContextChanging:()=>this._contextModeChanging,readDisplayPortalActive:()=>this._cockpitDisplayPortalActive}),this._globeResetPromise=null,this._dataManager=null,this._directionsShellModule=null,this._windowResizeHandler=null,this._cctvRequestFocusHandler=null,this._removeCctvRequestFocusListener=null,this._worldRequestFocusHandler=null,this._removeWorldRequestFocusListener=null,this._removeNavigationAuthorityListener=null,this._navigationOwnerChangedRemover=null,this._awarenessSelectedHandler=null,this._awarenessClearedHandler=null,this._disposed=!1,this._mapStackChangeHandler=null,this._cockpitDisplayPortal=null,this._cockpitDisplayModeHandler=null,this._activeLocationId=null,this._expandedCityId=null,this._activePoiIndex=null,this._currentTarget=null,this._currentPoi=null,this._searchedLocationLabel=null,this._trafficTransitionTimer=null,this._lastTrafficChipUpdateAt=0,this.orbitController=new c(t),this._orbitIndicator=null,this.hud=new s(t,{placeSearch:i,summaryService:r==null?void 0:r.summary}),this._recording.hud=this.hud,this.cockpitView=new F6(t,{services:{flightsLayer:g,militaryFlightsLayer:_,isTr3b:m,toggleTr3b:b,militaryAwarenessLayer:E,formatAwarenessLabel:au,cachedGroundFloor:k,cachedMeshFloor:T,GROUND_FLOOR_LIFT_M:I,meshFloorPreferred:R,warmGroundFloor:S,sampleMeshFloorCells:A,holdContinuousRender:L,releaseContinuousRender:F,fetchRegionalBrief:N,regionalDistanceM:G,weatherCodeLabel:W},onVisionChange:(V,H,B)=>this._setCockpitVision(V,H,B),onCameraTakeover:()=>this._stampNavigation({cancelPendingSelection:!1}),getInheritedVisionLabel:()=>WE[this.activeStyle]||String(this.activeStyle||"normal").toUpperCase(),isEntryAllowed:()=>{var V,H;return aT({contextMode:this._contextMode,contextModeChanging:this._contextModeChanging,flightsEnabled:!!((V=this._dataManager)!=null&&V.isEnabled("flights")),militaryEnabled:!!((H=this._dataManager)!=null&&H.isEnabled("military"))})},onEntered:()=>this._panelChrome.enterCockpit(),onExited:()=>this._panelChrome.exitCockpit(),restoreTrackingFrame:V=>{var z,j;const[H,...B]=String((V==null?void 0:V.gevTrackedId)||"").split(":"),q=B.join(":");return q?H==="flights"?((z=g.refocusTrackedById)==null?void 0:z.call(g,q))===!0:H==="military"?((j=_.refocusTrackedById)==null?void 0:j.call(_,q))===!0:!1:!1}}),this.celestialRing=new l(t,{enabled:!1,onAutoDisable:()=>this.setCelestialRingEnabled(!1,{syncShare:!!this.shareLinkManager,focus:!1})}),this.shareLinkManager=new a(t,{onRestore:async V=>{var ye,ve,pe;const{style:H,bloom:B,sharpen:q,bloomIntensity:z,bloomVersion:j,sharpenIntensity:ne,hudVariant:ee,hudVisible:re,detectionMode:se,detectionDensity:me,detectionAllocation:be,detectionFadePct:J,detectionOutsideOpacityPct:Z,celestialRing:ae,scopeEnabled:oe,scopeFeatherPct:le,scopeTerminusPct:Y,mapStack:K,panelState:_e,styleParams:he}=V||{};if(H&&H!=="normal"&&H!=="ai-edit"&&this.setStyle(H,{applyPreset:!0,revealParameters:!1,restore:!0}),he&&H&&this.stages[H]&&((ye=Ir[H])!=null&&ye.uniforms)){for(const[te,de]of Object.entries(he))Object.hasOwn(Ir[H].uniforms,te)&&(this.stages[H].uniforms[te]=de);this._updateSliderPanel(H,{reveal:!1})}if(typeof z=="number"&&this._bloomSlider){const te=ca(z,j);this._setBloomIntensity(te,{syncShare:!1})}if(typeof ne=="number"&&this._sharpenSlider){const te=Math.max(0,Math.min(100,Math.round(ne)));this._sharpenSlider.value=String(te),this._sharpenSliderValue.textContent=`${te}%`,this._applySharpenIntensity(te/100)}if(typeof B=="boolean"&&this._setBloomEnabled(B),typeof q=="boolean"&&this._setSharpenEnabled(q),ee&&this._setHudVariant(ee),typeof re=="boolean"&&(this.hud.setMode(re?"on":"off"),this._updateHudButtonState()),typeof me=="number"&&this._detectionDensitySlider){const te=wt(me);this._detectionDensitySlider.value=String(te),this._detectionDensityValue.textContent=`${te}%`,this._applyDetectionDensityFromUi()}if(be&&this._setDetectionAllocation(be,{syncShare:!1,persist:!1}),typeof J=="number"&&this._detectionFadeSlider&&(this._detectionFadeSlider.value=String(J)),typeof Z=="number"&&this._detectionOpacitySlider&&(this._detectionOpacitySlider.value=String(Z)),this._applyDetectionFadeFromUi(),se&&this._setDetectionMode(se),typeof ae=="boolean"&&this.setCelestialRingEnabled(ae,{syncShare:!1,focus:!1}),typeof oe=="boolean"&&(O(oe),(ve=this._scopeBtn)==null||ve.classList.toggle("active",oe),(pe=this._scopeBtn)==null||pe.setAttribute("aria-pressed",String(oe))),typeof le=="number"&&this._scopeFeatherSlider){const te=Math.max(0,Math.min(100,Math.round(le)));this._scopeFeatherSlider.value=String(te),this._scopeFeatherValue&&(this._scopeFeatherValue.textContent=`${te}%`),D(te/100)}if(Y===null)$(null);else if(typeof Y=="number"){const te=x(Y);$(te==null?null:te/100)}const Ce=K?this._setMapStack(K,{syncShare:!1}):Promise.resolve();_e&&this._restorePanelState(_e),await Ce,this._syncShareState()},isNavigationCurrent:V=>V===this._navigationGeneration,cancelOwnedNavigation:()=>this.viewer.camera.cancelFlight()}),this.shareLinkManager.setPanelStateProvider(()=>this._buildSharePanelState()),this.shareLinkManager.setStyleParamStateProvider(V=>{const H=Ir[V],B=this.stages[V];return!(H!=null&&H.uniforms)||!B?null:Object.fromEntries(Object.keys(H.uniforms).map(q=>[q,B.uniforms[q]]))}),this._shareState=wc(()=>this._readShareState()),this._shareState.subscribe(({state:V})=>{this.shareLinkManager.onToggleChange(V.bloomEnabled,V.sharpenEnabled,V.options)},{emitCurrent:!1}),this._locationState=wc(()=>{var V;return((V=this._locationLookup)==null?void 0:V.getState())||null}),this._locationState.subscribe(({state:V,change:H})=>{this._handleLocationSearchState(V,H)},{emitCurrent:!1}),this._shareRestoration.attachLinks(this.shareLinkManager),this._models3dModeBtns=[document.getElementById("models3d-mode-proximity"),document.getElementById("models3d-mode-all")],this._models3dEnabled=!0,this._models3dMode="proximity",h(t),d(t,[p,g,_,C,y,v,M,w],V=>{this._updateDetectionButton(V)}),u(t),f(this.activeStyle),this._applyDetectionDensityFromUi(),this._initStages(),this._initBloomSharpen(),this._initUI(),this._initMapStackControl(),this._initPanelChrome(),this._initLeftPanelAdaptiveLayout(),this._initRightPanelAdaptiveLayout(),this._initRadioPanel(),this._initCctvPanel(),this._initGlobalContextPanel(),this._initLocationBar(),this._initShareButton(),this._initCameraOrientationControls(),this._initClearSelectedLayersButton(),this._initHUDToggle(),this._initModels3dToggle(),this._applyGlobalPostDefaults(),this._initOrbit(),this._initRecordingOverlay(),this._startAnimationLoop(),this._startTrafficChipTicker(),this._updateStyleMiniStatus(),this._updateLocationMiniStatus(),this._shareRestoration.start(),this._layoutRightPanels(),this._syncCctvPanelViewport(),this._windowResizeHandler=()=>{this._scheduleRightPanelLayout({reconsiderAutoCollapse:!0}),this._syncCctvPanelViewport(),this._scheduleLeftPanelLayout({reconsiderAutoCollapse:!0})},window.addEventListener("resize",this._windowResizeHandler),this._feedback.observeVisibility(),this._cctvRequestFocusHandler=V=>kM(V,(H,B)=>this._runExplicitCctvFocus(H,B),(H,B)=>y.focusCamera(H,B)),this._removeCctvRequestFocusListener=TM(window,this._cctvRequestFocusHandler),this._worldRequestFocusHandler=V=>hM(V,(H,B)=>this._runExplicitWorldFocus(H,B),H=>fM(this.viewer,H)),this._removeWorldRequestFocusListener=dM(window,this._worldRequestFocusHandler),this._navigationOwnerChangedRemover=t.trackedEntityChanged.addEventListener(V=>{V&&!this._disposed&&this._stampNavigation({cancelPendingSelection:!1})}),this._removeNavigationAuthorityListener=TE(window,V=>{var H;this._disposed||this._stampNavigation({cancelPendingSelection:((H=V==null?void 0:V.detail)==null?void 0:H.cancelPendingSelection)!==!1})})}get _navigationGeneration(){return this._navigation._navigationGeneration}set _navigationGeneration(t){this._navigation._navigationGeneration=t}get _activeLocationSearchGeneration(){return this._navigation._activeLocationSearchGeneration}set _activeLocationSearchGeneration(t){this._navigation._activeLocationSearchGeneration=t}get _shareTrackingAcquiringKey(){return this._shareRestoration._shareTrackingAcquiringKey}set _shareTrackingAcquiringKey(t){this._shareRestoration._shareTrackingAcquiringKey=t}get _shareTrackingNoticeGeneration(){return this._shareRestoration._shareTrackingNoticeGeneration}set _shareTrackingNoticeGeneration(t){this._shareRestoration._shareTrackingNoticeGeneration=t}get _initialShareState(){return this._shareRestoration._initialShareState}set _initialShareState(t){this._shareRestoration._initialShareState=t}get _initialShareNavigationGeneration(){return this._shareRestoration._initialShareNavigationGeneration}set _initialShareNavigationGeneration(t){this._shareRestoration._initialShareNavigationGeneration=t}get _initialShareRestoreTimeout(){return this._shareRestoration._initialShareRestoreTimeout}set _initialShareRestoreTimeout(t){this._shareRestoration._initialShareRestoreTimeout=t}get _layerStateCoordinator(){return this._shareRestoration._layerStateCoordinator}set _layerStateCoordinator(t){this._shareRestoration._layerStateCoordinator=t}get _layerStateRestorePromise(){return this._shareRestoration._layerStateRestorePromise}set _layerStateRestorePromise(t){this._shareRestoration._layerStateRestorePromise=t}get _initialShareRestorePromise(){return this._shareRestoration._initialShareRestorePromise}set _initialShareRestorePromise(t){this._shareRestoration._initialShareRestorePromise=t}get _resolveInitialShareRestore(){return this._shareRestoration._resolveInitialShareRestore}set _resolveInitialShareRestore(t){this._shareRestoration._resolveInitialShareRestore=t}get _hasShareState(){return this._shareRestoration._hasShareState}set _hasShareState(t){this._shareRestoration._hasShareState=t}get _initialShareSelectionSuperseded(){return this._shareRestoration._initialShareSelectionSuperseded}set _initialShareSelectionSuperseded(t){this._shareRestoration._initialShareSelectionSuperseded=t}get _initialShareGestureHandler(){return this._shareRestoration._initialShareGestureHandler}set _initialShareGestureHandler(t){this._shareRestoration._initialShareGestureHandler=t}get _visualEffects(){return this._visualSettings._visualEffects}set _visualEffects(t){this._visualSettings._visualEffects=t}get activeStyle(){return this._visualSettings.activeStyle}set activeStyle(t){this._visualSettings.activeStyle=t}get _detectionUserOverridden(){return this._visualSettings._detectionUserOverridden}set _detectionUserOverridden(t){this._visualSettings._detectionUserOverridden=t}get _cockpitVisionMode(){return this._visualSettings._cockpitVisionMode}set _cockpitVisionMode(t){this._visualSettings._cockpitVisionMode=t}get _cockpitVisionRestore(){return this._visualSettings._cockpitVisionRestore}set _cockpitVisionRestore(t){this._visualSettings._cockpitVisionRestore=t}get _contactsDetectionRestore(){return this._visualSettings._contactsDetectionRestore}set _contactsDetectionRestore(t){this._visualSettings._contactsDetectionRestore=t}get _detectionAllocationBtns(){return this._visualSettings._detectionAllocationBtns}set _detectionAllocationBtns(t){this._visualSettings._detectionAllocationBtns=t}get _detectionAllocationPreference(){return this._visualSettings._detectionAllocationPreference}set _detectionAllocationPreference(t){this._visualSettings._detectionAllocationPreference=t}get _styleParameters(){return this._visualSettings._styleParameters}set _styleParameters(t){this._visualSettings._styleParameters=t}get _irBoostActive(){return this._visualSettings._irBoostActive}set _irBoostActive(t){this._visualSettings._irBoostActive=t}get _irFogWasEnabled(){return this._visualSettings._irFogWasEnabled}set _irFogWasEnabled(t){this._visualSettings._irFogWasEnabled=t}get _panelDisclosureControls(){return this._panelChrome._panelDisclosureControls}set _panelDisclosureControls(t){this._panelChrome._panelDisclosureControls=t}get _hoverPanelControls(){return this._panelChrome._hoverPanelControls}set _hoverPanelControls(t){this._panelChrome._hoverPanelControls=t}get _cancelMapSourceFocus(){return this._panelChrome._cancelMapSourceFocus}set _cancelMapSourceFocus(t){this._panelChrome._cancelMapSourceFocus=t}get _cockpitContextCollapsedForDataPanel(){return this._panelChrome._cockpitContextCollapsedForDataPanel}set _cockpitContextCollapsedForDataPanel(t){this._panelChrome._cockpitContextCollapsedForDataPanel=t}get _cockpitPanelRestore(){return this._panelChrome._cockpitPanelRestore}set _cockpitPanelRestore(t){this._panelChrome._cockpitPanelRestore=t}get _panelPosition(){return this._panelChrome._panelPosition}set _panelPosition(t){this._panelChrome._panelPosition=t}get _panelLayout(){return this._panelChrome._panelLayout}set _panelLayout(t){this._panelChrome._panelLayout=t}get stages(){return this._visualSettings.stages}get transitions(){return this._visualSettings.transitions}get bloomEnabled(){return this._visualSettings.bloomEnabled}get sharpenEnabled(){return this._visualSettings.sharpenEnabled}get _bloomStage(){return this._visualEffects.bloomStage}get _sharpenStage(){return this._visualEffects.sharpenStage}_stampNavigation({cancelPendingSelection:t=!0,clearSearchedLocation:n=!0}={}){return this._navigation._stampNavigation(...arguments)}_settleLocationSearchUi(t){return this._navigation._settleLocationSearchUi(...arguments)}_releaseFollowCamera({preserveVesselSelection:t=!0,preserveCameraFlight:n=!1,trackingOrigin:i="tool"}={}){return this._navigation._releaseFollowCamera(...arguments)}_runExplicitNavigation(t,n,i=void 0){return this._navigation._runExplicitNavigation(...arguments)}_beginDeferredNavigation(t="location",{cancelPendingSelection:n=!0}={}){return this._navigation._beginDeferredNavigation(...arguments)}_reassertNavigationHandoff(t){return this._navigation._reassertNavigationHandoff(...arguments)}beginDeferredLocationNavigation(){return this._beginDeferredNavigation("location")}reassertDeferredLocationNavigation(t){return this._reassertNavigationHandoff(t)}runImmediateLocationNavigation(t){return this.runImmediateNavigation("location",t)}runImmediateNavigation(t,n,i=void 0){return this._runExplicitNavigation(t,n,i)}_connectDirectionsCamera(){var n,i,o,r;if(!this._dataManager){(i=(n=this._directionsShellModule)==null?void 0:n.attachShellServices)==null||i.call(n,null),this._directionsShellModule=null;return}const t=(r=(o=this._dataManager.layers)==null?void 0:o.get("directions"))==null?void 0:r.module;typeof(t==null?void 0:t.attachShellServices)=="function"&&(this._directionsShellModule=t,t.attachShellServices({runNavigation:s=>this.runImmediateNavigation("route",s),floorFn:(s,a)=>this.services.cachedGroundFloor(s,a),warmFn:s=>this.services.warmGroundFloor(s),showToast:s=>this._showToast(s)}))}supersedeDeferredNavigation(){return this._stampNavigation()}_runExplicitWorldFocus(t,n){return this._runExplicitNavigation((t==null?void 0:t.kind)||"target",n)}getAircraftTrackingTarget(){var t,n;return dT((n=(t=this.cockpitView)==null?void 0:t.readAircraftInfo)==null?void 0:n.call(t))}_reclampDraggablePanels(){return this._panelPosition._reclampDraggablePanels()}_initStages(){return this._visualSettings._initStages(...arguments)}_setStageIntensity(t,n){return this._visualSettings._setStageIntensity(...arguments)}_syncStagesEnabledFromIntensity(){return this._visualSettings._syncStagesEnabledFromIntensity(...arguments)}_syncContactsDetection(){return this._visualSettings._syncContactsDetection(...arguments)}_setCockpitVision(t,n,{revealParameters:i=!1}={}){return this._visualSettings._setCockpitVision(...arguments)}_syncIrBoost(){return this._visualSettings._syncIrBoost(...arguments)}_syncCockpitInheritedStyle(){return this._visualSettings._syncCockpitInheritedStyle(...arguments)}_revealCockpitStyleParameters({openDisplay:t=!1}={}){return this._visualSettings._revealCockpitStyleParameters(...arguments)}_initBloomSharpen(){return this._visualSettings._initBloomSharpen(...arguments)}_getBloomIntensity(){return this._visualSettings._getBloomIntensity(...arguments)}_syncBloomStageEnabled(){return this._visualSettings._syncBloomStageEnabled(...arguments)}_setBloomIntensity(t,{syncShare:n=!0}={}){return this._visualSettings._setBloomIntensity(...arguments)}_applyBloomIntensity(t){return this._visualSettings._applyBloomIntensity(...arguments)}_setBloomEnabled(t){return this._visualSettings._setBloomEnabled(...arguments)}_applySharpenIntensity(t){return this._visualSettings._applySharpenIntensity(...arguments)}_setSharpenEnabled(t){return this._visualSettings._setSharpenEnabled(...arguments)}_initUI(){var r,s,a;const{cycleDetectionMode:t,setScopeMaskEnabled:n,isScopeMaskEnabled:i,setScopeMaskFeather:o}=this.services;(r=this._applicationShortcuts)==null||r.destroy(),(s=this._frameRateMonitor)==null||s.destroy(),this._frameRateMonitor=m8({viewer:this.viewer,documentRef:document}),this._applicationShortcuts=Uz({documentRef:document,searchInput:this._locationSearch,actions:{setStyle:c=>this.setStyle(c),dismissSearch:()=>{this._locationSearch.classList.contains("expanded")&&(this._locationSearch.classList.remove("expanded"),this._locationSearch.value="",this._locationSearch.blur())},toggleHud:()=>{var c,l;(l=(c=this.shareLinkManager)==null?void 0:c.claimRestoreLane)==null||l.call(c,"visual"),this.hud.toggle(),this._updateHudButtonState(),this._syncShareState()},toggleOrbit:()=>this._toggleOrbit(),toggleCleanView:()=>this.toggleCleanView(),toggleLayers:()=>document.getElementById("data-panel").classList.toggle("active"),cycleDetection:()=>{var c,l;(l=(c=this.shareLinkManager)==null?void 0:c.claimRestoreLane)==null||l.call(c,"visual"),this._detectionUserOverridden=!0,t(),this._syncShareState()},toggleCctv:()=>this._toggleCctvEnabled()}}),(a=this._displayControls)==null||a.destroy(),this._displayControls=Jj({elements:{styleButtons:document.querySelectorAll(".style-btn"),bloomButton:this._bloomBtn,bloomSlider:this._bloomSlider,sharpenButton:this._sharpenBtn,sharpenSlider:this._sharpenSlider,scopeButton:this._scopeBtn,scopeFeatherSlider:this._scopeFeatherSlider,hudLayout:this._hudLayoutSelect,hudButton:this._hudBtn,cleanViewButton:this._cleanViewBtn,cleanViewExitButton:this._cleanViewExitBtn,densitySlider:this._detectionDensitySlider,detectionButton:this._detectionBtn,allocationButtons:this._detectionAllocationBtns,fadeSliders:[this._detectionFadeSlider,this._detectionOpacitySlider],celestialButton:this._celestialBtn,modelsButton:this._models3dBtn,modelModeButtons:this._models3dBtn?this._models3dModeBtns:[]},actions:{setStyle:c=>this.setStyle(c),toggleBloom:()=>{var c,l;(l=(c=this.shareLinkManager)==null?void 0:c.claimRestoreLane)==null||l.call(c,"visual"),this._setBloomEnabled(!this.bloomEnabled)},setBloomIntensity:c=>{var l,u;(u=(l=this.shareLinkManager)==null?void 0:l.claimRestoreLane)==null||u.call(l,"visual"),this._setBloomIntensity(c)},toggleSharpen:()=>{var c,l;(l=(c=this.shareLinkManager)==null?void 0:c.claimRestoreLane)==null||l.call(c,"visual"),this._setSharpenEnabled(!this.sharpenEnabled)},toggleScope:()=>{var l,u;(u=(l=this.shareLinkManager)==null?void 0:l.claimRestoreLane)==null||u.call(l,"visual");const c=!i();n(c),this._scopeBtn.classList.toggle("active",c),this._scopeBtn.setAttribute("aria-pressed",String(c)),this._syncShareState()},setScopeFeather:c=>{var u,h;(h=(u=this.shareLinkManager)==null?void 0:u.claimRestoreLane)==null||h.call(u,"visual");const l=Math.max(0,Math.min(100,c||0));this._scopeFeatherValue&&(this._scopeFeatherValue.textContent=`${l}%`),o(l/100),this._syncShareState()},setSharpenIntensity:c=>{var l,u;(u=(l=this.shareLinkManager)==null?void 0:l.claimRestoreLane)==null||u.call(l,"visual"),this._sharpenSliderValue&&(this._sharpenSliderValue.textContent=`${c}%`),this._applySharpenIntensity(c/100),this._syncShareState()},setHudLayout:c=>{var l,u;(u=(l=this.shareLinkManager)==null?void 0:l.claimRestoreLane)==null||u.call(l,"visual"),this._setHudVariant(c)},toggleCleanView:()=>this.toggleCleanView(),exitCleanView:()=>this.toggleCleanView(!1),setDensity:c=>{var u,h;(h=(u=this.shareLinkManager)==null?void 0:u.claimRestoreLane)==null||h.call(u,"visual"),this._detectionUserOverridden=!0;const l=wt(c);this._detectionDensitySlider.value=String(l),this._detectionDensityValue&&(this._detectionDensityValue.textContent=`${l}%`),this._applyDetectionDensityFromUi(),this._syncShareState()},setAllocation:c=>{var l,u;(u=(l=this.shareLinkManager)==null?void 0:l.claimRestoreLane)==null||u.call(l,"visual"),this._detectionUserOverridden=!0,this._setDetectionAllocation(c)},setFade:()=>{var c,l;(l=(c=this.shareLinkManager)==null?void 0:c.claimRestoreLane)==null||l.call(c,"visual"),this._applyDetectionFadeFromUi(),this._syncShareState()},toggleCelestial:()=>{var l;const c=!!((l=this.celestialRing)!=null&&l.visible);!this.celestialRingEnabled||!c?this.setCelestialRingEnabled(!0,{focus:!0}):this.setCelestialRingEnabled(!1)},toggleHud:()=>{var c,l;(l=(c=this.shareLinkManager)==null?void 0:c.claimRestoreLane)==null||l.call(c,"visual"),this.hud.toggle(),this._updateHudButtonState(),this._syncShareState()},cycleDetection:()=>{var c,l;(l=(c=this.shareLinkManager)==null?void 0:c.claimRestoreLane)==null||l.call(c,"visual"),this._detectionUserOverridden=!0,t(),this._syncShareState()},toggleModels:()=>{this._setModels3dEnabled(!this._models3dEnabled),this._syncModels3dModeRow()},setModelsMode:c=>this._setModels3dMode(c)}})}_initMapStackControl(){var t;this.mapStackController&&((t=this._mapSourceControls)==null||t.destroy(),this._mapSourceControls=Zj({container:this._mapStackChips,statusElement:this._mapStackStatus,controller:this.mapStackController,subscribe:n=>(window.addEventListener("gev:map-stack-changed",n),()=>window.removeEventListener("gev:map-stack-changed",n)),claimSelection:()=>{var n,i;return(i=(n=this.shareLinkManager)==null?void 0:n.claimRestoreLane)==null?void 0:i.call(n,"map")},onStateChanged:()=>this._syncShareState(),onError:n=>this._showToast(n)}))}async _setMapStack(t,{syncShare:n=!0}={}){if(this.mapStackController)return this._mapSourceControls.select(t,{syncShare:n})}_renderMapStackState(t){var n;(n=this._mapSourceControls)==null||n.render(t)}_applyDetectionDensityFromUi(){return this._visualSettings._applyDetectionDensityFromUi(...arguments)}_applyDetectionFadeFromUi(){return this._visualSettings._applyDetectionFadeFromUi(...arguments)}_setDetectionAllocation(t,{syncShare:n=!0,persist:i=!0}={}){return this._visualSettings._setDetectionAllocation(...arguments)}_syncDetectionUiFromEngine(){return this._visualSettings._syncDetectionUiFromEngine(...arguments)}_setDetectionMode(t){return this._visualSettings._setDetectionMode(...arguments)}_setHudVariant(t){return this._visualSettings._setHudVariant(...arguments)}_scheduleAdaptivePanelLayout(t){return this._panelLayout._scheduleAdaptivePanelLayout(t)}_applyStylePresetDefaults(t){return this._visualSettings._applyStylePresetDefaults(...arguments)}_applyDetectionPreset(t){return this._visualSettings._applyDetectionPreset(...arguments)}_applyGlobalPostDefaults(){return this._visualSettings._applyGlobalPostDefaults(...arguments)}_shareableDetectionState(){return this._visualSettings._shareableDetectionState(...arguments)}subscribeShareState(t,n){return this._shareState.subscribe(t,n)}_syncShareState(){this._disposed||this._shareState.publish({type:"settings-changed"})}_readShareState(){return this._visualSettings._readShareState(...arguments)}_updateTrafficSyncChip(t,n){return this._feedback._updateTrafficSyncChip(t,n)}_initPanelChrome(){return this._panelChrome._initPanelChrome(...arguments)}_collapsePanelOnEscape(t,n){return this._panelChrome._collapsePanelOnEscape(...arguments)}_initCommandDockPins(){return this._panelChrome._initCommandDockPins(...arguments)}_setCommandDockPanelPinState(t,n,{restore:i=!1,persist:o=!0,syncShare:r=!0}={}){return this._panelChrome._setCommandDockPanelPinState(...arguments)}_initCommandDockTrayMetrics(){return this._panelChrome._initCommandDockTrayMetrics(...arguments)}_updateCommandDockTrayStack(){return this._panelChrome._updateCommandDockTrayStack(...arguments)}_maybeNotifyLayoutReset(){return this._panelChrome._maybeNotifyLayoutReset(...arguments)}_initAutoHoverPanel(t,{openDelayMs:n=850,closeDelayMs:i=1e3}={}){return this._panelChrome._initAutoHoverPanel(...arguments)}_initPanelDrag(){return this._panelPosition._initPanelDrag()}_persistAwarenessSelection(t,n=!1){var c,l,u,h,d,f,p,g,_;if(!this._dataManager)return;const i=String(((c=t==null?void 0:t.detail)==null?void 0:c.origin)||"programmatic");if(!Mo(i))return;const o=String(((l=t==null?void 0:t.detail)==null?void 0:l.layerId)||""),r={flights:{key:"selectedFlightsTrackingId",normalize:m=>String(m??"").trim().toLowerCase()||null},military:{key:"selectedMilitaryTrackingId",normalize:m=>String(m??"").trim().toLowerCase()||null},satellites:{key:"selectedSatTrackingId",normalize:m=>{const b=Number(m);return Number.isFinite(b)&&b>0?Math.trunc(b):null}}}[o];if(!r)return;const s=n?null:r.normalize((u=t==null?void 0:t.detail)==null?void 0:u.id);if(n||s===null){(d=(h=this._dataManager).adoptLayerParams)==null||d.call(h,o,{[r.key]:s},{origin:i});return}if(((p=(f=this._dataManager).adoptLayerVisibility)==null?void 0:p.call(f,o,!0,{origin:i,adoptedFromSelection:!0}))!==!1){for(const[m,b]of[["flights","selectedFlightsTrackingId"],["military","selectedMilitaryTrackingId"],["satellites","selectedSatTrackingId"]])m!==o&&this._dataManager.setLayerParams(m,{[b]:null},{origin:i});(_=(g=this._dataManager).adoptLayerParams)==null||_.call(g,o,{[r.key]:s},{origin:i})}}attachDataManager(t){var n;this._dataManager=t||null,this.hud.attachDataManager(this._dataManager),this._updateTrafficSyncChip(),this._dataManagerUnsubscribe&&(this._dataManagerUnsubscribe(),this._dataManagerUnsubscribe=null),this._contextControls.connect(this._dataManager),typeof((n=this._dataManager)==null?void 0:n.subscribe)=="function"&&(this._dataManagerUnsubscribe=this._dataManager.subscribe(i=>{this._feedback._loadingFeedbackEvent=i,this._updateGlobalLoadingFeedback(performance.now())})),this._updateGlobalLoadingFeedback(performance.now()),this._syncContextModeButtons(),this._cctvControls.connect(),this._radioControls.connect(),this._connectDirectionsCamera(),this._awarenessSelectedHandler||(this._awarenessSelectedHandler=i=>this._persistAwarenessSelection(i,!1),this._awarenessClearedHandler=i=>this._persistAwarenessSelection(i,!0),window.addEventListener("gev:awareness-subject-selected",this._awarenessSelectedHandler),window.addEventListener("gev:awareness-subject-cleared",this._awarenessClearedHandler)),this._shareRestoration.connect(this._dataManager)}_handleShareTrackingRestoreStatus(t){return this._shareRestoration._handleShareTrackingRestoreStatus(...arguments)}get _contextMode(){var t;return((t=this._contextControls)==null?void 0:t._contextMode)??null}get _contextModeChanging(){var t;return((t=this._contextControls)==null?void 0:t._contextModeChanging)??!1}get _preservePanelStateDuringLayerClear(){var t;return((t=this._contextControls)==null?void 0:t._preservePanelStateDuringLayerClear)??!1}_initGlobalContextPanel(){const{radioLayer:t,militaryInstallationsLayer:n}=this.services;this._contextControls=new uj({elements:{_globalContextPanel:document.getElementById("global-context-panel"),_globalContextFlightsBtn:this._globalContextFlightsBtn,_globalContextMissionsBtn:this._globalContextMissionsBtn,_contextModeStandby:this._contextModeStandby,_contextFlightsView:this._contextFlightsView,_contextMissionsView:this._contextMissionsView,_installationsSearchBtn:this._installationsSearchBtn},installations:n,actions:{getCockpit:()=>this.cockpitView,refreshRadio:()=>this._renderRadioState(t.getUIState()),claimVisualAuthority:()=>{var i,o;return(o=(i=this.shareLinkManager)==null?void 0:i.claimRestoreLane)==null?void 0:o.call(i,"visual")},syncDetection:()=>this._syncContactsDetection(),scheduleLayout:()=>this._scheduleRightPanelLayout(),setPanelCollapsed:(...i)=>this.setPanelCollapsed(...i),showToast:i=>{this._disposed||this._showToast(i)},setClearBusy:i=>{var o;this._disposed||(o=this._clearLayersControl)==null||o.setBusy(i)}}})}_runUserFacingContextAction(...t){var n;return(n=this._contextControls)==null?void 0:n._runUserFacingContextAction(...t)}_waitForContextLayerSettlement(...t){var n;return(n=this._contextControls)==null?void 0:n._waitForContextLayerSettlement(...t)}_syncContextModeButtons(...t){var n;return(n=this._contextControls)==null?void 0:n._syncContextModeButtons(...t)}_initRadioPanel(){var n,i;const{radioLayer:t}=this.services;(n=this._radioControls)==null||n.destroy(),this._radioControls=new Ij({elements:{_cockpitDisplayPanel:this._cockpitDisplayPanel,_cockpitDisplayToggleBtn:this._cockpitDisplayToggleBtn,_cockpitRadioEnableBtn:this._cockpitRadioEnableBtn,_cockpitRadioNextBtn:this._cockpitRadioNextBtn,_cockpitRadioPanel:this._cockpitRadioPanel,_cockpitRadioPlayBtn:this._cockpitRadioPlayBtn,_cockpitRadioPrevBtn:this._cockpitRadioPrevBtn,_cockpitRadioStation:this._cockpitRadioStation,_cockpitRadioToggleBtn:this._cockpitRadioToggleBtn,_cockpitRadioVolume:this._cockpitRadioVolume,_cockpitRadioVolumeValue:this._cockpitRadioVolumeValue,_cockpitUtilityControls:this._cockpitUtilityControls,_contextRadioDetailsBtn:this._contextRadioDetailsBtn,_contextRadioDock:this._contextRadioDock,_contextRadioMini:this._contextRadioMini,_contextRadioMiniCloseBtn:this._contextRadioMiniCloseBtn,_contextRadioMiniEnableBtn:this._contextRadioMiniEnableBtn,_contextRadioMiniNextBtn:this._contextRadioMiniNextBtn,_contextRadioMiniPlayBtn:this._contextRadioMiniPlayBtn,_contextRadioMiniPrevBtn:this._contextRadioMiniPrevBtn,_contextRadioMiniStation:this._contextRadioMiniStation,_contextRadioMiniVolume:this._contextRadioMiniVolume,_contextRadioMiniVolumeValue:this._contextRadioMiniVolumeValue,_contextRadioToggleBtn:this._contextRadioToggleBtn,_radioEnableBtn:this._radioEnableBtn,_radioFilter:this._radioFilter,_radioLayerState:this._radioLayerState,_radioNextBtn:this._radioNextBtn,_radioPanel:this._radioPanel,_radioPlayBtn:this._radioPlayBtn,_radioPlaybackState:this._radioPlaybackState,_radioPrevBtn:this._radioPrevBtn,_radioStationHomepage:this._radioStationHomepage,_radioStationMeta:this._radioStationMeta,_radioStationName:this._radioStationName,_radioStationTags:this._radioStationTags,_radioStopBtn:this._radioStopBtn,_radioTuner:this._radioTuner,_radioTunerBandLabel:this._radioTunerBandLabel,_radioTunerNeedle:this._radioTunerNeedle,_radioTunerSlider:this._radioTunerSlider,_radioTunerStation:this._radioTunerStation,_radioTunerValue:this._radioTunerValue,_radioVolume:this._radioVolume,_radioVolumeValue:this._radioVolumeValue},radio:t,canvas:(i=this.viewer)==null?void 0:i.canvas,actions:{isRegistered:()=>{var o,r;return(r=(o=this._dataManager)==null?void 0:o.layers)==null?void 0:r.has("radio")},isEnabled:()=>{var o;return(o=this._dataManager)==null?void 0:o.isEnabled("radio")},setEnabled:(o,r)=>this._dataManager.setEnabled("radio",o,r),setParams:(o,r)=>{var s;return(s=this._dataManager)==null?void 0:s.setLayerParams("radio",o,r)},getLifecycle:()=>{var o,r;return(r=(o=this._dataManager)==null?void 0:o.getLayerLifecycleState)==null?void 0:r.call(o,"radio")},runUserAction:(...o)=>this._runUserFacingContextAction(...o),setPanelCollapsed:(...o)=>this.setPanelCollapsed(...o),revealStyleParameters:()=>this._revealCockpitStyleParameters(),setSignalCollapsed:o=>{var r;return(r=this.cockpitView)==null?void 0:r.setSignalCollapsed(o)},isCockpitActive:()=>{var o;return(o=this.cockpitView)==null?void 0:o.active},signalUserCollapsed:()=>{var o;return(o=this.cockpitView)==null?void 0:o.signalUserCollapsed},layoutCockpit:()=>{var o;return(o=this.cockpitView)==null?void 0:o.scheduleContextLayout()},preservePanelStateDuringClear:()=>this._preservePanelStateDuringLayerClear,scheduleLayout:()=>this._scheduleRightPanelLayout()}})}_setCockpitDisclosure(...t){var n,i;return(i=(n=this._radioControls)==null?void 0:n._setCockpitDisclosure)==null?void 0:i.call(n,...t)}_setRadioDisclosure(...t){var n,i;return(i=(n=this._radioControls)==null?void 0:n._setRadioDisclosure)==null?void 0:i.call(n,...t)}_syncContextRadioLauncherState(...t){var n,i;return(i=(n=this._radioControls)==null?void 0:n._syncContextRadioLauncherState)==null?void 0:i.call(n,...t)}_renderRadioState(...t){var n,i;return(i=(n=this._radioControls)==null?void 0:n._renderRadioState)==null?void 0:i.call(n,...t)}_runExplicitCctvFocus(t,n){if(this._disposed)return!1;const i=t();return i?this._runExplicitNavigation("camera",()=>n(i)):!1}_initCctvPanel(){var n;const{cctvLayer:t}=this.services;(n=this._cctvControls)==null||n.destroy(),this._cctvControls=new Tj({elements:{_cctvAdjustBtn:this._cctvAdjustBtn,_cctvAutoHopBtn:this._cctvAutoHopBtn,_cctvCalReadout:this._cctvCalReadout,_cctvCalibResetBtn:this._cctvCalibResetBtn,_cctvCalibSaveBtn:this._cctvCalibSaveBtn,_cctvCoverageBtn:this._cctvCoverageBtn,_cctvEnableBtn:this._cctvEnableBtn,_cctvFocusBtn:this._cctvFocusBtn,_cctvFrame:this._cctvFrame,_cctvFrameWrap:this._cctvFrameWrap,_cctvMeta:this._cctvMeta,_cctvNearestBtn:this._cctvNearestBtn,_cctvNextBtn:this._cctvNextBtn,_cctvPanel:this._cctvPanel,_cctvPrevBtn:this._cctvPrevBtn,_cctvProjectionBtn:this._cctvProjectionBtn,_cctvQualityChip:this._cctvQualityChip,_cctvSelect:this._cctvSelect,_cctvSourceBadge:this._cctvSourceBadge,_cctvSummary:this._cctvSummary,_cctvSyncChip:this._cctvSyncChip,_cctvSyncLabel:this._cctvSyncLabel,_cctvSyncProgress:this._cctvSyncProgress},cctv:t,actions:{isEnabled:()=>{var i;return(i=this._dataManager)==null?void 0:i.isEnabled("cctv")},setParams:(i,o)=>{var r;return(r=this._dataManager)==null?void 0:r.setLayerParams("cctv",i,o)},toggleEnabled:(...i)=>this._toggleCctvEnabled(...i),runExplicitFocus:(...i)=>this._runExplicitCctvFocus(...i),setPanelCollapsed:(...i)=>this.setPanelCollapsed(...i),showToast:i=>this._showToast(i),syncViewport:()=>this._syncCctvPanelViewport(),setSplitFlapText:rf}})}async _toggleCctvEnabled(t){var r;const{cctvLayer:n}=this.services;if(this._disposed)return!1;if(!this._dataManager||!((r=this._dataManager.layers)!=null&&r.has("cctv")))return this._showToast("CCTV layer unavailable"),!1;const i=this._dataManager.isEnabled("cctv"),o=typeof t=="boolean"?t:!i;return o===i||await rq({target:o,setEnabled:s=>this._dataManager.setEnabled("cctv",s,{origin:"user"}),readOwnership:()=>{var s,a;return{trackedEntity:(s=this.viewer)==null?void 0:s.trackedEntity,cockpitActive:!!((a=this.cockpitView)!=null&&a.active)}},shouldFocus:()=>{var s,a;return!this._disposed&&this._dataManager.isEnabled("cctv")&&!((a=(s=this._cctvControls)==null?void 0:s.getState())!=null&&a.activeCameraId)},activate:()=>n.focusNearest({focus:!1}),fly:s=>this._runExplicitCctvFocus(()=>s,a=>n.focusCamera(a,1.6))}),!0}_panelStorageKey(t){return this._panelPosition._panelStorageKey(t)}_panelCollapseStorageKey(t){return this._panelPosition._panelCollapseStorageKey(t)}_restorePanelCollapsedState(t,n){return this._panelChrome._restorePanelCollapsedState(...arguments)}_savePanelCollapsedState(t,n){return this._panelChrome._savePanelCollapsedState(...arguments)}_initRightPanelAdaptiveLayout(){return this._panelLayout._initRightPanelAdaptiveLayout()}_scheduleRightPanelLayout(t){return this._panelChrome._scheduleRightPanelLayout(...arguments)}_syncRightPanelAdaptiveLayout(){return this._panelLayout._syncRightPanelAdaptiveLayout()}_initLeftPanelAdaptiveLayout(){return this._panelLayout._initLeftPanelAdaptiveLayout()}_scheduleLeftPanelLayout(t){return this._panelChrome._scheduleLeftPanelLayout(...arguments)}_syncLeftPanelAdaptiveLayout(){return this._panelLayout._syncLeftPanelAdaptiveLayout()}_syncPanelCollapseButton(t){return this._panelChrome._syncPanelCollapseButton(...arguments)}_pinPanelToRight(t){return this._panelPosition._pinPanelToRight(t)}_restorePanelPosition(t,n){return this._panelPosition._restorePanelPosition(t,n)}_clampToViewport(t,n,i){return this._panelPosition._clampToViewport(t,n,i)}_savePanelPosition(t,n){return this._panelPosition._savePanelPosition(t,n)}_promotePanelZ(t){return this._panelPosition._promotePanelZ(t)}_makePanelDraggable(t,n,i){return this._panelPosition._makePanelDraggable(t,n,i)}_buildSharePanelState(){return this._panelChrome._buildSharePanelState(...arguments)}_restorePanelState(t){return this._panelChrome._restorePanelState(...arguments)}setPanelCollapsed(t,n,{explicit:i=!1,restore:o=!1,persist:r=!0,syncShare:s=!0}={}){return this._panelChrome.setPanelCollapsed(...arguments)}toggleCleanView(t){const n=typeof t=="boolean"?t:!document.body.classList.contains("ui-clean-view");document.body.classList.toggle("ui-clean-view",n),this._cleanViewBtn&&this._cleanViewBtn.classList.toggle("active",n),this._scheduleLeftPanelLayout()}setHudVisible(t){var i,o;const n=String(t??"").toLowerCase();return["on","off","auto"].includes(n)?((o=(i=this.shareLinkManager)==null?void 0:i.claimRestoreLane)==null||o.call(i,"visual"),this.hud.setMode(n),this._updateHudButtonState(),this._syncShareState(),{ok:!0,visible:!!this.hud.visible,mode:n,layout:this.hud.getVariant()}):{ok:!1,error:`Unknown HUD visibility mode: ${t}`}}setHudLayout(t){var i,o;const n=String(t??"").toLowerCase();return["tactical","operator","minimal"].includes(n)?((o=(i=this.shareLinkManager)==null?void 0:i.claimRestoreLane)==null||o.call(i,"visual"),this._setHudVariant(n),{ok:!0,layout:this.hud.getVariant(),visible:!!this.hud.visible}):{ok:!1,error:`Unknown HUD layout: ${t}`}}getDetectionState(){return this._visualSettings.getDetectionState(...arguments)}getDetectionDiagnostics(){return this._visualSettings.getDetectionDiagnostics(...arguments)}setDetection({enabled:t,mode:n,densityPct:i,allocationStrategy:o,fadePct:r,outsideOpacityPct:s}={}){return this._visualSettings.setDetection(...arguments)}async setMapStack(t){if(!this.mapStackController)return{ok:!1,error:"Map stack controller unavailable"};const n=this.mapStackController.getStacks(),i=n.find(s=>s.id===t);if(!i)return{ok:!1,error:`Unknown map stack: ${t}`,available:n.map(s=>s.id)};if(!i.available)return{ok:!1,error:`${i.label} requires a Cesium ion token`,activeStack:this.mapStackController.getActiveId()};await this._setMapStack(t);const o=this.mapStackController.getState(),r=o.activeId===t;return{ok:r,activeStack:o.activeId,error:r?null:o.lastError||"Map stack did not switch"}}setBloom({enabled:t,intensityPct:n}={}){return this._visualSettings.setBloom(...arguments)}setSharpen({enabled:t,intensityPct:n}={}){return this._visualSettings.setSharpen(...arguments)}get celestialRingEnabled(){return this._visualSettings.celestialRingEnabled}setCelestialRingEnabled(t,{syncShare:n=!0,focus:i=!1}={}){return this._visualSettings.setCelestialRingEnabled(...arguments)}setOrbit(t){var i,o;const n=!!((i=this.orbitController)!=null&&i.active);return typeof t=="boolean"&&t===n?{ok:!0,orbiting:n}:t===!1?(this._stopOrbit(),{ok:!0,orbiting:!1}):this._currentTarget?(this._toggleOrbit(),{ok:!0,orbiting:!!((o=this.orbitController)!=null&&o.active)}):{ok:!1,orbiting:!1,error:"No active landmark to orbit — fly to a landmark first"}}setCleanView(t){return this.toggleCleanView(t),{ok:!0,cleanView:document.body.classList.contains("ui-clean-view")}}getContextModeState(...t){var n;return(n=this._contextControls)==null?void 0:n.getContextModeState(...t)}setContextMode(...t){var n;return(n=this._contextControls)==null?void 0:n.setContextMode(...t)}getCockpitState(){var a,c,l,u,h,d,f,p,g,_,m,b,C,y,v;const{militaryAwarenessLayer:t}=this.services,n=(a=t.getContextSnapshot)==null?void 0:a.call(t),i=(l=(c=this.cockpitView)==null?void 0:c.readAircraftInfo)==null?void 0:l.call(c),o=!!((u=this.cockpitView)!=null&&u.active),r=!!((d=(h=this.cockpitView)==null?void 0:h.isEntryAllowed)!=null&&d.call(h)),s=!o&&!!(r&&i&&((p=(f=this.viewer)==null?void 0:f.trackedEntity)!=null&&p.position));return{active:o,entryAllowed:s,entryBlockedReason:s||o?null:r?"no-tracked-aircraft":this._contextModeChanging?"contacts-starting":"contacts-inactive",visionMode:((g=this.cockpitView)==null?void 0:g.visionMode)||null,subject:i?{id:i.icao24||i.id||null,layerId:i.layerId||null,callsign:i.callsign||null}:null,navigation:n?{canPrevious:!!((_=n.navigation)!=null&&_.canPrevious),canNext:!!((m=n.navigation)!=null&&m.canNext),canFocus:!!((b=n.navigation)!=null&&b.canFocus)}:null,awareness:n?{radiusM:Number.isFinite(n.radiusM)?n.radiusM:null,subject:n.subject?{id:n.subject.id||null,layerId:n.subject.layerId||null}:null,cohorts:Array.isArray(n.cohorts)?n.cohorts.map(M=>({id:(M==null?void 0:M.id)||null,source:(M==null?void 0:M.source)||null,count:Number.isFinite(M==null?void 0:M.count)?M.count:null,relationship:(M==null?void 0:M.relationship)||null,reason:(M==null?void 0:M.reason)||null,coverage:(M==null?void 0:M.coverage)||null})):[],navigation:n.navigation?{canPrevious:!!n.navigation.canPrevious,canNext:!!n.navigation.canNext,canFocus:!!n.navigation.canFocus}:null}:null,activeTracked:(C=this.cockpitView)!=null&&C.active?!!((y=this.cockpitView)!=null&&y.trackedEntity):!1,activeMapView:!((v=this.cockpitView)!=null&&v.active)&&s}}_retargetCockpitEntryLayer({targetLayer:t,aircraftClass:n,currentTarget:i,selectedTarget:o}){const{militaryAwarenessLayer:r}=this.services;if(!["flights","military"].includes(t))return{ok:!1,error:`Cockpit flies aircraft only — ${t} contacts cannot be entered`};const a=((o==null?void 0:o.layerId)||(i==null?void 0:i.layerId)||null)===t;if(a&&!n)return{ok:!0,retargeted:!1};if(r!=null&&r.navigateNext?!!r.navigateNext({targetLayer:t,aircraftClass:n,origin:"voice"}):!1)return{ok:!0,retargeted:!0};if(a)return{ok:!0,retargeted:!1};const l=t==="military"?"military":"civilian";return{ok:!1,error:`No ${n?`${n} `:""}${l} contact is available to enter — track one first, or say "next ${l}"`}}controlCockpit(t,{notificationToken:n=null,targetLayer:i=null,aircraftClass:o=null,selectedTarget:r=null,rollbackTarget:s=void 0}={}){var u,h;const{flightsLayer:a,militaryFlightsLayer:c}=this.services,l=String(t||"").toLowerCase();if(!this.cockpitView)return{ok:!1,action:"control_cockpit",error:"Cockpit controller unavailable",state:this.getCockpitState()};if(l==="status")return{ok:!0,action:"control_cockpit",state:this.getCockpitState(),notificationToken:n||null};if(l==="enter"){if(!((h=(u=this.cockpitView).isEntryAllowed)!=null&&h.call(u)))return{ok:!1,action:"control_cockpit",error:this._contextModeChanging?"Contacts is still starting up — try Cockpit again in a moment":'Contacts must be active to enter Cockpit — say "open contacts" first',state:this.getCockpitState()};let d=this.getAircraftTrackingTarget();const f=_=>(_==null?void 0:_.layerId)==="military"?c:(_==null?void 0:_.layerId)==="flights"?a:null;if(i){const _=this._retargetCockpitEntryLayer({targetLayer:i,aircraftClass:o,currentTarget:d,selectedTarget:r});if(!_.ok)return{ok:!1,action:"control_cockpit",error:_.error,state:this.getCockpitState()};_.retargeted&&(r=null,s=s===void 0?d:s,d=this.getAircraftTrackingTarget())}const p=(r==null?void 0:r.layerId)==="military"?c:(r==null?void 0:r.layerId)==="flights"?a:null,g=tq({cockpitView:this.cockpitView,selectedLayer:p,selectedTarget:r,currentLayer:f(d),rollbackLayer:f(s===void 0?d:s),rollbackTarget:s,selectionOrigin:"voice"});return{ok:g.entered,action:"control_cockpit",state:this.getCockpitState(),error:g.error}}if(l==="exit"){const d=!!this.cockpitView.exit();return{ok:d,action:"control_cockpit",state:this.getCockpitState(),error:d?null:"Cockpit was already inactive"}}if(l==="next"||l==="previous"){const d=this.cockpitView.navigateContext(l==="next"?1:-1,{targetLayer:i,aircraftClass:o,origin:"voice"});return{ok:d,action:"control_cockpit",state:this.getCockpitState(),error:d?null:"No further context target was available"}}return{ok:!1,action:"control_cockpit",error:`Unknown cockpit action: ${t}`,state:this.getCockpitState()}}getControlState(){var t,n,i,o,r,s,a;return{style:this.activeStyle||"normal",mapStack:((n=(t=this.mapStackController)==null?void 0:t.getActiveId)==null?void 0:n.call(t))||null,hud:{visible:!!((i=this.hud)!=null&&i.visible),layout:((r=(o=this.hud)==null?void 0:o.getVariant)==null?void 0:r.call(o))||null},detection:this.getDetectionState(),bloom:{enabled:!!this.bloomEnabled,intensityPct:this._bloomSlider?parseInt(this._bloomSlider.value,10):null},sharpen:{enabled:!!this.sharpenEnabled,intensityPct:this._sharpenSlider?parseInt(this._sharpenSlider.value,10):null},celestialRing:{enabled:this.celestialRingEnabled,visible:!!((s=this.celestialRing)!=null&&s.visible)},orbiting:!!((a=this.orbitController)!=null&&a.active),models3d:{enabled:!!this._models3dEnabled,mode:this._models3dMode||"proximity"},recording:!!this._recording._recordingMode,cleanView:document.body.classList.contains("ui-clean-view")}}getCameraState(){const t=this.viewer.camera.positionCartographic;return t?{lat:Cesium.Math.toDegrees(t.latitude),lon:Cesium.Math.toDegrees(t.longitude),alt:t.height,heading:Cesium.Math.toDegrees(this.viewer.camera.heading),pitch:Cesium.Math.toDegrees(this.viewer.camera.pitch),roll:Cesium.Math.toDegrees(this.viewer.camera.roll)}:null}applyCameraState(t,n=2.8){t&&this.viewer.camera.flyTo({destination:Cesium.Cartesian3.fromDegrees(t.lon,t.lat,t.alt),orientation:{heading:Cesium.Math.toRadians(t.heading||0),pitch:Cesium.Math.toRadians(t.pitch||-35),roll:Cesium.Math.toRadians(t.roll||0)},duration:Math.max(.2,n||0),easingFunction:Cesium.EasingFunction.CUBIC_IN_OUT})}getVisualState(){return this._visualSettings.getVisualState(...arguments)}async applyVisualState(t={},{isCurrent:n=null}={}){return this._visualSettings.applyVisualState(...arguments)}_initRecordingOverlay(){return this._recording._initRecordingOverlay()}applyCinematicPreset(t={}){return this._visualSettings.applyCinematicPreset(...arguments)}setRecordingMode(t,n){return this._recording.setRecordingMode(t,n)}_updateSliderPanel(t,{reveal:n=!1}={}){return this._visualSettings._updateSliderPanel(...arguments)}_revealStyleParameters(){return this._visualSettings._revealStyleParameters(...arguments)}setStyle(t,{applyPreset:n=!0,revealParameters:i=n,restore:o=!1}={}){return this._visualSettings.setStyle(...arguments)}_startTransition(t,n,i){return this._visualSettings._startTransition(...arguments)}_updateGlobalLoadingFeedback(t){return this._feedback._updateGlobalLoadingFeedback(t)}_showGlobalStatusNotice(t,n){return this._feedback._showGlobalStatusNotice(t,n)}_startAnimationLoop(){this._visualEffects.startAnimationLoop()}_startTrafficChipTicker(){return this._feedback._startTrafficChipTicker()}_armLoadingFeedbackTicker(){return this._feedback._armLoadingFeedbackTicker()}_stopLoadingFeedbackTicker(){return this._feedback._stopLoadingFeedbackTicker()}subscribeLocationSearch(t,n){return this._locationState.subscribe(t,n)}_handleLocationSearchState(t,n){this._disposed||!n||(n.type==="started"?this._activeLocationSearchGeneration=n.generation:n.type==="found"?(this._searchedLocationLabel=t.destination.label||t.query,this._setActiveLocation(null),this._currentPoi=null,this._collapsePOIRow(),this._updateLocationMiniStatus()):n.type==="missing"?this._showToast("Location not found"):n.type==="failed"?this._showToast("Search failed"):n.type==="settled"?this._settleLocationSearchUi(n.generation):n.type==="reset"&&this._activeLocationSearchGeneration!==null&&this._settleLocationSearchUi(this._activeLocationSearchGeneration))}_initLocationBar(){var o,r,s;const{CITY_POIS:t,searchAndFlyTo:n,LocationSearch:i}=this.services;(o=this._locationControls)==null||o.destroy(),(r=this._locationLookupUnsubscribe)==null||r.call(this),(s=this._locationLookup)==null||s.destroy(),this._locationLookup=new i({input:this._locationSearch,begin:()=>this._beginDeferredNavigation("location"),isCurrent:a=>!this._disposed&&a===this._navigationGeneration,beforeFly:a=>this._reassertNavigationHandoff(a),search:(a,c)=>n(this.viewer,a,{placeSearch:this.placeSearch,...c}),onError:a=>console.error("[Search] Geocoding failed:",a)}),this._locationLookupUnsubscribe=this._locationLookup.subscribe(({initial:a,change:c})=>{this._locationState.publish(a?{type:"reset"}:c)}),this._locationControls=new xj({elements:{pills:this._locationPills,poiRow:this._poiRow,divider:this._locationBarDivider,search:this._locationSearch,searchToggle:this._searchToggle,resetButtons:[this._resetGlobeBtn,this._cockpitResetGlobeBtn],statusCity:this._locationMiniCity,statusPoi:this._locationMiniPoi},cities:t,getExpandedCity:()=>this._expandedCityId,onCity:a=>this._onCityPillClick(a),onPoi:(a,c)=>this._onPoiClick(a,c),onSearch:a=>this._locationLookup.run(a),onReset:()=>this.resetToGlobeView()})}_beginWorldJumpTransition(){var i;const{suspendDetection:t,trafficLayer:n}=this.services;clearTimeout(this._trafficTransitionTimer),(i=n.beginWorldJump)==null||i.call(n),t("intercity")}_endWorldJumpTransition(){var i;const{resumeDetection:t,trafficLayer:n}=this.services;clearTimeout(this._trafficTransitionTimer),(i=n.endWorldJump)==null||i.call(n),t(),this._updateTrafficSyncChip(!0)}_flyWithTransition(t,n){return this._runExplicitNavigation("location",()=>{if(!t)return n({});let i=!1;const o=()=>{i||(i=!0,this._endWorldJumpTransition())},r=n({onStart:()=>this._beginWorldJumpTransition(),onComplete:o});return this._trafficTransitionTimer=window.setTimeout(o,5200),r})}beginLocationNavigation(){var t;return this._stampNavigation(),(t=this.cockpitView)==null||t.exit({restoreTracking:!1}),this._releaseFollowCamera({preserveVesselSelection:!1})}_onCityPillClick(t){const{CITY_POIS:n,flyToPresetLocation:i}=this.services;if(this._expandedCityId===t){this._collapsePOIRow();return}const o=this._activeLocationId&&this._activeLocationId!==t,r=this._flyWithTransition(!!o,s=>i(this.viewer,t,s));r!==!1&&(this._expandPOIRow(t),this._setActiveLocation(t),this._activePoiIndex=0,this._updatePoiHighlight(),r&&(this._currentTarget=r.targetPosition,this._currentPoi=n[t].pois[0]),this._updateLocationMiniStatus())}_onPoiClick(t,n){const{CITY_POIS:i,flyToPOI:o}=this.services,r=this._activeLocationId&&this._activeLocationId!==t,s=this._flyWithTransition(!!r,a=>o(this.viewer,t,n,a));s!==!1&&(this._setActiveLocation(t),this._activePoiIndex=n,this._updatePoiHighlight(),s&&(this._currentTarget=s.targetPosition,this._currentPoi=i[t].pois[n]),this._updateLocationMiniStatus())}_expandPOIRow(t){const{CITY_POIS:n}=this.services;n[t]&&(this._expandedCityId=t,this._locationControls.showPois(t))}_collapsePOIRow(){this._expandedCityId=null,this._activePoiIndex=null,this._locationControls.hidePois()}_updatePoiHighlight(){this._locationControls.highlightPoi(this._activePoiIndex)}clearSearchedLocation(){this._searchedLocationLabel!==null&&(this._searchedLocationLabel=null,this._updateLocationMiniStatus())}_setActiveLocation(t){var n;this._activeLocationId=t,t&&(this._searchedLocationLabel=null),(n=this._locationControls)==null||n.highlightCity(t),this._updateLocationMiniStatus()}_updateLocationMiniStatus(){var n;const{CITY_POIS:t}=this.services;(n=this._locationControls)==null||n.renderStatus({city:this._activeLocationId?t[this._activeLocationId]:null,currentPoi:this._currentPoi,searchedLabel:this._searchedLocationLabel})}_updateStyleMiniStatus(t=this.activeStyle){return this._visualSettings._updateStyleMiniStatus(...arguments)}_initOrbit(){this._orbitIndicator=this._locationControls.createOrbitIndicator()}_toggleOrbit(){var n,i;if(!this._currentTarget){this._showToast("Fly to a POI first");return}const t=this.orbitController.toggle(this._currentTarget,{radius:((n=this._currentPoi)==null?void 0:n.alt)||500,pitch:((i=this._currentPoi)==null?void 0:i.pitch)||-30});this._orbitIndicator.classList.toggle("active",t)}_stopOrbit(){this.orbitController.active&&(this.orbitController.stop(),this._orbitIndicator.classList.remove("active"))}_initClearSelectedLayersButton(){var t;this._clearSelectedLayersBtn&&((t=this._clearLayersControl)==null||t.destroy(),this._clearLayersControl=Bj(this._clearSelectedLayersBtn,()=>this.clearSelectedLayers()))}_initCameraOrientationControls(){var t;(t=this._cameraOrientationControls)==null||t.destroy(),this._cameraOrientationControls=jj({viewer:this.viewer,elements:{tiltButton:this._tiltMapBtn,northButton:this._northUpBtn},runNavigation:(n,i)=>this._navigation.runOrientation(n,i),showToast:n=>this._showToast(n)})}clearSelectedLayers(...t){var n;return(n=this._contextControls)==null?void 0:n.clearSelectedLayers(...t)}resetToGlobeView(){var _,m,b,C,y,v,M,w,E;const{GLOBE_VIEW:t,flyToGlobeView:n,interruptCameraMotion:i,flightsLayer:o,militaryFlightsLayer:r,satellitesLayer:s,aisLiveVesselsLayer:a,militaryAwarenessLayer:c,rocketLaunchesLayer:l}=this.services;if(this._globeResetPromise)return this._globeResetPromise;this._stampNavigation(),i("reset-globe"),this._stopOrbit(),(_=this.cockpitView)==null||_.exit({restoreTracking:!1});try{(m=c.releaseCameraOwnership)==null||m.call(c,{origin:"tool"})}catch{try{(b=o.stopTracking)==null||b.call(o,{origin:"tool"})}catch{}try{(C=r.stopTracking)==null||C.call(r,{origin:"tool"})}catch{}try{(y=a.clearSelection)==null||y.call(a)}catch{}}try{(v=s.stopTracking)==null||v.call(s,{origin:"tool"})}catch{}try{(M=l.releaseCameraOwnership)==null||M.call(l)}catch{}this.viewer.trackedEntity=void 0,this.viewer.camera.cancelFlight(),this.viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY),this._beginWorldJumpTransition();let u;const h=new Promise(k=>{u=k});this._globeResetPromise=h;let d=!1,f=null;const p=(k=!1)=>{var R,S;if(d)return;d=!0,clearTimeout(f),this._endWorldJumpTransition();const T=this.viewer.camera.positionCartographic,I={ok:!k,action:"zoom_to_globe",cancelled:k,heightKm:Math.round(t.heightM/1e3),centeredOn:{latitude:Number(Cesium.Math.toDegrees(T.latitude).toFixed(2)),longitude:Number(Cesium.Math.toDegrees(T.longitude).toFixed(2))}};(R=this._resetGlobeBtn)==null||R.setAttribute("aria-label","Reset to full globe view"),(S=this._cockpitResetGlobeBtn)==null||S.setAttribute("aria-label","Reset cockpit to full globe view"),this._globeResetPromise=null,u(I)};return f=window.setTimeout(()=>{var T;const k=(T=this.viewer.camera.positionCartographic)==null?void 0:T.height;p(!Number.isFinite(k)||Math.abs(k-t.heightM)>1e3)},4200),(w=this._resetGlobeBtn)==null||w.setAttribute("aria-label","Resetting to full globe view"),(E=this._cockpitResetGlobeBtn)==null||E.setAttribute("aria-label","Resetting cockpit to full globe view"),n(this.viewer,{onComplete:()=>p(!1),onCancel:()=>p(!0)})||p(!0),h}_initShareButton(){this._lifetime.listen(this._shareBtn,"click",async()=>{const t=await this.shareLinkManager.copyLink();this._showToast(t?"Link copied!":"Copy failed")})}_showToast(t){return this._feedback._showToast(t)}_setModels3dParams(t,{origin:n="user"}={}){var i,o;(i=this._dataManager)==null||i.setLayerParams("flights",t,{origin:n}),(o=this._dataManager)==null||o.setLayerParams("military",t,{origin:n})}_syncModels3dFromLayerState(t){var i,o;const n=(i=t==null?void 0:t.options)==null?void 0:i.flights;if(n){this._models3dEnabled=n.models3d===!0,this._models3dMode=n.models3dMode==="all"?"all":"proximity",this._syncModels3dButtonState(),(o=this._models3dModeRow)==null||o.classList.toggle("visible",this._models3dEnabled);for(const r of this._models3dModeBtns||[]){if(!r)continue;const s=r.dataset.mode===this._models3dMode;r.classList.toggle("active",s),r.setAttribute("aria-checked",String(s))}this._layoutRightPanels()}}_syncModels3dModeRow(){this._models3dModeRow&&this._models3dModeRow.classList.toggle("visible",this._models3dEnabled),this._layoutRightPanels()}_initModels3dToggle(){this._models3dBtn&&(this._syncModels3dButtonState(),this._syncModels3dModeRow())}_setModels3dEnabled(t){this._models3dEnabled=!!t,this._setModels3dParams({models3d:this._models3dEnabled}),this._syncModels3dButtonState()}_setModels3dMode(t){const n=t==="all"?"all":"proximity";this._models3dMode=n,this._setModels3dParams({models3dMode:n});for(const i of this._models3dModeBtns){if(!i)continue;const o=i.dataset.mode===n;i.classList.toggle("active",o),i.setAttribute("aria-checked",String(o))}this._syncModels3dButtonState()}_syncModels3dButtonState(){var t,n;(t=this._models3dBtn)==null||t.classList.toggle("active",this._models3dEnabled),(n=this._models3dBtn)==null||n.setAttribute("aria-pressed",String(this._models3dEnabled))}_initHUDToggle(){this._hudLayoutSelect&&(this._hudLayoutSelect.value="tactical"),this._setHudVariant("tactical"),this.hud.setMode("on"),this._updateHudButtonState(),this._lifetime.listen(this._cockpitDisplayToggleBtn,"click",()=>{var n;const t=this._cockpitDisplayToggleBtn.getAttribute("aria-expanded")==="true";(n=this._setCockpitDisclosure)==null||n.call(this,"display",!t)}),this._initCockpitDisplayPortal()}_initCockpitDisplayPortal(){var t,n,i,o;(t=this._cockpitDisplayPortal)==null||t.destroy(),this._cockpitDisplayPortal=new S6({standardPanel:this._ppToggles,cockpitPanel:this._cockpitDisplayPanel,groups:[["hud",(n=this._hudBtn)==null?void 0:n.closest(".pp-toggle-group")],["detection",(i=this._detectionBtn)==null?void 0:i.closest(".pp-toggle-group")],["parameters",this._sliderPanel],["models3d",(o=this._models3dBtn)==null?void 0:o.closest(".pp-toggle-group")]],layout:()=>{var r;this._layoutRightPanels(),(r=this.cockpitView)==null||r.scheduleContextLayout()}})}_setCockpitDisplayPortalActive(t){var n;(n=this._cockpitDisplayPortal)==null||n.setActive(t)}get _cockpitDisplayPortalActive(){var t;return((t=this._cockpitDisplayPortal)==null?void 0:t.active)??!1}get _displayPortalScrollRestoreOwner(){var t;return((t=this._cockpitDisplayPortal)==null?void 0:t.restoreOwner)??null}get _standardDisplayScrollTop(){var t;return((t=this._cockpitDisplayPortal)==null?void 0:t.standardScrollTop)??0}_updateHudButtonState(){return this._visualSettings._updateHudButtonState(...arguments)}_updateDetectionButton(t){return this._visualSettings._updateDetectionButton(...arguments)}_layoutRightPanels(){return this._panelChrome._layoutRightPanels(...arguments)}_syncCctvPanelViewport(){if(!this._cctvPanel)return;const t=this._cctvPanel.querySelector(".cctv-panel-inner");this._lifetime.frame(()=>{var o;if(((o=this._cctvPanel.parentElement)==null?void 0:o.id)==="right-context-rail"){this._cctvPanel.style.maxHeight="",t&&(t.style.maxHeight=""),this._scheduleRightPanelLayout();return}const n=this._cctvPanel.getBoundingClientRect(),i=Math.max(190,Math.floor(window.innerHeight-n.top-12));this._cctvPanel.style.maxHeight=`${i}px`,t&&(t.style.maxHeight=`${i}px`)})}get hasShareState(){return!!this._hasShareState}get initialRestorePromise(){return this._initialShareRestorePromise||Promise.resolve({status:"not-requested"})}_settleInitialShareRestore(t){return this._shareRestoration._settleInitialShareRestore(...arguments)}async dispose(){var o,r,s,a,c,l,u,h,d,f,p,g,_,m,b,C,y,v,M,w,E,k,T,I;const{destroyTrackedReadout:t,destroyWorldOverlay:n,destroyDetection:i}=this.services;this._disposed||(this._shareRestoration.destroy(),this._feedback._globalStatusNotice=null,this._globalLoadingStatus&&(this._globalLoadingStatus.hidden=!0),this._disposed=!0,this._navigation.stop(),this._shareState.destroy(),this._locationState.destroy(),(o=this._locationLookupUnsubscribe)==null||o.call(this),this._locationLookupUnsubscribe=null,this._lifetime.destroy(),this._recording.destroy(),this._panelChrome.destroy(),this._feedback.destroy(),(r=this._applicationShortcuts)==null||r.destroy(),(s=this._displayControls)==null||s.destroy(),(a=this._frameRateMonitor)==null||a.destroy(),(c=this._mapSourceControls)==null||c.destroy(),(l=this._cameraOrientationControls)==null||l.destroy(),(u=this._clearLayersControl)==null||u.destroy(),(h=this._locationControls)==null||h.destroy(),(d=this._cctvControls)==null||d.destroy(),(f=this._radioControls)==null||f.destroy(),(p=this.cockpitView)==null||p.stop(),(g=this._cockpitDisplayPortal)==null||g.stop(),this._visualSettings.stop(),(_=this._locationLookup)==null||_.destroy(),(m=this.shareLinkManager)==null||m.destroy(),this._awarenessSelectedHandler&&(window.removeEventListener("gev:awareness-subject-selected",this._awarenessSelectedHandler),this._awarenessSelectedHandler=null),this._awarenessClearedHandler&&(window.removeEventListener("gev:awareness-subject-cleared",this._awarenessClearedHandler),this._awarenessClearedHandler=null),this._contextControls.stop(),this._navigation.destroy(),(b=this._removeCctvRequestFocusListener)==null||b.call(this),this._removeCctvRequestFocusListener=null,this._cctvRequestFocusHandler=null,(C=this._removeWorldRequestFocusListener)==null||C.call(this),this._removeWorldRequestFocusListener=null,this._worldRequestFocusHandler=null,(y=this._navigationOwnerChangedRemover)==null||y.call(this),this._navigationOwnerChangedRemover=null,(v=this._removeNavigationAuthorityListener)==null||v.call(this),this._removeNavigationAuthorityListener=null,await this._contextControls.restoreForDisposal(),this._visualSettings.releaseIrBoost(),(M=this.cockpitView)==null||M.dispose(),(w=this._cockpitDisplayPortal)==null||w.destroy(),this._cockpitDisplayPortal=null,this._contextControls.disconnect(),(E=this._dataManagerUnsubscribe)==null||E.call(this),this._dataManagerUnsubscribe=null,(T=(k=this._directionsShellModule)==null?void 0:k.attachShellServices)==null||T.call(k,null),this._directionsShellModule=null,this._windowResizeHandler&&(window.removeEventListener("resize",this._windowResizeHandler),this._windowResizeHandler=null),t(),i(),n(),(I=this.celestialRing)==null||I.destroy(),this._visualSettings.destroy())}};const Xa=65,Yt=73,vn=79;function aq(e,t){if(t=typeof t=="number"?t:5,!Array.isArray(e))throw new TypeError("forward did not receive an array");if(typeof e[0]=="string"||typeof e[1]=="string")throw new TypeError("forward received an array of strings, but it only accepts an array of numbers.");const[n,i]=e;if(n<-180||n>180)throw new TypeError("forward received an invalid longitude of "+n);if(i<-90||i>90)throw new TypeError("forward received an invalid latitude of "+i);if(i<-80||i>84)throw new TypeError(`forward received a latitude of ${i}, but this library does not support conversions of points in polar regions below 80°S and above 84°N`);return(function(o,r){const s="00000"+o.easting,a="00000"+o.northing;return o.zoneNumber+o.zoneLetter+(function(c,l,u){const h=cq(u),d=Math.floor(c/1e5),f=Math.floor(l/1e5)%20;return(function(p,g,_){const m=_-1,b="AJSAJS".charCodeAt(m),C="AFAFAF".charCodeAt(m);let y=b+p-1,v=C+g,M=!1;return y>90&&(y=y-90+Xa-1,M=!0),(y===Yt||bYt||(y>Yt||bvn||(y>vn||b90&&(y=y-90+Xa-1),v>86?(v=v-86+Xa-1,M=!0):M=!1,(v===Yt||CYt||(v>Yt||Cvn||(v>vn||C86&&(v=v-86+Xa-1),String.fromCharCode(y)+String.fromCharCode(v)})(d,f,h)})(o.easting,o.northing,o.zoneNumber)+s.substr(s.length-5,r)+a.substr(a.length-5,r)})((function(o){const r=o.lat,s=o.lon,a=6378137,c=bd(r),l=bd(s);let u;u=Math.floor((s+180)/6)+1,s===180&&(u=60),r>=56&&r<64&&s>=3&&s<12&&(u=32),r>=72&&r<84&&(s>=0&&s<9?u=31:s>=9&&s<21?u=33:s>=21&&s<33?u=35:s>=33&&s<42&&(u=37));const h=bd(6*(u-1)-180+3),d=a/Math.sqrt(1-.00669438*Math.sin(c)*Math.sin(c)),f=Math.tan(c)*Math.tan(c),p=.006739496752268451*Math.cos(c)*Math.cos(c),g=Math.cos(c)*(l-h),_=a*(.9983242984503243*c-.002514607064228144*Math.sin(2*c)+2639046602129982e-21*Math.sin(4*c)-3418046101696858e-24*Math.sin(6*c)),m=.9996*d*(g+(1-f+p)*g*g*g/6+(5-18*f+f*f+72*p-.39089081163157013)*g*g*g*g*g/120)+5e5;let b=.9996*(_+d*Math.tan(c)*(g*g/2+(5-f+9*p+4*p*p)*g*g*g*g/24+(61-58*f+f*f+600*p-2.2240339282485886)*g*g*g*g*g*g/720));return r<0&&(b+=1e7),{northing:Math.trunc(b),easting:Math.trunc(m),zoneNumber:u,zoneLetter:lq(r)}})({lat:i,lon:n}),t)}function bd(e){return e*(Math.PI/180)}function lq(e){return e<=84&&e>=72?"X":e<72&&e>=-80?"CDEFGHJKLMNPQRSTUVWX"[Math.floor((e- -80)/8)]:e>84||e<-80?"Z":void 0}function cq(e){let t=e%6;return t===0&&(t=6),t}const uq=150;function D0(e,t,n){return`${Math.abs(e).toFixed(2)}${e>=0?t:n}`}function dq(e,t,n){const i=Number(e==null?void 0:e.distKm);return e&&Number.isFinite(i)&&i<=uq?`NEAR ${String(e.poi).toUpperCase()} (${String(e.city).toUpperCase()}) ${Math.round(i)}KM`:`SECTOR ${D0(t,"N","S")} ${D0(n,"E","W")}`}function Lr(e,t,{fallbackEnabled:n=!1}={}){var r,s;let i=null;try{i=((r=e==null?void 0:e.getLayerLifecycleState)==null?void 0:r.call(e,t))||null}catch{i=null}if(i){const a=!!i.enabled;return{enabled:a,lifecycleState:i.lifecycleState||(a?"enabled":"disabled"),lifecycleUncertain:!!(i.uncertain??i.lifecycleUncertain)}}let o=!!n;try{const a=(s=e==null?void 0:e.isEnabled)==null?void 0:s.call(e,t);typeof a=="boolean"&&(o=a)}catch{}return{enabled:o,lifecycleState:o?"enabled":"disabled",lifecycleUncertain:!1}}const Cd={flights:{numeric:["altitudeM","speedMps","verticalRateMps"],text:["callsign","icao24","originCountry","operator","routeOrigin","routeDestination","aircraftClass"],flags:["military","onGround"]},military:{numeric:["altitudeM","speedMps","verticalRateMps"],text:["callsign","icao24","originCountry","operator","aircraftClass"],flags:["military","onGround"]},"ais-live-vessels":{numeric:["speedKts","courseDeg"],text:["name","mmsi","shipType","destination","navStatus"],flags:[]},"local-firms":{numeric:["frp"],text:["confidence","satellite"],flags:[]},earthquakes:{numeric:["magnitude","depthKm"],text:["place"],flags:[]}},hq=6371;function hT(e,t,n,i){const o=Math.PI/180,r=(n-e)*o,s=(i-t)*o,a=Math.sin(r/2)**2+Math.cos(e*o)*Math.cos(n*o)*Math.sin(s/2)**2;return 2*hq*Math.asin(Math.min(1,Math.sqrt(a)))}function fq(e,t){const{field:n,op:i,value:o}=t||{};return!n||!i?e:e.filter(r=>{const s=r[n];if(s==null)return!1;switch(i){case"gt":return Number(s)>Number(o);case"gte":return Number(s)>=Number(o);case"lt":return Number(s)Number.isFinite(i.lat)&&Number.isFinite(i.lon)&&DM(n.ring,i.lat,i.lon));if(t.kind==="radius"||t.kind==="view"){const i=n==null?void 0:n.center,o=n==null?void 0:n.km;return!i||!Number.isFinite(o)?e:e.filter(r=>Number.isFinite(r.lat)&&Number.isFinite(r.lon)&&hT(i.lat,i.lon,r.lat,r.lon)<=o)}return e}function pq(e,t){const n={count:e.length};if(t&&e.length){const i=e.map(o=>Number(o[t])).filter(Number.isFinite);i.length&&(n[`${t}Min`]=Math.min(...i),n[`${t}Max`]=Math.max(...i))}return n}function O0(e){let t=null;async function n(i={}){var _;const o=i.followUp&&t?null:Array.isArray(i.layers)&&i.layers.length?i.layers:["flights"];let r,s;if(o===null)r=t.items.slice(),s=t.coverage.layersQueried;else{r=[],s=[];const m=o.filter(b=>!Cd[b]);if(m.length)return{ok:!1,error:`I can't query ${m.join(", ")} yet — supported layers: ${Object.keys(Cd).join(", ")}.`,coverage:{layersQueried:[],scope:"unsupported-layer"}};for(const b of o){if(!Cd[b])continue;const C=e.getRecords(b)||[];s.push({layerKey:b,records:C.length});for(const y of C)r.push({layerKey:b,...y})}}let a=null,c="anywhere",l="anywhere in the loaded data";const u=i.scope||{kind:"view"};if(u.kind==="region"&&u.name){const m=await e.resolveRegionRing(u.name);if(!(m!=null&&m.ring))return{ok:!1,error:`I couldn't resolve a boundary for "${u.name}" — try a state, country, or a named natural region.`,coverage:{layersQueried:s,scope:`region:${u.name}:unresolved`}};a=m,c=`region:${m.name}`,l=`over ${m.name}`}else if(u.kind==="radius"){const m=u.center&&Number.isFinite(u.center.lat)?u.center:null,b=m?null:((_=e.getContextSubject)==null?void 0:_.call(e))||null,C=e.getViewContext(),y=Number.isFinite(b==null?void 0:b.lat)&&Number.isFinite(b==null?void 0:b.lon)?{lat:b.lat,lon:b.lon}:null;a={center:m||y||{lat:C.lat,lon:C.lon},km:Number(u.km)||100},y&&(a.centeredOn=b.label||null),c=a.centeredOn?`radius:${a.km}km@${a.centeredOn}`:`radius:${a.km}km`,l=a.centeredOn?`within ${a.km} km of ${a.centeredOn}`:`within ${a.km} km`}else if(u.kind==="view"){const m=e.getViewContext();a={center:{lat:m.lat,lon:m.lon},km:m.viewRadiusKm},c=`view:${Math.round(m.viewRadiusKm)}km`,l="in view"}else c="anywhere",l="anywhere in the loaded data";let h=mq(r,u,a);for(const m of i.filters||[])h=fq(h,m);const d=i.sortBy||null;if(d==="distance"){const m=(a==null?void 0:a.center)||e.getViewContext();for(const b of h)b.distanceKm=Number.isFinite(b.lat)&&Number.isFinite(b.lon)?Math.round(hT(m.lat,m.lon,b.lat,b.lon)*10)/10:null}if(d){const m=i.sortDir==="asc"?1:-1;h.sort((b,C)=>(Number(b[d])-Number(C[d]))*m||String(b.id).localeCompare(String(C.id))),d==="distance"&&h.sort((b,C)=>(b.distanceKm??1e9)-(C.distanceKm??1e9))}const f=Math.max(1,Math.min(50,Number(i.limit)||10)),p=h.slice(0,f),g={ok:!0,count:h.length,items:p,truncated:h.length>p.length,summary:pq(h,d&&d!=="distance"?d:null),scopeLabel:l,coverage:{layersQueried:s,scope:c,followUp:!!(i.followUp&&t),note:"client-side data only — answers cover what the enabled layers currently hold"},...a!=null&&a.centeredOn?{centeredOn:a.centeredOn}:{}};return t={items:h,coverage:g.coverage},g}return{query:n,reset(){t=null},hasMemory(){return!!t}}}const gq=new Set(["normal","retro","surveillance","thermal","anime","noir","snow"]),_q=new Map([["data","data-panel"],["data layers","data-panel"],["layers","data-panel"],["layer menu","data-panel"],["data layer menu","data-panel"],["locations","location-bar"],["location","location-bar"],["styles","control-panel"],["filters","control-panel"],["visual styles","control-panel"],["cctv","cctv-panel"],["cameras","cctv-panel"],["radio","radio-panel"],["internet radio","radio-panel"],["radio stations","radio-panel"],["context","global-context-panel"],["context panel","global-context-panel"],["global context","global-context-panel"],["right context","global-context-panel"],["context right panel","global-context-panel"],["scenes","scene-panel"],["scene","scene-panel"],["post processing","pp-toggles"],["hud controls","pp-toggles"],["map stack","control-panel"],["stack","control-panel"],["basemap","control-panel"],["map sources","control-panel"],["sources","control-panel"]]),bq=new Set(["data-panel","location-bar","control-panel","cctv-panel","radio-panel","global-context-panel","scene-panel","pp-toggles"]),Cq=new Map([["off","off"],["none","off"],["clear","off"],["contacts","flights"],["contact","flights"],["flights","flights"],["space missions","space-missions"],["space-mission","space-missions"],["space mission","space-missions"],["space-missions","space-missions"],["missions","space-missions"]]),yq=Object.freeze([{field:"mode",emptyAs:"off"},{field:"entering",emptyAs:null},{field:"priorMode",emptyAs:null}]),vq=Object.freeze(["context","contextRollback"]);function bi(e){if(!e||typeof e!="object")return e;let t=e;const n=()=>(t===e&&(t={...e}),t);for(const{field:i,emptyAs:o}of yq){if(!(i in e))continue;const r=e[i]??null,s=n();s[i]=lT(r,{emptyAs:o}),s[`${i}Internal`]=r}for(const i of vq){const o=e[i];if(!o||typeof o!="object")continue;const r=bi(o);r!==o&&(n()[i]=r)}return t}const B0=new Map([["next","next"],["previous","previous"],["prev","previous"],["enter","enter"],["exit","exit"],["status","status"],["state","status"],["next military","next"],["next military aircraft","next"],["next helicopter","next"],["next closest","next"],["next closest helicopter","next"],["next closest military","next"],["go to next","next"]]),Mq=new Set(["flights","military","ais-live-vessels","military-installations"]),V0=new Map([["flights","flights"],["planes","flights"],["aircraft","flights"],["military","military"],["military flights","military"],["earthquakes","earthquakes"],["quakes","earthquakes"],["satellites","satellites"],["space mission","rocket-launches"],["space missions","rocket-launches"],["missions","rocket-launches"],["traffic","traffic"],["street traffic","traffic"],["cctv","cctv"],["cameras","cctv"],["radio","radio"],["internet radio","radio"],["radio stations","radio"],["bikeshare","bikeshare"],["bikes","bikeshare"],["ais","ais-live-vessels"],["ships","ais-live-vessels"],["vessels","ais-live-vessels"],["live vessels","ais-live-vessels"],["datacenters","local-datacenters"],["data centers","local-datacenters"],["data centres","local-datacenters"],["dams","local-dams"],["submarine cables","telegeography-submarine-cables"],["cables","telegeography-submarine-cables"],["telegeography","telegeography-submarine-cables"],["firms","local-firms"],["fires","local-firms"],["active fires","local-firms"],["alpr","alpr-cameras"],["alpr cameras","alpr-cameras"],["flock cameras","alpr-cameras"],["license plate readers","alpr-cameras"],["license plate cameras","alpr-cameras"],["plate readers","alpr-cameras"]]),H0=new Map([["new york","nyc"],["new york city","nyc"],["san francisco","sf"],["washington","dc"],["washington dc","dc"],["washington d.c.","dc"]]),wq=new Map([["photoreal","photoreal"],["google 3d","photoreal"],["google","photoreal"],["3d","photoreal"],["photorealistic","photoreal"],["bing-aerial","bing-aerial"],["bing aerial","bing-aerial"],["bing-labels","bing-labels"],["bing labels","bing-labels"],["labels","bing-labels"],["aerial with labels","bing-labels"],["esri-imagery","esri-imagery"],["esri","esri-imagery"],["esri imagery","esri-imagery"],["esri satellite","esri-imagery"],["osm","osm"],["openstreetmap","osm"],["open street map","osm"],["road","osm"],["roads","osm"],["road map","osm"]]),Jm=[{layerId:"flights",kind:"aircraft"},{layerId:"military",kind:"aircraft"},{layerId:"ais-live-vessels",kind:"vessel"},{layerId:"satellites",kind:"satellite"}],Eq=new Map([["flights","flights"],["planes","flights"],["aircraft","flights"],["military","military"],["military flights","military"],["satellites","satellites"],["vessels","ais-live-vessels"],["ships","ais-live-vessels"]]),$0=new WeakMap;function ka(e){var n,i;(n=e.signal)==null||n.throwIfAborted();let t=$0.get(e);return t||(t={reverseGeocodeCache:new Map,reverseGeocodeInFlight:new Map,nearbyPlacesCache:new Map,nearbyPlacesInFlight:new Map},$0.set(e,t),(i=e.signal)==null||i.addEventListener("abort",()=>{for(const o of Object.values(t))o.clear()},{once:!0})),t}const Tq=64,go=1500,G0=new WeakMap;function kq({viewer:e,styleManager:t,dataManager:n,sceneDirector:i=null,annotations:o=null,placeSearch:r=So,floorServices:s=jw,annotationResolver:a=jN,searchNavigation:c=wa}){const l=new Map;let u;const h=d=>a.resolveRegionRingForQuery(d,void 0,r);return zq(e),$w(e,uu),async function d(f,p={},g={}){var b,C,y,v,M,w,E,k,T,I,R;const _=p&&typeof p=="object"?p:{},m=()=>{var S;return!((S=g.signal)!=null&&S.aborted)&&(typeof g.isCurrent!="function"||g.isCurrent())};if(f==="zoom_to_globe"&&St(`nav:${f}`),f==="zoom_to_globe"&&e.trackedEntity&&vd(e,n),f==="adjust_camera_zoom"){const S=String(_.direction||"").toLowerCase()==="out",A=String(_.amount||"medium").toLowerCase(),L={little:1.25,medium:1.6,lot:2.4}[A]||1.6;if(Uw(S?L:1/L))return{ok:!0,action:"adjust_camera_zoom",direction:S?"out":"in",amount:A,orbitRadiusAdjusted:!0}}if(f==="set_layer_visibility"){const S=Io(_.layerId);if(!S)throw new Error(`Unknown data layer: ${_.layerId||"missing"}`);if(!n.layers.has(S)){if(S==="radio")return{ok:!1,action:"set_layer_visibility",layerId:S,error:"Radio layer unavailable",...Lr(n,S)};throw new Error(`Unknown data layer: ${_.layerId||"missing"}`)}const A=!!_.enabled,L={origin:"voice"};g.signal&&(L.signal=g.signal);let F=!1,P=null,O=null;try{if(typeof n._setEnabledWithIntent=="function"){const V=n._setEnabledWithIntent(S,A,L);F=await V.promise,Number.isInteger(V.intentEpoch)&&(O=await((b=n._waitForVisibilityIntent)==null?void 0:b.call(n,S,V.intentEpoch)))}else F=await n.setEnabled(S,A,L);(S==="rocket-launches"||S==="satellites")&&await((C=t==null?void 0:t._waitForContextLayerSettlement)==null?void 0:C.call(t))}catch(V){P=V}const D=Lr(n,S);if((O==null?void 0:O.succeeded)===!1&&O.cancellationReason)return{ok:!1,action:"set_layer_visibility",layerId:S,cancelled:!0,phase:O.phase,cancellationReason:O.cancellationReason,successorIntentEpoch:O.successorIntentEpoch,successorEnabled:O.successorEnabled,successorOrigin:O.successorOrigin,...D};const $=(O==null?void 0:O.succeeded)===!0;if(!(!((y=g.signal)!=null&&y.aborted)&&(typeof g.isCurrent!="function"||g.isCurrent()))&&!$)return{ok:!1,action:"set_layer_visibility",layerId:S,cancelled:!0,error:"Layer request was superseded by a newer voice turn",...D};const N=D.enabled,G=D.lifecycleState===(A?"enabled":"disabled")&&!D.lifecycleUncertain;if(P)return{ok:!1,action:"set_layer_visibility",layerId:S,error:(P==null?void 0:P.message)||`Could not ${A?"enable":"disable"} the requested layer`,...D};if(F===!1||N!==A||!G)return{ok:!1,action:"set_layer_visibility",layerId:S,error:`Could not ${A?"enable":"disable"} the requested layer`,...D};A&&l.set(S,Date.now());const W=n.getAll().find(V=>V.id===S);return{ok:!0,action:"set_layer_visibility",layerId:S,label:(W==null?void 0:W.name)||S,...D}}if(f==="select_nearest_aircraft"){const S=Io(_.layerId||"flights");if(!["flights","military"].includes(S))return{ok:!1,action:"select_nearest_aircraft",error:"Nearest-aircraft selection supports Flights or Military Flights only"};const A=!!String(_.locationId||"").trim(),L=!!String(_.locationQuery||"").trim(),F=_.latitude!=null&&_.longitude!=null&&Number.isFinite(Number(_.latitude))&&Number.isFinite(Number(_.longitude));if(!A&&!L&&!F)return{ok:!1,action:"select_nearest_aircraft",stage:"location",error:"Nearest-aircraft selection needs a preset, place name, or latitude and longitude"};const P={waitForArrival:!0,..._.locationId?{locationId:_.locationId}:{},..._.locationQuery?{query:_.locationQuery}:{},...F?{latitude:Number(_.latitude),longitude:Number(_.longitude)}:{}},O=await d("set_layer_visibility",{layerId:S,enabled:!0},g);if((O==null?void 0:O.ok)!==!0||!m())return{ok:!1,action:"select_nearest_aircraft",stage:"layer",cancelled:!m()||!!(O!=null&&O.cancelled),error:(O==null?void 0:O.error)||`${S} could not be enabled`,layer:O};const D=await d("fly_to_location",P,g);if((D==null?void 0:D.ok)!==!0||!m())return{ok:!1,action:"select_nearest_aircraft",stage:"location",cancelled:!m()||!!(D!=null&&D.cancelled),error:(D==null?void 0:D.error)||`Could not arrive at ${(D==null?void 0:D.label)||_.locationQuery||_.locationId||"the requested place"}`,location:D,layer:O};const $=((v=n.layers.get(S))==null?void 0:v.module)||null;let x=!1;try{typeof n.refreshLayer=="function"?x=await n.refreshLayer(S,{signal:g.signal}):typeof($==null?void 0:$.update)=="function"&&(x=await $.update(e,{signal:g.signal})!==!1)}catch{x=!1}if(!x||!m())return{ok:!1,action:"select_nearest_aircraft",stage:"refresh",cancelled:!m(),error:m()?`${O.label||S} is enabled, but its destination refresh did not complete`:"Nearest-aircraft refresh was cancelled",location:D,layer:O};const N=((M=$==null?void 0:$.getStats)==null?void 0:M.call($))||{},G=String(N.source||($==null?void 0:$.source)||"").trim()||null,W={state:sf({...N,source:G}),source:G,count:Number.isFinite(Number(N.count))?Number(N.count):null},V=await O0(Y0(e,n,{recordLimitByLayer:{[S]:Number.MAX_SAFE_INTEGER},placeSearch:r,resolveRegionRing:h})).query({layers:[S],scope:{kind:"view"},filters:[{field:"onGround",op:"eq",value:!1}],sortBy:"distance",sortDir:"asc",limit:1}),H=((w=V==null?void 0:V.items)==null?void 0:w[0])||null;if(!H||!m())return{ok:!1,action:"select_nearest_aircraft",stage:"nearest",cancelled:!m(),error:m()?W.state==="unavailable"?`${O.label||S} is enabled, but ${W.source||"its aircraft feed"} is unavailable`:`${O.label||S} is enabled${W.state==="fallback"?` on the ${W.source||"fallback"} feed`:""}, but no airborne aircraft is loaded in the ${D.label||"destination"} view yet`:"Nearest-aircraft selection was cancelled",location:D,layer:O,feed:W,count:(V==null?void 0:V.count)||0};const B=H.icao24||H.id,q=await j0(e,n,t,{query:B,layerId:S});return(q==null?void 0:q.ok)!==!0?{ok:!1,action:"select_nearest_aircraft",stage:"selection",error:(q==null?void 0:q.error)||"The nearest airborne aircraft could not be selected",location:D,layer:O,feed:W,selection:q}:{ok:!0,action:"select_nearest_aircraft",location:D.label,layerId:S,label:q.label,feed:W,aircraft:{id:B,callsign:H.callsign||null,altitudeM:H.altitudeM??null,distanceKm:H.distanceKm??null,onGround:!1}}}if(f==="set_visual_style"){const S=nW(_.style);if(!S)throw new Error(`Unknown visual style: ${_.style||"missing"}`);return t.setStyle(S),{ok:!0,action:"set_visual_style",style:S}}if(f==="set_panel_open"){const S=Yq(_.panelId||_.panel);if(!S)throw new Error(`Unknown panel: ${_.panelId||_.panel||"missing"}`);const A=_.open!==!1;return Md(t,S,A),{ok:!0,action:"set_panel_open",panelId:S,open:A}}if(f==="set_context_mode"){if(!(t!=null&&t.setContextMode))return{ok:!1,action:"set_context_mode",error:"Context mode control unavailable"};const S=Jq(_.mode||_.contextMode);if(S===null&&_.mode!=null&&String(_.mode||"").trim()!=="off")return{ok:!1,action:"set_context_mode",error:`Unknown context mode: ${_.mode||"missing"}`};const A=()=>bi(typeof t.getContextModeState=="function"?t.getContextModeState():{});if(!m())return{ok:!1,action:"set_context_mode",cancelled:!0,error:"Context request was cancelled before it could run",...A()};S&&S!=="off"&&Md(t,"global-context-panel",!0);const L=await t.setContextMode(S==="off"?null:S,{signal:g.signal,isCurrent:g.isCurrent});if(!m()&&(L==null?void 0:L.ok)!==!0)return{...bi(L),ok:!1,action:"set_context_mode",cancelled:!0,error:(L==null?void 0:L.error)||"Context request was cancelled before it completed",...A()};const F=["contacts","flights"].includes(S)?zr(n):null;return{...bi(L),...F?{contactsWindow:F}:{}}}if(f==="control_cockpit"){if(!(t!=null&&t.controlCockpit))return{ok:!1,action:"control_cockpit",error:"Cockpit control unavailable"};const S=_.action||_.command,A=eW(S),L=_.notificationToken||null;if(!A)return{ok:!1,action:"control_cockpit",error:`Unknown cockpit action: ${_.action||_.command||"missing"}`};const F=Qq(S),P=Xq(_.targetLayer||F.targetLayer||_.layer||_.layerId),O=Zq(_.aircraftClass||F.aircraftClass||_.type||_.filterType);let D=!1,$=null,x=null;if(A==="enter"&&typeof t.setContextMode=="function"){if(!m())return{ok:!1,action:"control_cockpit",cancelled:!0,error:"Cockpit entry was cancelled before it could run",state:((E=t.getCockpitState)==null?void 0:E.call(t))||null};x=((k=t.getAircraftTrackingTarget)==null?void 0:k.call(t))||null;const W=typeof t.getContextModeState=="function"?t.getContextModeState():{};if($=(W==null?void 0:W.mode)||null,!((W==null?void 0:W.mode)==="flights"&&(W==null?void 0:W.active)!==!1&&(W==null?void 0:W.changing)!==!0)){const H=await t.setContextMode("flights",{signal:g.signal,isCurrent:g.isCurrent,claimVisualAuthority:!1});if(D=(H==null?void 0:H.ok)===!0,(H==null?void 0:H.ok)!==!0||!m()){const B=D?await t.setContextMode($,{claimVisualAuthority:!1}):null;return{ok:!1,action:"control_cockpit",cancelled:!m()||!!(H!=null&&H.cancelled),error:(H==null?void 0:H.error)||"Contacts context could not be established for Cockpit entry",context:H?bi(H):null,contextRollback:bi(B),state:((T=t.getCockpitState)==null?void 0:T.call(t))||null}}}}const N=A==="enter"?Aq(n):null;let G;try{G=await t.controlCockpit(A,{notificationToken:L,targetLayer:P,aircraftClass:O,selectedTarget:N,rollbackTarget:x})}catch(W){G={ok:!1,action:"control_cockpit",error:W instanceof Error?W.message:String(W),state:((I=t.getCockpitState)==null?void 0:I.call(t))||null}}if(A==="enter"&&(G==null?void 0:G.ok)!==!0&&D){const W=await t.setContextMode($,{claimVisualAuthority:!1,...m()?{signal:g.signal,isCurrent:g.isCurrent}:{}});return{...G,contextRollback:bi(W)}}return G}if(f==="show_data_layers_menu"){const S=Io(_.layerId||_.layer);return Md(t,"data-panel",!0),{ok:!0,action:"show_data_layers_menu",panelId:"data-panel",focusedLayer:S&&n.layers.has(S)?tW(S):null,layers:n.getAll().filter(L=>L.showInTogglePanel!==!1).map(L=>{var F;return{id:L.id,name:L.name,enabled:L.enabled,count:((F=L.stats)==null?void 0:F.count)||0}})}}if(f==="fly_to_location")return iW(e,_,{placeSearch:r,searchNavigation:c,signal:g.signal,runImmediate:typeof(t==null?void 0:t.runImmediateLocationNavigation)=="function"?S=>t.runImmediateLocationNavigation(S):null,beginDeferred:typeof(t==null?void 0:t.beginDeferredLocationNavigation)=="function"?()=>t.beginDeferredLocationNavigation():null,reassertDeferred:typeof(t==null?void 0:t.reassertDeferredLocationNavigation)=="function"?S=>t.reassertDeferredLocationNavigation(S):null,onStart:()=>{if(typeof(t==null?void 0:t.beginLocationNavigation)=="function"){t.beginLocationNavigation();return}St("nav:fly_to_location"),e.trackedEntity&&vd(e,n)}});if(f==="adjust_camera_zoom")return jq(e,_);if(f==="zoom_to_globe"){if(typeof(t==null?void 0:t.resetToGlobeView)=="function")return t.resetToGlobeView();const S=_m(e);return{ok:!0,action:"zoom_to_globe",heightKm:Math.round(ho.heightM/1e3),centeredOn:{latitude:Number(S.latitude.toFixed(2)),longitude:Number(S.longitude.toFixed(2))}}}if(f==="next_iss_pass")return Kq(e,n,_);if(f==="analyst_query")return u||(u=O0(Y0(e,n,{placeSearch:r,resolveRegionRing:h}))),EW(u,n,_,l);if(f==="move_camera")return Gw(_,(S,A)=>da(t,"camera","move_camera",S,A));if(f==="fly_route")return zw(((R=o==null?void 0:o.list)==null?void 0:R.call(o))||[],_,(S,A)=>s.cachedGroundFloor(S,A),S=>da(t,"route","fly_route",S),S=>s.warmGroundFloor(S));if(f==="get_entity_context")return rW(e,n,t,_,r);if(f==="get_current_view_state")return oW(e,t,n,i);if(f==="set_hud"){const S={ok:!0,action:"set_hud"};if(_.layout!=null){const A=t.setHudLayout(_.layout);if(!A.ok)return{...A,action:"set_hud"};Object.assign(S,A)}if(_.visible!=null){const A=t.setHudVisible(_.visible);if(!A.ok)return{...A,action:"set_hud"};Object.assign(S,A)}return{...S,hud:t.getControlState().hud}}if(f==="set_detection")return{action:"set_detection",...t.setDetection({enabled:typeof _.enabled=="boolean"?_.enabled:void 0,mode:typeof _.mode=="string"?_.mode:void 0,densityPct:Number.isFinite(Number(_.densityPct))?Number(_.densityPct):void 0,allocationStrategy:typeof _.allocationStrategy=="string"?_.allocationStrategy:void 0})};if(f==="set_map_stack"){const S=Fq(_.stack);if(!S)throw new Error(`Unknown map stack: ${_.stack||"missing"}`);const A=await t.setMapStack(S);return{action:"set_map_stack",requested:S,...A}}if(f==="set_post_processing"){const S={ok:!0,action:"set_post_processing"};return _.bloom&&typeof _.bloom=="object"&&Object.assign(S,t.setBloom({enabled:typeof _.bloom.enabled=="boolean"?_.bloom.enabled:void 0,intensityPct:Number.isFinite(Number(_.bloom.intensityPct))?Number(_.bloom.intensityPct):void 0})),_.sharpen&&typeof _.sharpen=="object"&&Object.assign(S,t.setSharpen({enabled:typeof _.sharpen.enabled=="boolean"?_.sharpen.enabled:void 0,intensityPct:Number.isFinite(Number(_.sharpen.intensityPct))?Number(_.sharpen.intensityPct):void 0})),S}if(f==="control_scene")return Sq(i,_);if(f==="control_cctv")return Nq(n,_,t);if(f==="control_radio")return Vq(e,n,_,{...g,placeSearch:r});if(f==="track_entity")return j0(e,n,t,_);if(f==="stop_tracking")return vd(e,n);if(f==="frame_overhead")return $q(e,n,t,_);if(f==="annotate_map")return Pq(o,_);if(f==="clear_annotations")return xq(o);throw new Error(`Unknown GEV tool: ${f}`)}}function Aq(e){var o,r;const t=am({dataManager:e});if(!t||!["flights","military"].includes(t.layerId))return null;const n=(r=(o=e==null?void 0:e.layers)==null?void 0:o.get(t.layerId))==null?void 0:r.module;if(!(n!=null&&n.trackById)||typeof n.trackById!="function")return null;const i=String(t.id||"").trim();return i?{layerId:t.layerId,id:i}:null}const U0=24,Iq=12,yd=200,Rq=120;function Qa(e,t){if(typeof e!="string")return e;const n=e.trim();return n.length>t?n.slice(0,t):n}function Lq(e){if(!e||typeof e!="object")return e;const t={...e};return typeof t.target=="string"&&(t.target=Qa(t.target,yd)),typeof t.toTarget=="string"&&(t.toTarget=Qa(t.toTarget,yd)),typeof t.label=="string"&&(t.label=Qa(t.label,Rq)),Array.isArray(t.points)&&(t.points=t.points.slice(0,Iq).map(n=>n&&typeof n=="object"&&typeof n.target=="string"?{...n,target:Qa(n.target,yd)}:n)),t}async function Pq(e,t={}){if(!e||typeof e.annotate!="function")return{ok:!1,action:"annotate_map",error:"Annotation engine unavailable"};const n=Array.isArray(t.annotations)?t.annotations:[];if(!n.length)return{ok:!1,action:"annotate_map",error:"No annotations supplied"};if(n.length>U0)return{ok:!1,action:"annotate_map",error:`Too many annotations in one call (${n.length}); max ${U0}. Mark fewer places, or split across calls.`};const i=n.map(Lq),o=await e.annotate(i,{clearPrevious:!1,persist:t.persist!==!1,flyTo:!!t.flyTo}),r=o.drawn>0,s=o.failed>0,a=[];for(const c of o.results||[])c.ok||(Array.isArray(c.failedTargets)&&c.failedTargets.length?a.push(...c.failedTargets):a.push(c.target||c.label||"an unnamed place"));return{ok:r,action:"annotate_map",drawn:o.drawn,failed:o.failed,partial:r&&s,failedLabels:s?a:void 0,routeFallback:(o.results||[]).some(c=>c.ok&&c.fallback),capped:!!o.capped,outlinePending:(o.results||[]).some(c=>c.ok&&c.outlinePending)||void 0,items:o.results,error:s?"Could not place one or more annotations":null}}function xq(e){return!e||typeof e.clear!="function"?{ok:!1,action:"clear_annotations",error:"Annotation engine unavailable"}:(e.clear(),{ok:!0,action:"clear_annotations"})}function Fq(e){const t=String(e||"").trim().toLowerCase();return t&&wq.get(t)||null}function Sq(e,t={}){if(!e)return{ok:!1,action:"control_scene",error:"Scene director unavailable"};const n=String(t.action||"").toLowerCase();if(n==="list")return{ok:!0,action:"control_scene",scenes:e.listScenes(),...e.getPlaybackStatus()};if(n==="status")return{ok:!0,action:"control_scene",...e.getPlaybackStatus()};if(n==="stop")return e.stopScene("Stopped by voice"),{ok:!0,action:"control_scene",running:!1};if(n==="next")return e.runNextScene(),{ok:!0,action:"control_scene",advanced:!0};if(n==="play"){if(e.running)return{ok:!1,action:"control_scene",error:"A scene is already running — stop it first"};const i=t.sceneId?e.findSceneByQuery(t.sceneId):e.listScenes()[0]||null;return i?(e.startScene(i.id,{single:!0}),{ok:!0,action:"control_scene",playing:i.title,shots:i.shots}):{ok:!1,action:"control_scene",error:`No scene matched "${t.sceneId||""}"`,scenes:e.listScenes()}}throw new Error(`Unknown scene action: ${t.action||"missing"}`)}async function Nq(e,t={},n=null){var s,a,c,l,u,h,d,f,p;const i=String(t.action||"").toLowerCase(),o=(s=e.layers.get("cctv"))==null?void 0:s.module;if(!o)return{ok:!1,action:"control_cctv",error:"CCTV layer unavailable"};if(i==="enable"||i==="disable")return await e.setEnabled("cctv",i==="enable",{origin:"voice"}),{ok:!0,action:"control_cctv",enabled:e.isEnabled("cctv")};if(!e.isEnabled("cctv"))return{ok:!1,action:"control_cctv",error:"CCTV layer is off — enable it first"};const r=()=>{var _,m,b;const g=((_=o.getUIState)==null?void 0:_.call(o))||{};return{activeCameraId:g.activeCameraId||null,activeCamera:((m=g.activeCamera)==null?void 0:m.name)||((b=g.activeCamera)==null?void 0:b.id)||null,cameraCount:Array.isArray(g.cameras)?g.cameras.length:g.count||0,showCoverage:!!g.showCoverage,coverageMode:g.coverageMode||(g.showCoverage?"on":"off"),showProjection:!!g.showProjection,calibrationMode:!!g.calibrationMode,autoHop:!!g.autoHop}};if(i==="select"){const g=String(t.cameraQuery||"").trim().toLowerCase();if(!g)throw new Error("control_cctv select needs cameraQuery");const _=((c=(a=o.getUIState)==null?void 0:a.call(o))==null?void 0:c.cameras)||[],m=_.find(y=>String(y.id||"").toLowerCase()===g)||_.find(y=>String(y.name||"").toLowerCase()===g)||_.find(y=>String(y.name||"").toLowerCase().includes(g));if(!m)return{ok:!1,action:"control_cctv",error:`No camera matched "${t.cameraQuery}"`,...r()};(l=n==null?void 0:n.supersedeDeferredNavigation)==null||l.call(n);const b=o.selectCamera(m.id),C=b?o.focusCamera(m.id,1.8):mn.NO_ACTIVE_CAMERA;return{action:"control_cctv",selected:m.name||m.id,...r(),...Za(C,{cameraSelected:!!b})}}if(i==="next"||i==="prev"){(u=n==null?void 0:n.supersedeDeferredNavigation)==null||u.call(n);const g=o.cycleCamera(i==="next"?1:-1),_=g?o.focusCamera(g,1.8):mn.NO_ACTIVE_CAMERA;return{action:"control_cctv",...r(),...Za(_,{cameraSelected:!!g})}}if(i==="nearest"){(h=n==null?void 0:n.supersedeDeferredNavigation)==null||h.call(n);const g=o.focusNearest({focus:!1}),_=g?o.focusCamera(g,1.8):mn.NO_ACTIVE_CAMERA;return{action:"control_cctv",...r(),...Za(_,{cameraSelected:!!g})}}if(i==="focus"){const g=(f=(d=o.getUIState)==null?void 0:d.call(o))==null?void 0:f.activeCameraId;g&&((p=n==null?void 0:n.supersedeDeferredNavigation)==null||p.call(n));const _=g?o.focusCamera(g):mn.NO_ACTIVE_CAMERA;return{action:"control_cctv",...r(),...Za(_)}}if(i==="viewshed"){const g=typeof t.enabled=="boolean"&&!t.enabled?"on":"viewshed";return e.setLayerParams("cctv",{coverageMode:g},{origin:"voice"}),{ok:!0,action:"control_cctv",...r()}}if(i==="adjust"){const g=r(),_=typeof t.enabled=="boolean"?t.enabled:!g.calibrationMode;return e.setLayerParams("cctv",{calibrationMode:_},{origin:"voice"}),{ok:!0,action:"control_cctv",...r()}}if(i==="coverage"){const g=r(),_=typeof t.enabled=="boolean"?t.enabled:!g.showCoverage;return e.setLayerParams("cctv",{coverageMode:_?"on":"off"},{origin:"voice"}),{ok:!0,action:"control_cctv",...r()}}if(i==="projection"||i==="autohop"){const g=i==="projection"?"showProjection":"autoHop",_=r(),m=typeof t.enabled=="boolean"?t.enabled:!_[g];return e.setLayerParams("cctv",{[g]:m},{origin:"voice"}),{ok:!0,action:"control_cctv",...r()}}throw new Error(`Unknown CCTV action: ${t.action||"missing"}`)}const Dq=new Map([["us",{lat:39.8,lon:-98.6,country:"US",label:"United States"}],["usa",{lat:39.8,lon:-98.6,country:"US",label:"United States"}],["united states",{lat:39.8,lon:-98.6,country:"US",label:"United States"}],["united states of america",{lat:39.8,lon:-98.6,country:"US",label:"United States"}]]);function Oq(e,t=""){var o,r;const n=af(t)||af(e),i=n?Ot[n]:null;if(i){const s=i.viewBounds;return{lat:s?(s.southwest.lat+s.northeast.lat)/2:(o=i.pois[0])==null?void 0:o.lat,lon:s?(s.southwest.lng+s.northeast.lng)/2:(r=i.pois[0])==null?void 0:r.lon,label:i.name,country:""}}return Dq.get(String(e||"").trim().toLowerCase())||null}function fT(e={}){const t=Object.hasOwn(e,"latitude"),n=Object.hasOwn(e,"longitude"),i=t||n,o=e.latitude,r=e.longitude,s=t&&n&&typeof o=="number"&&typeof r=="number"&&Number.isFinite(o)&&Number.isFinite(r)&&o>=-90&&o<=90&&r>=-180&&r<=180;return{provided:i,valid:s,latitude:o,longitude:r}}function Ct(e={}){var t;return!((t=e.signal)!=null&&t.aborted)&&(typeof e.isCurrent!="function"||e.isCurrent())}function z0(){const e=new Error("Radio request was superseded by a newer voice turn");return e.name="AbortError",e}async function Bq(e={},t=fT(e),n={}){if(!Ct(n))throw z0();if(t.valid){const{latitude:c,longitude:l}=t;return{lat:c,lon:l,label:`${c.toFixed(3)}, ${l.toFixed(3)}`,country:""}}const i=String(e.locationQuery||"").trim(),o=Oq(i,e.locationId);if(o)return o;if(!i)return null;const{placeSearch:r=So,signal:s}=n,{place:a}=await r.geocode(i,{signal:s});if(!Ct(n))throw z0();return a?{lat:a.lat,lon:a.lng,label:a.label||i,country:""}:null}async function Vq(e,t,n={},i={}){var w,E,k,T,I,R;const o=String(n.action||"").trim().toLowerCase(),r=fT(n),s=!!(n.category||n.locationId||n.locationQuery||r.provided||n.country||n.stationQuery),a=o==="play"&&s?"select":o,c=()=>Lr(t,"radio"),l=(w=t.layers.get("radio"))==null?void 0:w.module;if(!l)return{ok:!1,action:"control_radio",error:"Radio layer unavailable",...c()};const u=lc(n.country);let h=null,d=null;const f=()=>h?{phase:h.phase,cancellationReason:h.cancellationReason||null,successorIntentEpoch:h.successorIntentEpoch??null,successorEnabled:h.successorEnabled??null,successorOrigin:h.successorOrigin??null}:{},p=S=>({ok:!1,action:"control_radio",cancelled:!0,error:"Radio request was superseded by a newer voice turn",...f(),...S()}),g=S=>{const A=c();return A.enabled===S&&A.lifecycleState===(S?"enabled":"disabled")&&!A.lifecycleUncertain},_=async S=>{var F;if(h=null,d=null,!Ct(i))return!1;const A={origin:"voice"};i.signal&&(A.signal=i.signal);let L=!1;try{if(typeof t._setEnabledWithIntent=="function"){const P=t._setEnabledWithIntent("radio",S,A);L=await P.promise,Number.isInteger(P.intentEpoch)&&(h=await((F=t._waitForVisibilityIntent)==null?void 0:F.call(t,"radio",P.intentEpoch)))}else L=await t.setEnabled("radio",S,A)}catch(P){return d=P,!1}return(h==null?void 0:h.succeeded)===!1||!Ct(i)&&(h==null?void 0:h.succeeded)!==!0?!1:L!==!1&&g(S)},m=(S,A)=>({ok:!1,action:"control_radio",cancelled:!!(h!=null&&h.cancellationReason),error:(d==null?void 0:d.message)||S,...f(),...A()}),b=async({enableIfOff:S=!1}={})=>{const A=c();return g(!0)?!0:!S&&!A.enabled&&A.lifecycleState==="disabled"&&!A.lifecycleUncertain?!1:await _(!0)&&g(!0)},C=()=>{var A,L;const S=((A=l.getUIState)==null?void 0:A.call(l))||{};return{radioAction:a,...c(),stationId:((L=S.selected)==null?void 0:L.id)||null,category:S.filter||"all",audioState:S.audioState||"stopped",volumePct:Math.round((S.volume??.8)*100),mutedForVoice:!!S.voiceDucked}};if(!u.valid)return{ok:!1,action:"control_radio",error:"Radio country must be a recognized code or country name (80 characters maximum)",...C()};if(r.provided&&!r.valid)return{ok:!1,action:"control_radio",error:"Radio coordinates require a complete numeric latitude/longitude pair in range",...C()};if(!Ct(i))return p(C);if(a==="enable"||a==="disable"){const S=a==="enable",A=await _(S);return!Ct(i)&&(h==null?void 0:h.succeeded)!==!0?p(C):A?{ok:!0,action:"control_radio",...C()}:m(`Radio could not be ${S?"enabled":"disabled"}`,C)}if(a==="status")return{ok:!0,action:"control_radio",...C()};if(a==="volume"){const S=Number(n.volumePct);if(!Number.isFinite(S)||S<0||S>100)return{ok:!1,action:"control_radio",error:"Radio volume must be from 0 to 100",...C()};const A=await b();return Ct(i)?A?Ct(i)?(typeof t.setLayerParams=="function"?t.setLayerParams("radio",{volume:S/100},{origin:"voice"}):l.setVolume(S/100))===!1?{ok:!1,action:"control_radio",error:"Radio must be fully enabled before changing volume",...C()}:{ok:!0,action:"control_radio",...C()}:p(C):m("Radio must be fully enabled before changing volume",C):p(C)}if(a==="stop"){if(!Ct(i))return p(C);let S=!1;try{S=await l.stopPlayback({origin:"voice"})}catch(A){return{ok:!1,action:"control_radio",error:(A==null?void 0:A.message)||"Radio could not be stopped",...C()}}return Ct(i)?S===!1?{ok:!1,action:"control_radio",error:"Radio could not be stopped",...C()}:{ok:!0,action:"control_radio",...C()}:p(C)}if(a==="pause"){const S=c();return!S.enabled&&S.lifecycleState!=="enabling"?{ok:!0,action:"control_radio",changed:!1,...C()}:Ct(i)?((E=l.pause)==null?void 0:E.call(l,{origin:"voice"}))||!1?{ok:!0,action:"control_radio",changed:!0,...C()}:{ok:!1,action:"control_radio",error:"Radio could not be paused",...C()}:p(C)}let y=null;if(a==="select"){try{y=await Bq(n,r,i)}catch(S){if((S==null?void 0:S.name)==="AbortError"||!Ct(i))return p(C);throw S}if(!Ct(i))return p(C);if((n.locationQuery||n.locationId)&&!y)return{ok:!1,action:"control_radio",error:`Could not resolve Radio location "${n.locationQuery||n.locationId}"`,...C()}}const v=await b({enableIfOff:!0});if(!Ct(i))return p(C);if(!v)return m("Radio could not be enabled",C);const M=((k=l.getUIState)==null?void 0:k.call(l))||{};if(!Ct(i))return p(C);if(!M.stationCount)return{ok:!1,action:"control_radio",error:M.error||"No healthy Radio stations are available",...C()};if(a==="play"||a==="resume"){if(!Ct(i))return p(C);const S=M.selected?!0:(T=l.cycleStation)==null?void 0:T.call(l,1,{focus:!1,autoplay:!1});return{ok:!!S,action:"control_radio",radioPlaybackRequested:!!S,...C()}}if(a==="next"||a==="previous"){if(!Ct(i))return p(C);n.category&&(typeof t.setLayerParams=="function"?t.setLayerParams("radio",{filter:String(n.category)},{origin:"voice"}):l.setFilter(String(n.category)));const S=(I=l.cycleStation)==null?void 0:I.call(l,a==="next"?1:-1,{focus:!1,autoplay:!1});return{ok:!!S,action:"control_radio",radioPlaybackRequested:!!S,...C()}}if(a==="select"){const S=y;return Ct(i)?((R=l.selectRequestedStation)==null?void 0:R.call(l,{categoryId:String(n.category||"all"),anchor:S?{lat:S.lat,lon:S.lon}:null,country:u.empty?String((S==null?void 0:S.country)||""):u.code,stationQuery:String(n.stationQuery||"")},{autoplay:!1}))?{ok:!0,action:"control_radio",radioPlaybackRequested:!0,requestedLocation:(S==null?void 0:S.label)||null,...C()}:{ok:!1,action:"control_radio",error:"No Radio station matched that location and category",...C()}:p(C)}throw new Error(`Unknown Radio action: ${n.action||"missing"}`)}function Za(e,{cameraSelected:t=!1}={}){return e===mn.FOCUSED||e===!0?{ok:!0,error:null}:e===mn.TRACKING_HOLDS_VIEW?{ok:!1,error:t?"Camera selected; tracking holds the view — say untrack to fly":"Camera active; tracking holds the view — say untrack first"}:e===mn.COCKPIT_ACTIVE?{ok:!1,error:t?"Camera selected; in cockpit — exit cockpit to fly to it":"In cockpit — exit cockpit to fly to a camera"}:{ok:!1,error:"No active camera to focus"}}function Hq(e,t=""){const n=i=>String(i??"").trim();return n(e==null?void 0:e.callsign)||n(e==null?void 0:e.registration)||n(e==null?void 0:e.name)||n(e==null?void 0:e.icao24)||n(e==null?void 0:e.mmsi)||n(e==null?void 0:e.noradId)||String(t)}async function j0(e,t,n,i={}){var l,u,h;const o=String(i.query||"").trim();if(!o)throw new Error("track_entity needs a query");if(/\bfires?\b/i.test(o)){if(!t.isEnabled("local-firms"))return{ok:!1,action:"track_entity",query:o,error:"The FIRMS fires layer is not enabled"};const d=(l=t.layers.get("local-firms"))==null?void 0:l.module,f=(u=d==null?void 0:d.getStrongestFire)==null?void 0:u.call(d);return f?!Number.isFinite(f.latitude)||!Number.isFinite(f.longitude)?{ok:!1,action:"track_entity",query:o,error:"The strongest fire has no usable position"}:da(n,"fire","track_entity",()=>(ji(e,f.latitude,f.longitude,{range:14e3,pitch:-50,heading:0,buildingHeight:0,duration:2.2}),{ok:!0,action:"track_entity",kind:"fire",layerId:"local-firms",label:f.label||"Strongest fire",latitude:f.latitude,longitude:f.longitude,frp:f.frp??null})):{ok:!1,action:"track_entity",query:o,error:"No fire detections loaded yet"}}const r=i.layerId?Io(i.layerId):null,s=Jm.filter(d=>!r||d.layerId===r),a=[];for(const d of s){if(!t.isEnabled(d.layerId)){a.push(d.layerId);continue}const f=(h=t.layers.get(d.layerId))==null?void 0:h.module;if(!f||typeof f.findByQuery!="function")continue;const p=f.findByQuery(o);if(p)return d.kind==="vessel"&&(!Number.isFinite(p.latitude)||!Number.isFinite(p.longitude))?{ok:!1,action:"track_entity",layerId:d.layerId,kind:d.kind,error:"The matched vessel has no usable position"}:da(n,d.kind,"track_entity",()=>{var _,m,b;let g=!1;return d.kind==="vessel"?(g=!!((_=f.selectById)!=null&&_.call(f,p.mmsi)),ji(e,p.latitude,p.longitude,{range:6e3,pitch:-45,heading:0,buildingHeight:0,duration:2})):d.kind==="satellite"?g=!!((m=f.trackById)!=null&&m.call(f,p.noradId,{origin:"voice"})):g=!!((b=f.trackById)!=null&&b.call(f,p.icao24,{origin:"voice"})),{ok:g,action:"track_entity",layerId:d.layerId,kind:d.kind,label:Hq(p,o),latitude:p.latitude??null,longitude:p.longitude??null,altitudeM:Number.isFinite(p.altitudeM)?Math.round(p.altitudeM):null,error:g?null:"Match found but tracking failed"}})}const c=a.length?` (disabled layers skipped: ${a.join(", ")})`:"";return{ok:!1,action:"track_entity",query:o,error:`Nothing matched "${o}"${c}`}}function vd(e,t){var o,r,s;const n=[],i=new Set;for(const a of Jm){const c=(o=t.layers.get(a.layerId))==null?void 0:o.module;if(c)try{a.kind==="vessel"?(r=c.getSelectedInfo)!=null&&r.call(c)&&(typeof c.clearSelection!="function"||c.clearSelection()===!1?i.add(a.layerId):n.push(a.layerId)):(s=c.getTrackedInfo)!=null&&s.call(c)&&(typeof c.stopTracking!="function"||c.stopTracking({origin:"voice"})===!1?i.add(a.layerId):n.push(a.layerId))}catch{i.add(a.layerId)}}for(const[a,c]of[["flights","selectedFlightsTrackingId"],["military","selectedMilitaryTrackingId"],["satellites","selectedSatTrackingId"]])try{t.setLayerParams(a,{[c]:null},{origin:"voice"})===!1&&i.add(a)}catch{i.add(a)}if(e&&(e.trackedEntity=void 0),i.size){const a=[...i];return{ok:!1,action:"stop_tracking",released:n,failedLayerIds:a,error:`Tracking could not be cleared for: ${a.join(", ")}`}}return{ok:!0,action:"stop_tracking",released:n}}async function $q(e,t,n,i={}){var p;const o=String(i.target||"flights").toLowerCase(),r=Eq.get(o)||Io(o)||"flights";if(!t.layers.has(r))return{ok:!1,action:"frame_overhead",error:`Unknown target layer: ${i.target}`};if(!t.isEnabled(r))return{ok:!1,action:"frame_overhead",layerId:r,error:`The ${r} layer is not enabled`};const s=(p=t.layers.get(r))==null?void 0:p.module,a=r==="satellites",c=a?3e3:r==="ais-live-vessels"?120:150,l=hu(i.radiusKm,10,2e4,c),u=uu(e)||e.camera.positionWC;let h=[];if(typeof s.getNearby=="function"?h=s.getNearby(u,l*1e3,80)||[]:typeof s.getAllPositions=="function"&&(h=(s.getAllPositions(800)||[]).filter(g=>g.position).map(g=>({...g,distance:Cesium.Cartesian3.distance(u,g.position)})).filter(g=>g.distance<=l*1e3).sort((g,_)=>g.distance-_.distance).slice(0,80)),!h.length)return{ok:!1,action:"frame_overhead",layerId:r,radiusKm:Math.round(l),count:0,error:`No ${o} within ${Math.round(l)} km of the current view`};const d=Cesium.BoundingSphere.fromPoints(h.map(g=>g.position));d.radius=Math.max(d.radius*1.25,8e3);const f=Cesium.Math.toRadians(a?-35:-62);return da(n,"frame","frame_overhead",()=>{var _;e.camera.flyToBoundingSphere(d,{duration:2,offset:new Cesium.HeadingPitchRange(e.camera.heading,f,d.radius*2.4)});let g=!1;try{const m=(_=n==null?void 0:n.getDetectionState)==null?void 0:_.call(n);if((m==null?void 0:m.detectionMode)==="OFF"){const b=n.setDetection({mode:"dense"});g=(b==null?void 0:b.ok)===!0}else m&&(g=!0)}catch{}return{ok:!0,action:"frame_overhead",layerId:r,radiusKm:Math.round(l),count:h.length,detectionEnabled:g,nearest:h.slice(0,5).map(m=>({id:m.id||m.icao24||m.mmsi||null,label:m.label||m.callsign||m.name||null}))}})}function da(e,t,n,i,o=void 0){if(typeof(e==null?void 0:e.runImmediateNavigation)!="function")return{ok:!1,action:n,error:"Camera navigation policy unavailable"};const r=e.runImmediateNavigation(t,i,o);return r!==!1?r:{ok:!1,action:n,error:"Camera navigation is unavailable in the current view"}}function Gq(e){var n,i,o;const t=[];for(const r of Jm){const s=(n=e.layers.get(r.layerId))==null?void 0:n.module;if(s)try{const a=r.kind==="vessel"?(i=s.getSelectedInfo)==null?void 0:i.call(s):(o=s.getTrackedInfo)==null?void 0:o.call(s);a&&t.push({kind:r.kind,layerId:r.layerId,...a})}catch{}}return t}async function Uq(e,t=No,{cachedOnly:n=!1}={}){const{reverseGeocodeCache:i,nearbyPlacesCache:o}=ka(t),r=gT(e),s=e.camera.positionCartographic.height,a=ep(e);if(!a)return{placeLabels:[],streetLabels:[],nearbyPlaceLabels:[]};const c=Number(Cesium.Math.toDegrees(a.latitude).toFixed(6)),l=Number(Cesium.Math.toDegrees(a.longitude).toFixed(6)),u=bT(r,s,t),h=u?Promise.resolve(u):n?Promise.resolve(null):_T(r,s,t),d=lf(s)?n?Promise.resolve(i.get(du(c,l,t))||null):tp(c,l,t):Promise.resolve(null),f=cf(s)?n?Promise.resolve(o.get(np(c,l,s,t))||[]):yT(c,l,s,t):Promise.resolve([]),[p,g,_]=await Promise.all([_o(h,go,u),_o(d,go,null),_o(f,go,[])]);return{placeLabels:Us([g==null?void 0:g.formattedAddress,g==null?void 0:g.locality,g==null?void 0:g.region,g==null?void 0:g.country,...(g==null?void 0:g.labels)||[],...(p==null?void 0:p.visibleLabels)||[]]).slice(0,24),streetLabels:Us([...(g==null?void 0:g.streetLabels)||[],...(p==null?void 0:p.streetLabels)||[]]).slice(0,16),nearbyPlaceLabels:Us((_||[]).flatMap(m=>[m.name,m.address])).slice(0,24)}}function zq(e){if(e.__gevViewTargetPrewarmInstalled)return;e.__gevViewTargetPrewarmInstalled=!0;let t=null,n=!1;e.camera.moveEnd.addEventListener(()=>{t&&window.clearTimeout(t),t=window.setTimeout(()=>{t=null;const i=()=>{try{ep(e)}catch(o){if(n)return;n=!0,console.debug("[Voice] view-target prewarm skipped:",(o==null?void 0:o.message)||o)}};typeof window.requestIdleCallback=="function"?window.requestIdleCallback(i,{timeout:500}):i()},120)})}function jq(e,t){const n=String(t.direction||"").toLowerCase();if(n!=="in"&&n!=="out")throw new Error('adjust_camera_zoom direction must be "in" or "out"');const i=String(t.amount||"little").toLowerCase(),o={little:.25,medium:.55,lot:1}[i];if(!o)throw new Error(`Unknown zoom amount: ${t.amount}`);const r=e.camera,s=Cesium.Cartesian3.clone(r.positionWC),a=r.positionCartographic.height,c=uu(e),l=c?Cesium.Cartesian3.distance(s,c):Math.max(100,a),h=Math.max(n==="in"?20:50,l*o);if(r.cancelFlight(),n==="out")r.zoomOut(h);else{const _=Math.min(h,Math.max(0,l-25));if(_<=0)return{ok:!1,action:"adjust_camera_zoom",direction:n,amount:i,error:"Camera is already at the minimum target distance"};r.zoomIn(_)}e.scene.requestRender();const d=r.positionWC,f=Cesium.Cartesian3.distance(s,d),p=r.positionCartographic.height,g=f>=.5;return{ok:g,action:"adjust_camera_zoom",direction:n,amount:i,movementRequestedM:Math.round(h),movementActualM:Math.round(f),beforeHeightM:Math.round(a),afterHeightM:Math.round(p),error:g?null:"Cesium camera position did not change"}}const qq=["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];function Wq(e){return qq[Math.round((e%360+360)%360/22.5)%16]}function Kq(e,t,n){var c,l,u,h,d;let i=Number.isFinite(n.latitude)?n.latitude:null,o=Number.isFinite(n.longitude)?n.longitude:null;if(i==null||o==null){const f=(c=e==null?void 0:e.camera)==null?void 0:c.positionCartographic;if(!f)throw new Error("Camera position unavailable");i=Cesium.Math.toDegrees(f.latitude),o=Cesium.Math.toDegrees(f.longitude)}const r=Number.isFinite(n.minElevationDeg)?n.minElevationDeg:10,s=((d=(h=(u=(l=t==null?void 0:t.layers)==null?void 0:l.get("satellites"))==null?void 0:u.module)==null?void 0:h.getNextIssPass)==null?void 0:d.call(h,{latDeg:i,lonDeg:o,minElevDeg:r}))??{status:"no-tle"};if(s.status==="no-tle")return{ok:!1,action:"next_iss_pass",error:"ISS orbital elements not loaded yet — enable the satellites layer once, then ask again."};if(s.status==="none")return{ok:!1,action:"next_iss_pass",error:`No ISS pass above ${r}° in the next 24 hours for this location.`};const{pass:a}=s;return{ok:!0,action:"next_iss_pass",observer:{latitude:i,longitude:o},riseIso:new Date(a.riseMs).toISOString(),minutesFromNow:Math.round((a.riseMs-Date.now())/6e4),durationMin:Math.max(1,Math.round((a.setMs-a.riseMs)/6e4)),peakElevationDeg:Math.round(a.maxElevDeg),riseDirection:Wq(a.riseAzDeg)}}function Yq(e){const t=String(e||"").trim();return t?bq.has(t)?t:_q.get(t.toLowerCase())||null:null}function Io(e){const t=String(e||"").trim();return t?V0.has(t.toLowerCase())?V0.get(t.toLowerCase()):t:null}function Xq(e){const t=Io(e);return!t||!Mq.has(t)?null:t}function Qq(e){const t=String(e||"").trim().toLowerCase();if(!t)return{};const n=t.includes("vessel")||t.includes("ship")||t.includes("ais")?"ais-live-vessels":t.includes("installation")||t.includes("facility")||t.includes("base")?"military-installations":t.includes("military")?"military":null,i=t.includes("helicopter")||t.includes("helo")||t.includes("chopper")?"helicopter":null;return{targetLayer:n,aircraftClass:i}}function Zq(e){const t=String(e||"").trim().toLowerCase();return t?t.replace(/[\s-]+/g,"")===Bl?Bl:t:null}function Md(e,t,n){if(e&&typeof e.setPanelCollapsed=="function")e.setPanelCollapsed(t,!n,{explicit:!0});else{const i=document.getElementById(t);i&&i.classList.toggle("collapsed",!n)}}function Jq(e){const t=String(e||"").trim().toLowerCase();return t&&Cq.get(t)||null}function eW(e){const t=String(e||"").trim().toLowerCase();if(!t)return null;const n=B0.get(t);if(n)return n;const i=t.replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," "),o=B0.get(i);return o||(/\bprevious\b|\bprev\b/.test(i)?"previous":/\bstatus\b|\bstate\b/.test(i)?"status":/\bexit\b|\bleave\b|\bquit\b/.test(i)?"exit":/\benter\b|\bopen\b|\bstart\b/.test(i)?"enter":/\bnext\b|\bclosest\b|\bnearby\b|\bnearest\b/.test(i)?"next":null)}function tW(e){var i,o;const t=document.querySelector(`#data-toggles [data-layer-id="${CSS.escape(e)}"]`);if(!t)return null;t.scrollIntoView({block:"center",behavior:"smooth"}),t.classList.remove("gev-voice-focus"),t.offsetWidth,t.classList.add("gev-voice-focus"),window.setTimeout(()=>t.classList.remove("gev-voice-focus"),3e3);const n=((o=(i=t.querySelector(".data-name"))==null?void 0:i.textContent)==null?void 0:o.trim())||e;return{id:e,name:n}}function nW(e){const t=String(e||"").trim().toLowerCase();return t==="filter off"||t==="off"||t==="default"?"normal":t==="night vision"||t==="nvg"?"surveillance":t==="flir"?"thermal":gq.has(t)?t:null}async function iW(e,t,{placeSearch:n=So,searchNavigation:i=wa,signal:o,onStart:r=null,runImmediate:s=null,beginDeferred:a=null,reassertDeferred:c=null}={}){var M,w,E,k;const l=Number(t.rangeM),u=Number.isFinite(l)?hu(l,100,2e7,900):null,h=af(t.locationId||t.query),d=T=>typeof s=="function"?s(T):T(),f=typeof s=="function"?null:r,p=T=>({ok:!1,cancelled:!0,action:"fly_to_location",label:T});let g=null;const _=t.waitForArrival===!0?new Promise(T=>{g=T}):null,m=_?{onComplete:()=>g==null?void 0:g("arrived"),onCancel:()=>g==null?void 0:g("cancelled")}:{},b=async(T,I)=>{if(!_||(T==null?void 0:T.ok)!==!0)return T;const R=await _;return g=null,R==="arrived"?{...T,arrived:!0}:p(I)};if(h){const T=d(()=>bm(e,h,{...u||t.viewMode==="close"?{range:u||250}:{viewMode:"overview"},duration:2.2,onStart:f,...m}));if(T===!1)return p(((M=Ot[h])==null?void 0:M.name)||h);const I={ok:!!T,action:"fly_to_location",locationId:h,label:((w=Ot[h])==null?void 0:w.name)||h,rangeM:T!=null&&T.range?Math.round(T.range):u||null,navigationMode:u?"explicit-range":t.viewMode==="close"?"city-close":(T==null?void 0:T.navigationMode)||"city-overview"};return b(I,I.label)}const C=Number(t.latitude),y=Number(t.longitude);if(Number.isFinite(C)&&Number.isFinite(y)){if(d(()=>ji(e,C,y,{range:u||250,pitch:-35,heading:0,buildingHeight:0,duration:2.2,onStart:f,...m}))===!1)return p(`${C.toFixed(4)}, ${y.toFixed(4)}`);const I={ok:!0,action:"fly_to_location",latitude:C,longitude:y,label:`${C.toFixed(4)}, ${y.toFixed(4)}`,rangeM:Math.round(u||250),navigationMode:u?"explicit-range":"close-coordinate"};return b(I,I.label)}const v=String(t.query||"").trim();if(v){const T=KM(v);if(T){const L=d(()=>Cm(e,T.cityId,T.index,{duration:2.2,onStart:f,...m,...u?{range:u}:{}})),F=(k=(E=Ot[T.cityId])==null?void 0:E.pois)==null?void 0:k[T.index];if(L===!1)return p((F==null?void 0:F.name)||v);const P={ok:!!L,action:"fly_to_location",query:v,label:(F==null?void 0:F.name)||v,navigationMode:u?"preset-poi-range":"preset-poi",rangeM:L!=null&&L.range?Math.round(L.range):u||null};return b(P,P.label)}const I=typeof a=="function"?a():null;if(I===!1)return p(v);const R=typeof c=="function",S=await i(e,v,{placeSearch:n,signal:o,...u?{range:u}:{},forceClose:t.viewMode==="close",viewMode:t.viewMode||null,duration:2.2,...m,beforeFly:R?()=>c(I):null,onStart:R?null:r});if(S!=null&&S.cancelled)return p(v);const A={ok:!!S,action:"fly_to_location",query:v,label:(S==null?void 0:S.label)||v,navigationMode:(S==null?void 0:S.navigationMode)||null,rangeM:(S==null?void 0:S.rangeM)||u||null};return b(A,A.label)}throw new Error("fly_to_location needs a locationId, query, or latitude/longitude")}function af(e){const t=String(e||"").trim().toLowerCase();return t?Ot[t]?t:H0.has(t)?H0.get(t):null:null}function oW(e,t,n,i=null){var r;const o=Cesium.Cartographic.fromCartesian(e.camera.positionWC);return{ok:!0,action:"get_current_view_state",camera:{latitude:Cesium.Math.toDegrees(o.latitude),longitude:Cesium.Math.toDegrees(o.longitude),heightM:o.height},style:t.activeStyle||"normal",context:typeof t.getContextModeState=="function"?{...bi(t.getContextModeState()),...zr(n)?{contactsWindow:zr(n)}:{}}:null,cockpit:typeof t.getCockpitState=="function"?t.getCockpitState():null,controls:typeof t.getControlState=="function"?t.getControlState():null,scenePlayback:((r=i==null?void 0:i.getPlaybackStatus)==null?void 0:r.call(i))||null,tracked:Gq(n),layers:n.getAll().map(s=>{var a,c;return{id:s.id,name:s.name,enabled:s.enabled,count:((a=s.stats)==null?void 0:a.count)||0,error:((c=s.stats)==null?void 0:c.error)||null}})}}async function rW(e,t,n,i={},o=No){const r=performance.now(),s=String(i.scope||"auto").toLowerCase(),a=Io(i.layerId||i.layer),c=Math.round(hu(i.limit,1,12,5)),l=cW(t),u=e.camera.positionCartographic.height,h=ep(e),d=hW(e,n,t,h,o),p=!(l&&(s==="selected"||s==="auto"))&&q0(u)?uW(e,t,{layerId:a,limit:c,target:h}):[],g=await d;return(s==="selected"||s==="auto")&&l?(W0(r,"selected"),{ok:!0,action:"get_entity_context",scope:"selected",scene:g,selected:l}):(W0(r,"in_view"),{ok:!0,action:"get_entity_context",scope:"in_view",scene:g,selected:l||null,visible:p,count:p.length,visibleScanSkipped:!q0(u)})}function sW(e,t,n){var p,g,_,m,b;const i=t==null?void 0:t.scope;if(String((i==null?void 0:i.kind)||"").toLowerCase()!=="radius")return null;const o=Array.isArray(t.layers)?t.layers:[];if(!o.some(C=>C==="flights"||C==="military"))return null;const r=(m=(_=(g=(p=e==null?void 0:e.layers)==null?void 0:p.get("military-awareness"))==null?void 0:g.module)==null?void 0:_.getContextSnapshot)==null?void 0:m.call(_),s=r==null?void 0:r.subject;if(!(s!=null&&s.position)||i.center&&!lW(i.center,s.position))return null;const a=Number.isFinite(i.km)?i.km*1e3:r.radiusM||25e4,c=e.layers.get("military-awareness").module.collectAircraftProximityWindow(s.position,{radiusM:a,subject:s});if(!c)return null;const l=s.label||s.id||"the selected contact",u=Math.round(a/1e3),h=new Set(o),d=[...h.has("flights")?c.flights.map(C=>({...C,layerKey:"flights"})):[],...h.has("military")?c.military.map(C=>({...C,layerKey:"military"})):[]],f=d.length;return{ok:!0,action:"analyst_query",count:f,scopeLabel:`within ${u} km of ${l}`,truncated:!1,items:d.slice(0,Math.round(hu(t.limit,1,50,12))).map(C=>({layerKey:C.layerKey,id:C.id,...C.icao24?{icao24:C.icao24}:{},...C.callsign?{callsign:C.callsign}:{},...Number.isFinite(C.distance)?{distanceKm:Math.round(C.distance/100)/10}:{}})),summary:{count:f},coverage:{layersQueried:((b=n==null?void 0:n.coverage)==null?void 0:b.layersQueried)||[],scope:`window:${u}km@${l}`,followUp:!1,note:"Contacts window engine — the same computation and cohort the Contacts panel displays, so this count matches the panel exactly — counts cover loaded data; the flights layer loads by viewport."},window:{engine:"contacts-window",centeredOn:l,radiusKm:u,flights:c.flights.length,military:c.military.length,aircraft:c.aircraft},...zr(e)?{contactsWindow:zr(e)}:{}}}const aW=1;function lW(e,t){if(!Number.isFinite(e==null?void 0:e.lat)||!Number.isFinite(e==null?void 0:e.lon))return!1;const n=Cesium.Cartographic.fromCartesian(t);if(!n)return!1;const i=Cesium.Math.toDegrees(n.latitude),o=Cesium.Math.toDegrees(n.longitude);return pT(i,o,e.lat,e.lon)<=aW}function q0(e){return e<=1e5}function cW(e){const t=am({dataManager:e});return t?MT(t,{includeProperties:!0}):null}function uW(e,t,{layerId:n=null,limit:i=5,target:o=null}={}){var _,m,b;const r=[],s=e.scene.canvas,a=s.clientWidth||s.width||0,c=s.clientHeight||s.height||0,l=a/2,u=c/2,h=o?Cesium.Math.toDegrees(o.latitude):null,d=o?Cesium.Math.toDegrees(o.longitude):null,f=On(),p=new Set(t.getAll().filter(C=>C.enabled).map(C=>C.id));for(const C of f.entities.values())n&&C.layerId!==n||C.layerId&&!p.has(C.layerId)||((_=C.entity)==null?void 0:_.show)===!1||((m=C.dataSource)==null?void 0:m.show)===!1||!Number.isFinite(C.latitude)||!Number.isFinite(C.longitude)||dW(r,{record:C,distanceScore:o?vW(h,d,C.latitude,C.longitude):0},Tq);const g=[];for(const{record:C}of r){const y=(b=C.entity)==null?void 0:b.__localBaseCartesian;if(!y)continue;const v=Cesium.SceneTransforms.worldToWindowCoordinates(e.scene,y);if(!v||v.x<0||v.y<0||v.x>a||v.y>c)continue;const M=v.x-l,w=v.y-u;g.push({summary:MT(C,{includeProperties:!0}),distancePx:Math.sqrt(M*M+w*w)})}return g.sort((C,y)=>C.distancePx-y.distancePx).slice(0,i).map(C=>C.summary)}function dW(e,t,n){if(e.lengthr.distanceScore-s.distanceScore);return}if(t.distanceScore>=e[e.length-1].distanceScore)return;let i=0,o=e.length;for(;i>1;e[r].distanceScore<=t.distanceScore?i=r+1:o=r}e.splice(i,0,t),e.pop()}async function hW(e,t,n,i=null,o=No){const r=Cesium.Cartographic.fromCartesian(e.camera.positionWC),s=await fW(e,i,o),a=n.getAll().filter(c=>c.enabled).map(c=>{var l;return{id:c.id,name:c.name,count:((l=c.stats)==null?void 0:l.count)||0,source:c.source}});return{camera:{latitude:Number(Cesium.Math.toDegrees(r.latitude).toFixed(6)),longitude:Number(Cesium.Math.toDegrees(r.longitude).toFixed(6)),heightM:Math.round(r.height)},basemap:s,style:t.activeStyle||"normal",enabledLayers:a}}async function fW(e,t=null,n=No){var I,R;const{reverseGeocodeCache:i,nearbyPlacesCache:o}=ka(n),r=t,s=gT(e),c=Cesium.Cartographic.fromCartesian(e.camera.positionWC).height,l=mW(c),u=bT(s,c,n),h=u?Promise.resolve(u):_T(s,c,n);if(!r){const S=await _o(h,go,u);return{source:"Google Photorealistic 3D Tiles / Cesium basemap",hasGoogle3DTiles:!!((I=window.__godsEyeView)!=null&&I.tileset),viewScale:l,viewportSamples:s,viewportPlaces:S,target:null,place:null}}const d=Number(Cesium.Math.toDegrees(r.latitude).toFixed(6)),f=Number(Cesium.Math.toDegrees(r.longitude).toFixed(6)),p=bW(s),g=pW(d,f,c),_=gW(l,d,f,p),m=lf(c)&&i.get(du(d,f,n))||null,b=np(d,f,c,n),C=cf(c)&&o.has(b)?o.get(b):null,y=lf(c)&&!m?tp(d,f,n):Promise.resolve(m),v=cf(c)&&!C?yT(d,f,c,n):Promise.resolve(C),[M,w,E]=await Promise.all([_o(h,go,u),_o(y,go,m),_o(v,go,C)]),k=w||_,T=E||[];return{source:"Google Photorealistic 3D Tiles / Cesium basemap",hasGoogle3DTiles:!!((R=window.__godsEyeView)!=null&&R.tileset),viewScale:l,viewportSamples:s,viewportPlaces:M,target:{latitude:d,longitude:f,heightM:Math.round(r.height||0)},knownLandmarks:g,nearbyPlaces:T,place:k}}function mW(e){return e>12e6?"global":e>3e6?"continental":e>75e4?"regional":e>1e5?"metro":e>1e4?"city":"local"}function lf(e){return e<=75e4}function mT(e){return e<=3e6}function cf(e){return e<=25e3}function pW(e,t,n){if(!Number.isFinite(e)||!Number.isFinite(t))return[];const i=n<=5e3?2:n<=5e4?10:n<=25e4?35:0;if(i<=0)return[];const o=[];for(const[r,s]of Object.entries(Ot))for(let a=0;ai||o.push({name:c.name,cityId:r,city:s.name,latitude:c.lat,longitude:c.lon,distanceKm:Number(l.toFixed(3))})}return o.sort((r,s)=>r.distanceKm-s.distanceKm).slice(0,5)}function pT(e,t,n,i){const o=l=>Cesium.Math.toRadians(l),r=6371.0088,s=o(n-e),a=o(i-t),c=Math.sin(s/2)*Math.sin(s/2)+Math.cos(o(e))*Math.cos(o(n))*Math.sin(a/2)*Math.sin(a/2);return 2*r*Math.atan2(Math.sqrt(c),Math.sqrt(1-c))}function gW(e,t,n,i=null){return e==="global"?{formattedAddress:"Global Earth view",locality:null,region:null,country:null,precision:"global",note:"Camera is too far out for a precise street or city label; do not infer a local place from the center point."}:{formattedAddress:i!=null&&i.country?`${e[0].toUpperCase()}${e.slice(1)} basemap view over ${i.country}`:`${e[0].toUpperCase()}${e.slice(1)} basemap view centered near ${t.toFixed(2)}, ${n.toFixed(2)}`,locality:null,region:null,country:(i==null?void 0:i.country)||null,precision:e,confidence:(i==null?void 0:i.confidence)||null,note:"Camera altitude is high, so this is approximate basemap context rather than a precise address."}}function ep(e){const t=_W(e),n=G0.get(e);if((n==null?void 0:n.signature)===t&&performance.now()-n.cachedAt<2500)return n.target;const i=uu(e),o=i&&Cesium.Cartographic.fromCartesian(i)||null;return G0.set(e,{signature:t,target:o,cachedAt:performance.now()}),o}function _W(e){const t=e.camera,n=t.positionCartographic;return[Cesium.Math.toDegrees(n.latitude).toFixed(5),Cesium.Math.toDegrees(n.longitude).toFixed(5),Math.round(n.height/2),t.heading.toFixed(3),t.pitch.toFixed(3)].join(":")}function uu(e){var a;const t=e.scene,n=t.canvas,i=n.clientWidth||n.width||0,o=n.clientHeight||n.height||0,r=new Cesium.Cartesian2(i/2,o/2);let s=null;if(t.pickPositionSupported&&typeof t.pickPosition=="function")try{s=t.pickPosition(r)}catch{s=null}if(!zt(s)&&e.camera&&typeof e.camera.pickEllipsoid=="function")try{s=e.camera.pickEllipsoid(r,Cesium.Ellipsoid.WGS84)}catch{s=null}if(!zt(s)&&e.camera&&typeof e.camera.getPickRay=="function")try{const c=e.camera.getPickRay(r);s=((a=t.globe)==null?void 0:a.pick(c,t))||null}catch{s=null}return zt(s)?s:null}function gT(e){const n=e.scene.canvas,i=n.clientWidth||n.width||0,o=n.clientHeight||n.height||0;if(!i||!o)return[];const r=[[.5,.5],[.25,.35],[.75,.35],[.25,.65],[.75,.65],[.5,.25],[.5,.75]],s=[];for(const[a,c]of r){const l=e.camera.pickEllipsoid(new Cesium.Cartesian2(i*a,o*c),Cesium.Ellipsoid.WGS84);if(!zt(l))continue;const u=Cesium.Cartographic.fromCartesian(l);u&&s.push({latitude:Number(Cesium.Math.toDegrees(u.latitude).toFixed(4)),longitude:Number(Cesium.Math.toDegrees(u.longitude).toFixed(4))})}return s}function bW(e){if(!e.length)return null;const t=new Map;for(const o of e){const r=CW(o.latitude,o.longitude);r&&t.set(r,(t.get(r)||0)+1)}if(!t.size)return null;const[n,i]=[...t.entries()].sort((o,r)=>r[1]-o[1])[0];return{country:n,confidence:Number((i/e.length).toFixed(2)),sampleCount:i,totalSamples:e.length}}function CW(e,t){const i=[{name:"Iran",south:24,north:40.2,west:44,east:63.5},{name:"Iraq",south:29,north:37.5,west:38.5,east:49},{name:"Turkey",south:35.5,north:42.5,west:25.5,east:45.2},{name:"Saudi Arabia",south:16,north:32.5,west:34,east:56.5},{name:"Afghanistan",south:29,north:38.8,west:60,east:75.5},{name:"Pakistan",south:23,north:37.2,west:60.5,east:77.5},{name:"Turkmenistan",south:35,north:42.9,west:52,east:66.8},{name:"Azerbaijan",south:38.3,north:41.9,west:44.6,east:50.8},{name:"Armenia",south:38.7,north:41.4,west:43.4,east:46.7},{name:"Japan",south:24,north:46.5,west:122,east:146.5},{name:"South Korea",south:33,north:38.8,west:124,east:132},{name:"North Korea",south:37.5,north:43.2,west:124,east:131},{name:"China",south:18,north:53.8,west:73,east:135.2},{name:"Russia",south:41,north:82,west:19,east:180},{name:"United States",south:24,north:49.8,west:-125,east:-66}].find(o=>e>=o.south&&e<=o.north&&t>=o.west&&t<=o.east);return(i==null?void 0:i.name)||null}async function tp(e,t,n){const{reverseGeocodeCache:i,reverseGeocodeInFlight:o}=ka(n);if(!Number.isFinite(e)||!Number.isFinite(t))return null;const r=du(e,t,n);if(i.has(r))return i.get(r);if(o.has(r))return o.get(r);const s=(async()=>{var a;try{const c=await((a=n.reverseGeocode)==null?void 0:a.call(n,e,t))||null;return c&&(i.set(r,c),i.size>256&&i.delete(i.keys().next().value)),c}catch{return null}finally{o.delete(r)}})();return o.set(r,s),s}async function _T(e,t,n){if(!mT(t)||!e.length||t<=1e4)return null;const i=[e[0],e[1],e[2]].filter(Boolean),o=(await Promise.all(i.map(async r=>{const s=await tp(r.latitude,r.longitude,n);return s?{latitude:r.latitude,longitude:r.longitude,formattedAddress:s.formattedAddress,locality:s.locality,region:s.region,country:s.country,types:s.types,labels:s.labels,streetLabels:s.streetLabels}:null}))).filter(Boolean);return CT(o)}function bT(e,t,n){const{reverseGeocodeCache:i}=ka(n);if(!mT(t)||t<=1e4||!e.length)return null;const o=[e[0],e[1],e[2]].filter(Boolean).flatMap(r=>{const s=i.get(du(r.latitude,r.longitude,n));return s?[{latitude:r.latitude,longitude:r.longitude,formattedAddress:s.formattedAddress,locality:s.locality,region:s.region,country:s.country,types:s.types,labels:s.labels,streetLabels:s.streetLabels}]:[]});return CT(o)}function CT(e){return e.length?{samples:e,dominantCountry:wd(e.map(t=>t.country).filter(Boolean)),dominantRegion:wd(e.map(t=>t.region).filter(Boolean)),dominantLocality:wd(e.map(t=>t.locality).filter(Boolean)),visibleLabels:Us(e.flatMap(t=>t.labels||[])).slice(0,24),streetLabels:Us(e.flatMap(t=>t.streetLabels||[])).slice(0,20)}:null}async function yT(e,t,n,i){const{nearbyPlacesCache:o,nearbyPlacesInFlight:r}=ka(i),s=vT(n),a=np(e,t,n,i);if(o.has(a))return o.get(a);if(r.has(a))return r.get(a);const c=(async()=>{var l;try{const u=(await((l=i.nearby)==null?void 0:l.call(i,{latitude:e,longitude:t,radiusM:s}))||[]).filter(h=>h==null?void 0:h.name).slice(0,12);return o.set(a,u),o.size>256&&o.delete(o.keys().next().value),u}catch{return[]}finally{r.delete(a)}})();return r.set(a,c),c}function Us(e){return[...new Set(e.map(t=>yW(t)).filter(Boolean))]}function yW(e){const t=String(e||"");let n="";for(const i of t){const o=i.codePointAt(0);n+=o<32||o===127?" ":i}return n.replace(/\s+/g," ").trim().slice(0,120)}function kc(e){return Number.isInteger(e==null?void 0:e.cachePrecision)?Math.max(3,Math.min(6,e.cachePrecision)):4}function du(e,t,n){return`${e.toFixed(kc(n))},${t.toFixed(kc(n))}`}function np(e,t,n,i){const o=vT(n);return`${e.toFixed(kc(i))},${t.toFixed(kc(i))},${o}`}function vT(e){return e<=1e3?500:e<=5e3?2e3:5e3}async function _o(e,t,n){let i=null;try{return await Promise.race([Promise.resolve(e).catch(()=>n),new Promise(o=>{i=window.setTimeout(()=>o(n),t)})])}finally{i&&window.clearTimeout(i)}}function vW(e,t,n,i){const o=n-e,r=(i-t)*Math.cos(Cesium.Math.toRadians((e+n)/2));return o*o+r*r}function W0(e,t){const n=Math.round(performance.now()-e);n>=500&&console.info(`[GEV Voice] ${t} scene context completed in ${n}ms`)}function wd(e){if(!e.length)return null;const t=new Map;for(const o of e)t.set(o,(t.get(o)||0)+1);const[n,i]=[...t.entries()].sort((o,r)=>r[1]-o[1])[0];return{value:n,count:i,confidence:Number((i/e.length).toFixed(2))}}function MT(e,{includeProperties:t=!1}={}){var n;return{id:String(e.id||""),name:uf(e.label||((n=e.properties)==null?void 0:n.name))||K0(e.layerId),layerId:e.layerId||null,layerName:e.layerName||K0(e.layerId),source:e.source||null,latitude:e.latitude??null,longitude:e.longitude??null,properties:t?MW(e.properties||{}):void 0,active:lm(e)}}function MW(e){const t=["name","operator","owner","brand","addr:city","addr:state","country","capacity","output","osm_id","source"],n={...e,...e.tags&&typeof e.tags=="object"?e.tags:{}},i={};for(const o of t){const r=uf(n[o]);r&&(i[o]=r)}for(const[o,r]of Object.entries(n)){if(Object.keys(i).length>=12)break;if(o==="tags"||i[o]!==void 0)continue;const s=uf(r);s&&(i[o]=s)}return i}function uf(e){if(e==null||typeof e=="object")return"";const t=String(e).trim();return!t||t==="undefined"||t==="null"?"":t.length>180?`${t.slice(0,177)}...`:t}function K0(e){return e==="local-datacenters"?"Datacenter":e==="local-dams"?"Dam":e==="telegeography-submarine-cables"?"Submarine Cable":e==="local-firms"?"Active Fire":e||"Entity"}function hu(e,t,n,i){const o=Number(e);return Number.isFinite(o)?Math.max(t,Math.min(n,o)):i}const wW=new Set(["flights"]);function zr(e){var t,n,i,o;try{const r=(n=(t=e==null?void 0:e.layers)==null?void 0:t.get("military-awareness"))==null?void 0:n.module;return((o=r==null?void 0:r.contactsWindowFromSnapshot)==null?void 0:o.call(r,(i=r.getContextSnapshot)==null?void 0:i.call(r)))??null}catch{return null}}function Y0(e,t,{recordLimitByLayer:n=null,placeSearch:i=So,resolveRegionRing:o=r=>qM(r,void 0,i)}={}){return{getRecords(r){const s=t.layers.get(r);if(!s||!t.isEnabled(r))return[];const a=s.module;if(typeof(a==null?void 0:a.getAnalystRecords)!="function")return[];const c=n==null?void 0:n[r];return Number.isFinite(c)?a.getAnalystRecords(c)||[]:a.getAnalystRecords()||[]},resolveRegionRing:o,getContextSubject(){var c,l,u,h;const r=(h=(u=(l=(c=t==null?void 0:t.layers)==null?void 0:c.get("military-awareness"))==null?void 0:l.module)==null?void 0:u.getContextSnapshot)==null?void 0:h.call(u),s=r==null?void 0:r.subject;if(!(s!=null&&s.position))return null;const a=Cesium.Cartographic.fromCartesian(s.position);return a?{lat:Cesium.Math.toDegrees(a.latitude),lon:Cesium.Math.toDegrees(a.longitude),label:s.label||s.id||null}:null},getViewContext(){const r=e.camera.positionCartographic,s=r.height/1e3,a=Math.max(25,Math.min(2500,s*1.6));return{lat:Cesium.Math.toDegrees(r.latitude),lon:Cesium.Math.toDegrees(r.longitude),viewRadiusKm:a}}}}async function EW(e,t,n={},i){var g,_,m,b;const o=await e.query({layers:Array.isArray(n.layers)?n.layers:void 0,scope:n.scope,filters:Array.isArray(n.filters)?n.filters:[],sortBy:n.sortBy||null,sortDir:n.sortDir,limit:n.limit,followUp:!!n.followUp});if(!o.ok)return{ok:!1,action:"analyst_query",error:o.error,coverage:o.coverage};const r=o.items.map(C=>{const y={layerKey:C.layerKey,id:C.id};for(const v of["icao24","mmsi","registration","label","callsign","name","altitudeM","speedMps","speedKts","frp","magnitude","shipType","destination","operator","routeOrigin","routeDestination","aircraftClass","military","onGround","distanceKm","confidence","place"])C[v]!==null&&C[v]!==void 0&&(y[v]=C[v]);return y}),s=(((g=o.coverage)==null?void 0:g.layersQueried)||[]).filter(C=>{const y=i.get(C.layerKey);return y&&Date.now()-y<45e3}).map(C=>C.layerKey);s.length&&(o.coverage.warmup=`${s.join(", ")} enabled moments ago — data is still loading; counts will rise for ~30-45s. Say so.`);const a=String(((_=n.scope)==null?void 0:_.kind)||"view").toLowerCase();(a==="radius"||a==="view")&&(((m=o.coverage)==null?void 0:m.layersQueried)||[]).some(C=>wW.has(C.layerKey))&&o.coverage&&(o.coverage.note=`${o.coverage.note} — counts cover loaded data; the flights layer loads by viewport`);const l=sW(t,n,o);if(l)return l;const u=zr(t),h=(((b=o.coverage)==null?void 0:b.layersQueried)||[]).some(C=>C.layerKey==="flights"||C.layerKey==="military"),d=Number.isFinite(u==null?void 0:u.aircraft)?u.aircraft:null,p=u&&h&&(a==="radius"||a==="view")&&d!==null?`Contacts is ACTIVE: its window holds ${d} aircraft within ${u.radiusKm} km of ${u.centeredOn}, and that is the answer to a bare "how many aircraft are nearby". This query measured something else — ${o.count} ${o.scopeLabel}. Give this one only if the operator asked about that specific area, and name both scopes if you give both.`:null;return{ok:!0,action:"analyst_query",count:o.count,scopeLabel:o.scopeLabel,truncated:o.truncated,items:r,summary:o.summary,coverage:o.coverage,...u&&h?{contactsWindow:u,contactsWindowCount:d,contactsWindowSubject:u.centeredOn||null}:{},...p?{countsReconciliation:p}:{}}}const TW="OPENAI_NOT_CONFIGURED";function kW(e,t){return(t!==null&&typeof t=="object"&&!Array.isArray(t)?Object.keys(t):[]).length===4&&e===200&&(t==null?void 0:t.configured)===!1&&(t==null?void 0:t.code)===TW&&(t==null?void 0:t.error)===null&&(t==null?void 0:t.summary)===null}const X0={surveillance:{main:"rgba(51, 255, 51, 0.8)",glow:"rgba(51, 255, 51, 0.5)",border:"rgba(51, 255, 51, 0.2)"},thermal:{main:"rgba(255, 255, 255, 0.7)",glow:"rgba(255, 255, 255, 0.4)",border:"rgba(255, 255, 255, 0.15)"},retro:{main:"rgba(255, 170, 0, 0.8)",glow:"rgba(255, 170, 0, 0.5)",border:"rgba(255, 170, 0, 0.2)"},_default:{main:"rgba(0, 255, 255, 0.6)",glow:"rgba(0, 255, 255, 0.4)",border:"rgba(0, 255, 255, 0.15)"}},AW=new Set(["retro","surveillance","thermal"]),IW=new Set(["tactical","operator","minimal"]),RW=15e3,Q0=.01,LW=Object.values(Ot).flatMap(e=>e.pois.map(t=>({city:e.name,poi:t.name,lat:t.lat,lon:t.lon})));class PW{constructor(t,{placeSearch:n,summaryPolicy:i={},basemapContext:o={},summaryService:r=ts.summary}={}){this.summaryService=r,this.summaryPolicy=i,this.basemapContext=o,this.placeSearch=n,this.viewer=t,this._visible=!1,this._autoMode=!0,this._currentStyle="normal",this._el=null,this._variant="tactical",this._recBlinkState=!0,this._updateInterval=null,this._recBlinkInterval=null,this._timestampInterval=null,this._summaryInterval=null,this._summaryTypingInterval=null,this._latestMetrics=null,this._dataManager=null,this._dataManagerUnsubscribe=null,this._summaryDirty=!0,this._summaryRequest=null,this._lastSummarySignature="",this._summaryRevision=0,this._firstMetricsShown=!1,this._firstSummaryKicked=!1,this._geoidRequested=!1,this._geoidReady=!1,this._geoidCellKey=null,this._geoidN=null,this._geoidCorrectionApplied=!1,this._onCameraMoveEnd=()=>{this._markSummaryDirty(),this._visible&&(this._updateCameraData(),this._setSummaryText(this._composeSummary(),!1)),!this._firstSummaryKicked&&this._visible&&this._latestMetrics&&(this._firstSummaryKicked=!0,this._updateSummary(!0,!0))},this._missionId=`KH11-${4e3+Math.floor(Math.random()*200)}`,this._sensorId=`OPS-${4100+Math.floor(Math.random()*100)}`,this._orbitNum=47e3+Math.floor(Math.random()*1e3),this._passNum=100+Math.floor(Math.random()*200),this._buildDOM(),this.viewer.camera.moveEnd.addEventListener(this._onCameraMoveEnd),this._startTimers()}_buildDOM(){this._el=document.getElementById("intel-hud"),this._el&&(this._el.innerHTML=` +
    + TOP SECRET // SI-TK // NOFORN + ${this._missionId} + PAGE 1/1 +
    + +
    +
    ┌
    +
    +
    TOP SECRET // SI-TK // NOFORN
    +
    ${this._missionId} ${this._sensorId}
    +
    NORMAL
    +
    +
    SUMMARY
    +
    Awaiting telemetry...
    +
    +
    +
    + +
    +
    +
    ● REC 2026-01-01 00:00:00Z
    +
    ORB: ${this._orbitNum} PASS: DESC-${this._passNum}
    +
    +
    ┐
    +
    + +
    +
    └
    +
    +
    MGRS: ---
    +
    --°--'--"N ---°--'--"W
    +
    +
    + +
    +
    +
    GSD: --m NIIRS: --
    +
    ALT: --m SUN: --° EL
    +
    AIS: --
    +
    +
    ┘
    +
    + +
    +
    COLL: --:--:--Z
    +
    ONA: --°
    +
    + +
    +
    BAND: PAN
    +
    BITS: 11
    +
    LVL: 1A
    +
    + +
    + LAT: -- LON: -- MGRS: --- +
    + `,this._el.dataset.variant=this._variant)}_startTimers(){this._timestampInterval=setInterval(()=>{const t=document.getElementById("hud-timestamp");t&&(t.textContent=this._formatUTC())},1e3),this._recBlinkInterval=setInterval(()=>{this._recBlinkState=!this._recBlinkState;const t=document.getElementById("hud-rec-dot");t&&(t.style.visibility=this._recBlinkState?"visible":"hidden")},800),this._updateInterval=setInterval(()=>{this._visible&&this._updateCameraData()},250),this._summaryInterval=setInterval(()=>{this._visible&&this._updateSummary(!0)},RW)}_formatUTC(){const t=new Date,n=t.getUTCFullYear(),i=String(t.getUTCMonth()+1).padStart(2,"0"),o=String(t.getUTCDate()).padStart(2,"0"),r=String(t.getUTCHours()).padStart(2,"0"),s=String(t.getUTCMinutes()).padStart(2,"0"),a=String(t.getUTCSeconds()).padStart(2,"0");return`${n}-${i}-${o} ${r}:${s}:${a}Z`}_geoidUndulationM(t,n){if(!this._geoidReady)return this._geoidRequested||(this._geoidRequested=!0,Mf().then(()=>{this._geoidReady=!0}).catch(()=>{})),null;const i=`${Math.round(t/Q0)}:${Math.round(n/Q0)}`;if(i!==this._geoidCellKey){try{this._geoidN=Hc(t,n)}catch{this._geoidN=null}this._geoidCellKey=i}return Number.isFinite(this._geoidN)?this._geoidN:null}_updateCameraData(){const t=this.viewer.camera,n=t.positionCartographic;if(!n)return;const i=Cesium.Math.toDegrees(n.longitude),o=Cesium.Math.toDegrees(n.latitude),r=n.height,s=this._toDMS(o,"lat"),a=this._toDMS(i,"lon");let c="---";try{const E=aq([i,o],4),k=this._formatMGRS(E);c=k;const T=document.getElementById("hud-mgrs");T&&(T.textContent=`MGRS: ${k}`)}catch{const E=document.getElementById("hud-mgrs");E&&(E.textContent="MGRS: ---")}const l=document.getElementById("hud-latlon");l&&(l.textContent=`${s} ${a}`);const u=document.getElementById("hud-bottom-line");u&&(u.textContent=`MGRS: ${c} LAT: ${s} LON: ${a}`);const h=Math.max(.01,r*375e-6),d=h*39.37,f=Math.max(0,Math.min(9,10.25-3.32*Math.log10(d))),p=document.getElementById("hud-gsd");p&&(p.textContent=`GSD: ${h.toFixed(2)}m NIIRS: ${f.toFixed(1)}`);const g=document.getElementById("hud-alt"),_=this._geoidUndulationM(o,i),m=$C(r,_),b=this._estimateSunElevation(o,i);g&&(g.textContent=`ALT: ${Math.round(m)}m SUN: ${b.toFixed(1)}° EL`);const C=document.getElementById("hud-coll");if(C){const E=new Date,k=String(E.getUTCHours()).padStart(2,"0"),T=String(E.getUTCMinutes()).padStart(2,"0"),I=String(E.getUTCSeconds()).padStart(2,"0");C.textContent=`COLL: ${k}:${T}:${I}Z`}const y=Cesium.Math.toDegrees(t.pitch),v=Math.max(0,90+y),M=document.getElementById("hud-ona");M&&(M.textContent=`ONA: ${v.toFixed(1)}°`),this._latestMetrics={latDeg:o,lonDeg:i,altM:r,altMslM:m,sunEl:b,ona:v},this._firstMetricsShown||(this._firstMetricsShown=!0,this._setSummaryText(this._composeSummary(),!1));const w=Number.isFinite(_);w!==this._geoidCorrectionApplied&&(this._geoidCorrectionApplied=w,this._markSummaryDirty(),this._setSummaryText(this._composeSummary(),!1))}_formatMGRS(t){const n=t.match(/^(\d{1,2}[A-Z])\s*([A-Z]{2})\s*(\d+)$/);if(!n)return t;const[,i,o,r]=n,s=r.length/2,a=r.slice(0,s),c=r.slice(s);return`${i} ${o} ${a} ${c}`}_toDMS(t,n){const i=Math.abs(t),o=Math.floor(i),r=(i-o)*60,s=Math.floor(r),a=((r-s)*60).toFixed(2);let c;return n==="lat"?c=t>=0?"N":"S":c=t>=0?"E":"W",`${n==="lon"?String(o).padStart(3,"0"):String(o).padStart(2,"0")}°${String(s).padStart(2,"0")}'${String(a).padStart(5,"0")}"${c}`}_estimateSunElevation(t,n){const i=new Date,s=(i.getUTCHours()+i.getUTCMinutes()/60+n/15-12)*15,a=23.45*Math.sin(Cesium.Math.toRadians(360/365*(i.getUTCDate()+30*i.getUTCMonth()-81))),c=Cesium.Math.toRadians(t),l=Cesium.Math.toRadians(a),u=Cesium.Math.toRadians(s),h=Math.sin(c)*Math.sin(l)+Math.cos(c)*Math.cos(l)*Math.cos(u);return Cesium.Math.toDegrees(Math.asin(Math.max(-1,Math.min(1,h))))}_viewBand(t){return t<1200?"STREET":t<5e3?"CITY":t<3e4?"METRO":t<25e4?"REGIONAL":"GLOBAL"}_regionLabel(t,n){return t>72?"ARCTIC":t<-60?"ANTARCTIC":t>=5&&t<=83&&n>=-170&&n<=-50?"NORTH AMERICA":t>=-60&&t<=15&&n>=-90&&n<=-30?"SOUTH AMERICA":t>=34&&t<=72&&n>=-25&&n<=45?"EUROPE":t>=-35&&t<=38&&n>=-20&&n<=55?"AFRICA":t>=5&&t<=80&&n>=45&&n<=180?"ASIA":t>=-50&&t<=5&&n>=110&&n<=180?"OCEANIA":t>=0?"NORTHERN OCEANIC GRID":"SOUTHERN OCEANIC GRID"}_viewWindowKm(t){const n=this.viewer.camera.computeViewRectangle();if(!n)return null;const i=Cesium.Math.toDegrees(n.north),o=Cesium.Math.toDegrees(n.south);let r=Cesium.Math.toDegrees(n.east),s=Cesium.Math.toDegrees(n.west),a=Math.abs(r-s);a>180&&(a=360-a);const c=Math.abs(i-o),l=Math.max(0,a*111*Math.cos(Cesium.Math.toRadians(t))),u=Math.max(0,c*111);return{widthKm:l,heightKm:u}}_haversineKm(t,n,i,o){const r=l=>Cesium.Math.toRadians(l),s=r(i-t),a=r(o-n),c=Math.sin(s/2)**2+Math.cos(r(t))*Math.cos(r(i))*Math.sin(a/2)**2;return 6371*2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c))}_nearestKnownPoint(t,n){let i=null;for(const o of LW){const r=this._haversineKm(t,n,o.lat,o.lon);(!i||r=0?"+":""}${c}`,u=Number.isFinite(t.altMslM)?t.altMslM:t.altM,h=u>=1e3?`${(u/1e3).toFixed(1)}KM`:`${Math.round(u)}M`,d=a?`${Math.max(1,Math.round(a.widthKm))}x${Math.max(1,Math.round(a.heightKm))}KM`:"N/A",f=dq(r,t.latDeg,t.lonDeg);return`${i} ${s} ${f} | ${o} | ALT ${h} | WINDOW ${d} | SUN ${t.sunEl.toFixed(0)}° | ONA ${t.ona.toFixed(0)}° | ${l}`}_typeSummary(t){const n=document.getElementById("hud-summary");if(!n)return;clearInterval(this._summaryTypingInterval);let i=0;n.textContent="",this._summaryTypingInterval=setInterval(()=>{if(i+=2,i>=t.length){n.textContent=t,clearInterval(this._summaryTypingInterval),this._summaryTypingInterval=null;return}n.textContent=t.slice(0,i)},24)}async _updateSummary(t=!1,n=!1){var l,u,h,d;const i=this._composeSummary();if(!this._latestMetrics){this._setSummaryText(i,t);return}if(!n&&!this._summaryDirty||((u=(l=this.summaryPolicy).canRequest)==null?void 0:u.call(l))===!1)return;const o=this._summaryRevision;let r;try{r=await this._summaryContext()}catch(f){console.warn("[HUD] summary context unavailable:",f),this._setSummaryText(i,t);return}if(o!==this._summaryRevision)return;const s=JSON.stringify(r);if(!n&&s===this._lastSummarySignature){this._summaryDirty=!1;return}if(this._summaryRequest)return;n&&this._setSummaryText(i,!1),this._summaryDirty=!1,this._lastSummarySignature=s;const a=new AbortController,c=window.setTimeout(()=>a.abort(),5e3);this._summaryRequest=a;try{(d=(h=this.summaryPolicy).onRequest)==null||d.call(h);const f=await this.summaryService.summarize(r,{signal:a.signal}),p=f.data;if(o!==this._summaryRevision)return;if(kW(f.status,p)){this._setSummaryText(i,t);return}if(!f.ok||!(p!=null&&p.summary))throw new Error((p==null?void 0:p.error)||`HTTP ${f.status}`);this._setSummaryText(p.summary,t)}catch(f){(f==null?void 0:f.name)!=="AbortError"&&(console.warn("[HUD] AI summary unavailable:",f),this._lastSummarySignature=null,this._summaryDirty=!0),this._setSummaryText(i,t)}finally{window.clearTimeout(c),this._summaryRequest===a&&(this._summaryRequest=null)}}_setSummaryText(t,n){if(n){this._typeSummary(t);return}const i=document.getElementById("hud-summary");i&&(i.textContent=t)}async _summaryContext(){var i,o,r;const t=await Uq(this.viewer,this.placeSearch,this.basemapContext),n=((r=(o=(i=this._dataManager)==null?void 0:i.getAll)==null?void 0:o.call(i))==null?void 0:r.filter(s=>s.enabled).map(s=>s.name))||[];return{placeLabels:t.placeLabels,streetLabels:t.streetLabels,nearbyPlaceLabels:t.nearbyPlaceLabels,enabledLayerLabels:n}}_markSummaryDirty(){this._summaryDirty=!0,this._summaryRevision++}onStyleChange(t){this._currentStyle=t;const n=document.getElementById("hud-mode");if(n){const o={surveillance:"NVG",thermal:"FLIR",retro:"CRT"};n.textContent=o[t]||t.toUpperCase()}const i=X0[t]||X0._default;this._el&&(this._el.style.setProperty("--hud-color",i.main),this._el.style.setProperty("--hud-glow",i.glow),this._el.style.setProperty("--hud-border",i.border)),this._autoMode&&(AW.has(t)?this.show():this.hide())}show(){this._visible=!0,this._el&&this._el.classList.add("active"),this._updateCameraData(),this._markSummaryDirty(),this._updateSummary(!1,!0)}hide(){this._visible=!1,this._el&&this._el.classList.remove("active")}toggle(){this._visible?(this._autoMode=!1,this.hide()):(this._autoMode=!1,this.show())}setMode(t){if(t==="auto"){this._autoMode=!0,this.onStyleChange(this._currentStyle);return}this._autoMode=!1,t==="on"?this.show():this.hide()}setVariant(t){const n=String(t||"").toLowerCase();this._variant=IW.has(n)?n:"tactical",this._el&&(this._el.dataset.variant=this._variant)}getVariant(){return this._variant}getMode(){return this._autoMode?"auto":this._visible?"on":"off"}get visible(){return this._visible}attachDataManager(t){var n;this._dataManagerUnsubscribe&&(this._dataManagerUnsubscribe(),this._dataManagerUnsubscribe=null),this._dataManager=t||null,typeof((n=this._dataManager)==null?void 0:n.subscribe)=="function"&&(this._dataManagerUnsubscribe=this._dataManager.subscribe(i=>{(i==null?void 0:i.type)==="visibility"&&this._markSummaryDirty()})),this._markSummaryDirty()}destroy(){var t,n;clearInterval(this._updateInterval),clearInterval(this._recBlinkInterval),clearInterval(this._timestampInterval),clearInterval(this._summaryInterval),clearInterval(this._summaryTypingInterval),this.viewer.camera.moveEnd.removeEventListener(this._onCameraMoveEnd),(t=this._dataManagerUnsubscribe)==null||t.call(this),(n=this._summaryRequest)==null||n.abort()}}const xW={r:5,g:5,b:8},FW=.11,bo=.94,SW=Math.round(bo*100),NW=100,Z0=1,Ed=1e7,J0=7e6,eC=.005,DW=120;let At=null,Ro=null,zs=null,Oo=!0,fu=FW,gr=null,to=null,Co=null,qi=bo,Bo=null,Ml=null,wl=null,Ac=-1/0,sr=!1,El=!1,Tl=!1;function wT(e){const t=Number(e);if(!Number.isFinite(t)||t>=Ed)return bo;if(t<=J0)return Z0;const n=(Ed-t)/(Ed-J0),i=n*n*(3-2*n);return bo+(Z0-bo)*i}function ET(e){const t=Math.max(0,Math.min(1,Number(e)||0));return Math.round(Math.round(t/eC)*eC*1e3)/1e3}function kl(e){const t=typeof e=="string"?e.trim():e;if(typeof t!="number"&&(typeof t!="string"||t===""))return null;const n=Number(t);return Number.isFinite(n)?Math.max(SW,Math.min(NW,Math.round(n))):null}function df(e){const t=ET(Bo??wT(e));return t===qi?!1:(qi=t,Wi(),!0)}function OW(e){if(Tl){e();return}Tl=!0,El=!1;try{e()}finally{Tl=!1,El&&(El=!1,Wi())}}function ip(){return ET(Bo??wT(Ic()))}function BW(e){e==null||!Number.isFinite(Number(e))?Bo=null:Bo=Math.max(bo,Math.min(1,Number(e)));const t=ip();t!==qi&&(qi=t),Wi()}function VW(){return Bo}function HW(e=typeof window<"u"?window.devicePixelRatio:1){return Math.min(2,Number(e)||1)}function TT(){if(typeof window>"u"||typeof window.matchMedia!="function")return;kT();const e=window.devicePixelRatio||1;let t;try{t=window.matchMedia(`(resolution: ${e}dppx)`)}catch{return}to=t,Co=()=>{OW(()=>{TT(),Oo&&df(Ic()),Wi()})},typeof t.addEventListener=="function"?t.addEventListener("change",Co,{once:!0}):typeof t.addListener=="function"&&t.addListener(Co)}function kT(){to&&Co&&(typeof to.removeEventListener=="function"?to.removeEventListener("change",Co):typeof to.removeListener=="function"&&to.removeListener(Co)),to=null,Co=null}function $W(e,t,n=fu){const i=es(e,t);if(!(i.radius>0))return null;const o=Math.max(0,Math.min(1,Number(n)||0)),r=i.radius*o*.5;return{centerX:i.centerX,centerY:i.centerY,innerR:Math.max(0,i.radius-r),outerR:i.radius+r,maxR:Math.hypot(Math.max(i.centerX,e-i.centerX),Math.max(i.centerY,t-i.centerY))}}function Wi(){if(Tl){El=!0;return}if(!At||!Ro)return;if(!Oo){if(!sr)return;const l=At.getContext("2d");l&&(l.setTransform(1,0,0,1,0,0),l.clearRect(0,0,At.width,At.height)),sr=!1;return}const e=Ro.clientWidth,t=Ro.clientHeight;if(!(e>0)||!(t>0))return;const n=HW();At.width=Math.round(e*n),At.height=Math.round(t*n);const i=At.getContext("2d");if(!i)return;i.setTransform(n,0,0,n,0,0),i.clearRect(0,0,e,t),sr=!1;const o=$W(e,t,fu);if(!o)return;const{r,g:s,b:a}=xW;if(o.outerR-o.innerR<1){i.fillStyle=`rgba(${r},${s},${a},${qi})`,i.beginPath(),i.rect(0,0,e,t),i.arc(o.centerX,o.centerY,Math.max(1,o.innerR),0,Math.PI*2),i.fill("evenodd"),sr=!0;return}const c=i.createRadialGradient(o.centerX,o.centerY,o.innerR,o.centerX,o.centerY,o.outerR);c.addColorStop(0,`rgba(${r},${s},${a},0)`),c.addColorStop(1,`rgba(${r},${s},${a},${qi})`),i.fillStyle=c,i.fillRect(0,0,e,t),sr=!0}function GW(e){At||!(e!=null&&e.container)||(Ro=e.container,zs=e,At=document.createElement("canvas"),At.id="scope-mask",At.setAttribute("aria-hidden","true"),Ro.appendChild(At),gr=new ResizeObserver(()=>Wi()),gr.observe(Ro),TT(),UW(e),qi=ip(),Wi())}function Ic(){var t,n;const e=(n=(t=zs==null?void 0:zs.camera)==null?void 0:t.positionCartographic)==null?void 0:n.height;return Number.isFinite(e)?e:Number.POSITIVE_INFINITY}function UW(e){var i,o;const t=(i=e==null?void 0:e.scene)==null?void 0:i.preRender;t!=null&&t.addEventListener&&(Ml=t.addEventListener(()=>{if(!Oo)return;const r=typeof performance<"u"?performance.now():Date.now();r-Ac{Oo&&df(Ic())}))}function zW(){Ml&&(Ml(),Ml=null),wl&&(wl(),wl=null),Ac=-1/0}function jW(e){const t=!!e,n=t&&!Oo;Oo=t,n&&(Ac=-1/0,qi=ip()),Wi()}function qW(){return Oo}function WW(e){fu=Math.max(0,Math.min(1,Number(e)||0)),Wi()}function KW(){return fu}function YW(){gr==null||gr.disconnect(),gr=null,kT(),zW(),At==null||At.remove(),At=null,Ro=null,zs=null,sr=!1}const XW=500,QW=50,AT={normal:"normal",retro:"crt",surveillance:"nvg",thermal:"flir",anime:"anime",noir:"noir",snow:"snow"},js="ui",qs="sp",hf="at",IT=Object.freeze([{id:"control-panel",token:"c",pinnable:!0},{id:"location-bar",token:"l",pinnable:!0},{id:"data-panel",token:"d",pinnable:!1},{id:"cctv-panel",token:"v",pinnable:!1},{id:"radio-panel",token:"r",pinnable:!1},{id:"scene-panel",token:"s",pinnable:!1},{id:"global-context-panel",token:"g",pinnable:!1},{id:"pp-toggles",token:"p",pinnable:!1},{id:"param-slider-panel",token:"m",pinnable:!1}]),ZW=Object.freeze(new Map(IT.map(e=>[e.token,e]))),JW=Object.fromEntries(Object.entries(AT).map(([e,t])=>[t,e])),RT=Object.freeze({retro:Object.freeze([{key:"pixelation",token:"p",min:1,max:10},{key:"distortion",token:"d",min:0,max:1},{key:"instability",token:"i",min:0,max:1}]),surveillance:Object.freeze([{key:"gain",token:"g",min:0,max:1},{key:"bloom",token:"b",min:0,max:1},{key:"scanlineStr",token:"s",min:0,max:1},{key:"pixelation",token:"p",min:1,max:6}]),thermal:Object.freeze([{key:"sensitivity",token:"s",min:0,max:1},{key:"bloom",token:"b",min:0,max:1},{key:"mode",token:"m",min:0,max:1},{key:"pixelation",token:"p",min:1,max:6},{key:"palette",token:"a",min:0,max:1}]),anime:Object.freeze([{key:"saturation",token:"s",min:0,max:2},{key:"edgeThick",token:"e",min:0,max:1}]),noir:Object.freeze([{key:"contrastAmt",token:"c",min:0,max:2},{key:"grainAmt",token:"g",min:0,max:1},{key:"vignetteAmt",token:"v",min:0,max:1}]),snow:Object.freeze([{key:"density",token:"d",min:0,max:1},{key:"wind",token:"w",min:0,max:1}])});class eK{constructor(t,{onRestore:n,isNavigationCurrent:i,cancelOwnedNavigation:o}={}){this.viewer=t,this._onRestore=n,this._debounceTimer=null,this._currentStyle="normal",this._bloomEnabled=!1,this._sharpenEnabled=!1,this._bloomIntensity=oi,this._bloomVersion=ti,this._sharpenIntensity=49,this._hudVariant="tactical",this._hudVisible=!1,this._detectionMode="OFF",this._detectionDensity=50,this._detectionAllocation="ELASTIC",this._detectionFadePct=7,this._detectionOutsideOpacityPct=1,this._celestialRingEnabled=!1,this._scopeEnabled=!0,this._scopeFeatherPct=11,this._scopeTerminusPct=null,this._mapStack="photoreal",this._layerStateProvider=null,this._panelStateProvider=null,this._styleParamStateProvider=null,this._initialRestorePending=!1,this._restoreAuthority={visual:0,map:0,panels:new Map},this._destroyed=!1,this._restoreGeneration=0,this._activeCameraFlight=null,this._isNavigationCurrent=typeof i=="function"?i:()=>!0,this._cancelOwnedNavigation=typeof o=="function"?o:null,this._removeCameraChanged=this.viewer.camera.changed.addEventListener(()=>{this._scheduleUpdate()})}parseInitialHash(){const t=window.location.hash.slice(1);if(!t)return null;const n=new URLSearchParams(t),i=parseFloat(n.get("lat")),o=parseFloat(n.get("lon"));if(!Number.isFinite(i)||!Number.isFinite(o))return null;const r=(u,h)=>{const d=parseFloat(u);return Number.isFinite(d)?d:h},s=tL(n.get("dm")||"OFF",r(n.get("dd"),50),50),a=JW[n.get("style")]||"normal",c=XC(n),l={lat:i,lon:o,alt:r(n.get("alt"),800),heading:r(n.get("heading"),0),pitch:r(n.get("pitch"),-35),roll:r(n.get("roll"),0),style:a,styleParams:iK(n,a),bloom:n.get("bloom")==="1",sharpen:n.get("sharpen")==="1",bloomIntensity:r(n.get("bi"),QW),bloomVersion:r(n.get("bv"),1),sharpenIntensity:r(n.get("si"),49),hudVariant:n.get("hud")||"tactical",hudVisible:n.get("hv")==="1",detectionMode:s.enabled?s.profile:"OFF",detectionDensity:s.densityPct,detectionAllocation:xo(n.get("da")),detectionFadePct:Math.max(0,Math.min(40,Math.round(r(n.get("kf"),16)))),detectionOutsideOpacityPct:Math.max(0,Math.min(100,Math.round(r(n.get("ko"),5)))),celestialRing:n.has("cr")?n.get("cr")==="1":!1,scopeEnabled:n.has("sc")?n.get("sc")==="1":!0,scopeFeatherPct:Math.max(0,Math.min(100,Math.round(r(n.get("scf"),35)))),scopeTerminusPct:n.has("sce")?kl(n.get("sce")):null,mapStack:n.get("map")||"photoreal",layerState:c,layerStateInvalid:n.get("v")==="2"&&n.has("l")&&c===null,panelState:oK(n),sharedAtMs:tK(n)};return l.restoreAuthority={visual:this._restoreAuthority.visual,map:this._restoreAuthority.map,panels:new Map(this._restoreAuthority.panels)},this._initialRestorePending=!0,l}async applyState(t,{applyCamera:n=!0,navigationToken:i=null}={}){if(this._destroyed||!t)return{succeeded:!1,reason:"unavailable"};const o={destination:Cesium.Cartesian3.fromDegrees(t.lon,t.lat,t.alt),orientation:{heading:Cesium.Math.toRadians(t.heading),pitch:Cesium.Math.toRadians(t.pitch),roll:Cesium.Math.toRadians(t.roll)}};let r=Promise.resolve({status:n?"superseded":"skipped"});if(n&&this._isNavigationCurrent(i)){const d=++this._restoreGeneration;let f;r=new Promise(g=>{f=g});const p=(g="cancelled")=>{var _;((_=this._activeCameraFlight)==null?void 0:_.restoreGeneration)===d&&(this._activeCameraFlight=null),f({status:g})};this._activeCameraFlight={restoreGeneration:d,navigationToken:i,settle:p},this.viewer.camera.flyTo({...o,duration:3,easingFunction:Cesium.EasingFunction.CUBIC_IN_OUT,complete:()=>{var g,_;if(this._destroyed||d!==this._restoreGeneration||!this._isNavigationCurrent(i)){p("superseded");return}this.viewer.camera.setView(o),(_=(g=this.viewer.scene)==null?void 0:g.requestRender)==null||_.call(g),p("applied")},cancel:()=>p("cancelled")})}const s=t.restoreAuthority||null,a=!s||s.visual===this._restoreAuthority.visual,c=!s||s.map===this._restoreAuthority.map;let l=t.panelState;s&&(l!=null&&l.specs)&&(l={specs:l.specs.filter(d=>{var f;return(((f=s.panels)==null?void 0:f.get(d.id))||0)===(this._restoreAuthority.panels.get(d.id)||0)})},l.specs.length===0&&(l=null));let u="skipped";this._onRestore&&(await this._onRestore({style:a?t.style:void 0,bloom:a?t.bloom:void 0,sharpen:a?t.sharpen:void 0,bloomIntensity:a?t.bloomIntensity:void 0,bloomVersion:a?t.bloomVersion:void 0,sharpenIntensity:a?t.sharpenIntensity:void 0,hudVariant:a?t.hudVariant:void 0,hudVisible:a?t.hudVisible:void 0,detectionMode:a?t.detectionMode:void 0,detectionDensity:a?t.detectionDensity:void 0,detectionAllocation:a?t.detectionAllocation:void 0,detectionFadePct:a?t.detectionFadePct:void 0,detectionOutsideOpacityPct:a?t.detectionOutsideOpacityPct:void 0,celestialRing:a?t.celestialRing:void 0,scopeEnabled:a?t.scopeEnabled:void 0,scopeFeatherPct:a?t.scopeFeatherPct:void 0,scopeTerminusPct:a?t.scopeTerminusPct:void 0,mapStack:c?t.mapStack:void 0,panelState:l,styleParams:a?t.styleParams:void 0}),u="applied");const h=await r;return{succeeded:!this._destroyed,camera:h.status,visual:a?u:"superseded",map:c?u:"superseded",panels:l?u:t.panelState?"superseded":"skipped"}}completeInitialRestore(){this._initialRestorePending&&(this._initialRestorePending=!1,this._scheduleUpdate())}claimRestoreLane(t,n=null){this._initialRestorePending&&(t==="panel"&&n?this._restoreAuthority.panels.set(n,(this._restoreAuthority.panels.get(n)||0)+1):(t==="visual"||t==="map")&&(this._restoreAuthority[t]+=1))}setLayerStateProvider(t){this._layerStateProvider=typeof t=="function"?t:null}setPanelStateProvider(t){this._panelStateProvider=typeof t=="function"?t:null}setStyleParamStateProvider(t){this._styleParamStateProvider=typeof t=="function"?t:null}onLayerStateChange(){this._scheduleUpdate()}onPanelStateChange(t=null){t&&this.claimRestoreLane("panel",t),this._scheduleUpdate()}_encodePanelStateParam(t,n){if(!n||!Array.isArray(n.specs)||n.specs.length===0){t.delete(js);return}const i=[];for(const o of IT){const r=n.specs.find(s=>s.id===o.id);!r||typeof r.collapsed!="boolean"||(i.push(`${o.token}.c.${r.collapsed?"1":"0"}`),o.pinnable&&typeof r.pinned=="boolean"&&i.push(`${o.token}.p.${r.pinned?"1":"0"}`))}i.length?t.set(js,i.join("_")):t.delete(js)}onStyleChange(t){this._currentStyle=t,this._scheduleUpdate()}onToggleChange(t,n,i={}){this._bloomEnabled=t,this._sharpenEnabled=n,typeof i.bloomIntensity=="number"&&(this._bloomIntensity=i.bloomIntensity),typeof i.bloomVersion=="number"&&(this._bloomVersion=i.bloomVersion),typeof i.sharpenIntensity=="number"&&(this._sharpenIntensity=i.sharpenIntensity),typeof i.hudVariant=="string"&&(this._hudVariant=i.hudVariant),typeof i.hudVisible=="boolean"&&(this._hudVisible=i.hudVisible),typeof i.detectionMode=="string"&&(this._detectionMode=i.detectionMode.toUpperCase()),typeof i.detectionDensity=="number"&&(this._detectionDensity=i.detectionDensity),typeof i.detectionAllocation=="string"&&(this._detectionAllocation=xo(i.detectionAllocation)),typeof i.detectionFadePct=="number"&&(this._detectionFadePct=Math.max(0,Math.min(40,Math.round(i.detectionFadePct)))),typeof i.detectionOutsideOpacityPct=="number"&&(this._detectionOutsideOpacityPct=Math.max(0,Math.min(100,Math.round(i.detectionOutsideOpacityPct)))),typeof i.celestialRingEnabled=="boolean"&&(this._celestialRingEnabled=i.celestialRingEnabled),typeof i.scopeEnabled=="boolean"&&(this._scopeEnabled=i.scopeEnabled),typeof i.scopeFeatherPct=="number"&&(this._scopeFeatherPct=Math.max(0,Math.min(100,Math.round(i.scopeFeatherPct)))),i.scopeTerminusPct===null?this._scopeTerminusPct=null:typeof i.scopeTerminusPct=="number"&&(this._scopeTerminusPct=kl(i.scopeTerminusPct)),typeof i.mapStack=="string"&&(this._mapStack=i.mapStack),this._scheduleUpdate()}async copyLink({nowMs:t=Date.now()}={}){const n=this._buildHashParams();if(!n)return!1;n.set(hf,String(Math.floor(t/1e3)));const i=new URL(window.location.href);i.hash=n.toString();try{return await navigator.clipboard.writeText(i.href),!0}catch{return!1}}_scheduleUpdate(){this._destroyed||this._initialRestorePending||(clearTimeout(this._debounceTimer),this._debounceTimer=setTimeout(()=>this._updateHash(),XW))}_updateHash(){if(this._destroyed||this._initialRestorePending)return;const t=this._buildHashParams();t&&history.replaceState(null,"",`#${t.toString()}`)}_buildHashParams(){var s,a,c;if(this._destroyed)return null;const t=this.viewer.camera,n=t.positionCartographic;if(!n)return null;const i=new URLSearchParams;i.set("v","2"),i.set("lat",Cesium.Math.toDegrees(n.latitude).toFixed(4)),i.set("lon",Cesium.Math.toDegrees(n.longitude).toFixed(4)),i.set("alt",Math.round(n.height).toString()),i.set("heading",Math.round(Cesium.Math.toDegrees(t.heading)).toString()),i.set("pitch",Math.round(Cesium.Math.toDegrees(t.pitch)).toString()),i.set("roll",Math.round(Cesium.Math.toDegrees(t.roll)).toString()),i.set("style",AT[this._currentStyle]||"normal"),i.set("bloom",this._bloomEnabled?"1":"0"),i.set("sharpen",this._sharpenEnabled?"1":"0"),i.set("bi",Math.round(this._bloomIntensity).toString()),i.set("bv",Math.round(this._bloomVersion).toString()),i.set("si",Math.round(this._sharpenIntensity).toString()),i.set("hud",this._hudVariant),i.set("hv",this._hudVisible?"1":"0"),i.set("dm",this._detectionMode),i.set("dd",Math.round(this._detectionDensity).toString()),i.set("da",this._detectionAllocation.toLowerCase()),i.set("kf",Math.round(this._detectionFadePct).toString()),i.set("ko",Math.round(this._detectionOutsideOpacityPct).toString()),i.set("cr",this._celestialRingEnabled?"1":"0"),i.set("sc",this._scopeEnabled?"1":"0"),i.set("scf",Math.round(this._scopeFeatherPct).toString());const o=kl(this._scopeTerminusPct);o!=null&&i.set("sce",String(o)),i.set("map",this._mapStack);const r=(s=this._layerStateProvider)==null?void 0:s.call(this);return r&&YC(i,r),this._encodePanelStateParam(i,(a=this._panelStateProvider)==null?void 0:a.call(this)),nK(i,this._currentStyle,(c=this._styleParamStateProvider)==null?void 0:c.call(this,this._currentStyle)),i.delete(hf),i}destroy(){var n,i,o;if(this._destroyed)return;const t=this._activeCameraFlight;t&&this._isNavigationCurrent(t.navigationToken)&&((n=this._cancelOwnedNavigation)==null||n.call(this)),(i=t==null?void 0:t.settle)==null||i.call(t,"destroyed"),this._restoreGeneration+=1,this._activeCameraFlight=null,this._destroyed=!0,clearTimeout(this._debounceTimer),this._debounceTimer=null,(o=this._removeCameraChanged)==null||o.call(this),this._removeCameraChanged=null,this._layerStateProvider=null,this._panelStateProvider=null,this._styleParamStateProvider=null,this._onRestore=null}}function tK(e,{nowMs:t=Date.now()}={}){var r;const n=(r=e==null?void 0:e.get)==null?void 0:r.call(e,hf);if(typeof n!="string"||!/^[1-9]\d*$/.test(n))return null;const i=Number(n);if(!Number.isSafeInteger(i))return null;const o=i*1e3;return!Number.isSafeInteger(o)||o>t?null:o}function nK(e,t,n){const i=RT[t];if(!i||!n||typeof n!="object"){e.delete(qs);return}const o=[];for(const r of i){const s=Number(n[r.key]);if(!Number.isFinite(s))continue;const a=Math.max(r.min,Math.min(r.max,s));o.push(`${r.token}.${Math.round(a*100)}`)}o.length?e.set(qs,o.join("_")):e.delete(qs)}function iK(e,t){if(e.get("v")!=="2"||!e.has(qs))return null;const n=RT[t];if(!n)return null;const i=new Map(n.map(r=>[r.token,r])),o={};for(const r of String(e.get(qs)||"").split("_")){const[s,a,...c]=r.split(".");if(c.length||!/^-?\d+$/.test(a||""))continue;const l=i.get(s);if(!l)continue;const u=Number(a)/100;o[l.key]=Math.max(l.min,Math.min(l.max,u))}return Object.keys(o).length?o:null}function oK(e){if(e.get("v")!=="2"||!e.has(js))return null;const t=String(e.get(js)||"").trim();if(!t)return null;const n=new Map;for(const o of t.split("_")){if(!o)continue;const[r,s,a,...c]=o.split(".");if(c.length)continue;const l=ZW.get(r);if(!l||s!=="c"&&s!=="p"||a!=="0"&&a!=="1")continue;const u=a==="1",h=n.get(l.id)||{id:l.id,collapsed:null,pinned:null};s==="c"?h.collapsed=u:s==="p"&&l.pinnable&&(h.pinned=u),n.set(l.id,h)}const i=Array.from(n.values()).filter(o=>typeof o.collapsed=="boolean");return i.length?{specs:i}:null}class rK{constructor(t){this.viewer=t,this.active=!1,this.target=null,this.radius=500,this.pitch=-30,this.speed=Cesium.Math.toRadians(6),this.angle=0,this._removeListener=null}start(t,n={}){if(!t)return;this.target=t,this.radius=n.radius||this.radius,this.pitch=n.pitch||this.pitch,this.speed=Cesium.Math.toRadians(n.speed||6),this.active=!0,ii("camera-orbit"),this.angle=this.viewer.camera.heading;let i=Date.now();this._removeListener=this.viewer.scene.preRender.addEventListener(()=>{if(!this.active)return;const o=Date.now(),r=(o-i)/1e3;i=o,this.angle+=this.speed*r;const s=new Cesium.HeadingPitchRange(this.angle,Cesium.Math.toRadians(this.pitch),this.radius);this.viewer.camera.lookAt(this.target,s)})}stop(){this.active=!1,Vi("camera-orbit"),this._removeListener&&(this._removeListener(),this._removeListener=null),this.viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY)}toggle(t,n){return this.active?this.stop():this.start(t,n),this.active}}const LT=220,sK=1e3/60,aK=4;function lK(e){return Number.isFinite(e)?Math.floor(e/sK)*2%aK:0}function cK({active:e,nowMs:t,enabledAtMs:n,fadeMs:i=LT,animatingLabelCount:o=0,solvePending:r=!1}={}){if(!e)return!1;if(Number(o)>0||r===!0)return!0;if(!Number.isFinite(t)||!Number.isFinite(n))return!1;const s=t-n;return s>=0&&si&&Number(n)%2!==0;return{skip:o,requestFollowUp:o}}function hK(e){return e?e.selected?Number(e.temporalAlpha)<1:!0:!1}function fK(e){let t=0;for(let n=0;n{var a;ap=((a=s==null?void 0:s.detail)==null?void 0:a.active)===!0,at==null||at.requestPaint()},typeof window<"u"&&window.addEventListener("gev:cockpit-mode-changed",yo),ST("normal"),Wr(),console.log("[Detection] Initialized")}function RK(){var e,t;yo&&typeof window<"u"&&window.removeEventListener("gev:cockpit-mode-changed",yo),yo=null,ap=!1,op=!1,nn&&(nn.style.display="none"),(e=at==null?void 0:at.unregister)==null||e.call(at),at=null,(t=Rt==null?void 0:Rt.unregister)==null||t.call(Rt),Rt=null,xc.clear(),Sn=0,Ci=null,Rc=[],jr=null,_r=null,nn=null,Ke=null,qe=Tt,on=!1,mu="",Xt.clear(),Ys=0,en=!0,Ve=null,yi={demandByLayer:{},cohortByLayer:{},cohortCount:0},ha=-1,Sc=0,ff=0,Ks=0,Lc=0,Il=0,Pc=0}function rC(e,t,n){return Math.max(t,Math.min(n,e))}function Nc(e=gn){return ci.indexOf(Eo(e))}function LK(){qe===Tt?qe=qr||Nc():(qr=qe,qe=Tt),DT()}function PK(e){if(!e)return;const t=HK(e);if(t){if(t==="OFF")qe!==Tt&&(qr=qe),qe=Tt;else{const n=$l(t);Eo(gn)!==t&&(gn=n),qe=Nc(),qr=qe}en=!0,DT()}}function xK(){return ci[qe]}function FK(e="transition"){on=!0,mu=String(e||"transition"),Wr(),Dc(!1)}function SK(){on=!1,mu="",Wr(),Dc(qe!==Tt)}function Dc(e){const t=e===!0;at==null||at.setActive(t),Rt==null||Rt.setActive(t),t||(Sn=0)}function NK(e={}){let t=!1;if(typeof e.densityPct=="number"&&Number.isFinite(e.densityPct)){const n=wt(e.densityPct);n!==gn&&(gn=n,qe!==Tt?(qe=Nc(),qr=qe,t=!0):qr=Nc(),en=!0)}if(e.allocationStrategy!=null){const n=xo(e.allocationStrategy,Ln);n!==Ln&&(Ln=n,en=!0)}t&&jr&&jr(ci[qe]),at==null||at.requestPaint()}function DK(){return{densityPct:gn,allocationStrategy:Ln}}function OK(e="sources-changed"){qe!==Tt&&(en=!0,Ve&&(Ve.lastSourceChangeReason=e))}function BK(){if(!Ve)return null;const e=JSON.parse(JSON.stringify(Ve));return e.calloutRects=Fc.slice(0,Sn).map(({x:t,y:n,w:i,h:o,alpha:r})=>({x:t,y:n,w:i,h:o,alpha:r})),e}function VK(){if(!(_r!=null&&_r.dataset)||!Ve)return;const e=_r.dataset;e.profile=Ve.profile||"OFF",e.densityPct=String(Ve.densityPct??gn),e.allocationStrategy=Ve.allocationStrategy||Ln,e.solveRevision=String(Ve.solveRevision??0),e.collectiveLabelBudget=String(Ve.collectiveLabelBudget??0),e.labelsByLayer=JSON.stringify(Ve.labelsByLayer||{}),e.entitlementByLayer=JSON.stringify(Ve.entitlementByLayer||{}),e.labeledKeys=JSON.stringify(Ve.labeledKeys||[]),e.labelAlphaByKey=JSON.stringify(Ve.labelAlphaByKey||{}),e.bracketOpacityCounts=JSON.stringify(Ve.bracketOpacityCounts||{}),e.keyholeRadius=String(Ve.keyholeRadius??0),e.keyholeFeatherPx=String(Ve.keyholeFeatherPx??0),e.demandByLayer=JSON.stringify(Ve.demandByLayer||{}),e.cohortByLayer=JSON.stringify(Ve.cohortByLayer||{}),e.placementBuildCount=String(Ve.placementBuildCount??0),e.observationCount=String(Ve.observationCount??0),e.selectedCount=String(Ve.selectedCount??0),e.fadingCount=String(Ve.fadingCount??0),e.paintMs=String(Ve.paintMs??0),e.solveMs=String(Ve.solveMs??0),e.frameTotalMs=String(Ve.frameTotalMs??0),e.throttleSkipCount=String(Ve.throttleSkipCount??0)}function ST(e){oC=e||"normal",Lt=Al[oC]||Al._default,mf=Lt.calloutPlate||Al._default.calloutPlate,FT=Lt.calloutPlateSpace||mf,NT(),at==null||at.requestPaint()}function NT(){nn&&(nn.style.mixBlendMode=Lt.blend,nn.style.filter=`${Lt.filter} drop-shadow(0 0 ${kK}px ${Lt.glow})`)}function Wr(){qt("detection-visibility"),nn&&(nn.style.display=qe===Tt?"none":"block",nn.style.opacity=on?"0":"1")}function HK(e){const t=String(e).toUpperCase();return tC[t]?tC[t]:ci.includes(t)?t:null}function DT(){const e=ci[qe];qe===Tt?(Wr(),Dc(!1),Xt.clear(),Ys=0,en=!0,yi={demandByLayer:{},cohortByLayer:{},cohortCount:0}):(sp=rp(),Wr(),Dc(!on),en=!0),jr&&jr(e),console.log(`[Detection] Mode: ${e}`)}function $K(e){if(qe===Tt||on)return!1;const t=e.layoutRevision!==ha;ff++;const n=dK({layoutChanged:t,lastPaintMs:Lc,frameCount:ff});return n.skip?(Pc++,Ve&&(Ve.throttleSkipCount=Pc),n.requestFollowUp&&qt("detection-paint-skipped"),!1):!0}function GK(e){if(qe===Tt||on)return;Ke=e.ctx,_r=e.canvas,nn!==e.surface&&(nn=e.surface,NT(),Wr()),e.layoutRevision!==ha&&(ha=e.layoutRevision,en=!0);const t=performance.now(),n=YK(e)||{didSolve:!1,solveMs:0,animatingCount:0,solvePending:!1};Ks=performance.now()-t,Il=n.solveMs||0,Lc=Math.max(0,Ks-Il),Ve&&(Ve.frameTotalMs=Ks,Ve.paintMs=Lc,Ve.solveMs=Il,Ve.throttleSkipCount=Pc),n.didSolve&&VK(),cK({active:qe!==Tt&&!on,nowMs:Number.isFinite(e.timestamp)?e.timestamp:rp(),enabledAtMs:sp,fadeMs:PT,animatingLabelCount:n.animatingCount||0,solvePending:n.solvePending===!0})&&qt("detection-animation")}function UK(){const e=ci[qe],t=[];for(let n=0;n0)for(const s of r)s._layerId=i.id,t.push(s)}catch{}}return t}function sC(e,t,n){if(!(!Lt.scanline||!Ke)){Ke.save(),Ke.globalAlpha=Lt.scanline,Ke.fillStyle=Lt.labelBg;for(let i=lK(n);ir-4||_+o.h>s-4)continue;const m={x:g,y:_,w:o.w,h:o.h};if(Hy(m,c))continue;const b=p.leadToSide.endsWith("E")?g+o.w:g,C=p.leadToSide.startsWith("S")?_+o.h:_,y=g+o.w*.5,v=_+o.h*.5,M=si(y,v,a);M<=0||f.push({...p,leadToX:b,leadToY:C,centerX:y,centerY:v,keyholeAlpha:M,rect:m,primaryX:g+o.primaryX,microX:g+o.microX,baseline:_+o.baseline})}return f}function qK(e,t,n){const{candidate:i,placement:o,temporalAlpha:r}=e,s=si(o.centerX,o.centerY,n),a=t*r*s;if(a<=.001)return;let c=Fc[Sn];c||(c={x:0,y:0,w:0,h:0,primaryX:0,microX:0,baseline:0,leadFromX:0,leadFromY:0,leadToX:0,leadToY:0,plate:"",plateScale:1,accent:"",label:"",primary:"",micro:"",font:Ws,microFont:iC,alpha:1},Fc[Sn]=c),c.x=o.cardX,c.y=o.cardY,c.w=o.rect.w,c.h=o.rect.h,c.primaryX=o.primaryX,c.microX=o.microX,c.baseline=o.baseline,c.leadFromX=o.leadFromX,c.leadFromY=o.leadFromY,c.leadToX=o.leadToX,c.leadToY=o.leadToY,c.plate=i.type==="SAT"?FT:mf,c.plateScale=i.plateScale??1,c.accent=i.color,c.label=Lt.label,c.primary=i.primary,c.micro=i.hasMicro?i.micro:"",c.font=Ws,c.microFont=iC,c.alpha=a,Sn++}function WK(e){if(qe===Tt||on)return;const t=e.ctx;if(t){for(const n of xc.values())for(const i of n)i&&Gy(t,i.path,i.color,i.alpha*xT);t.textAlign="left",t.textBaseline="alphabetic";for(let n=0;n=CK,s=e.uiRects,a=r?Xt.liveIdentities({includeFading:!1,now:i}):null,c=Xt.liveIdentities({includeFading:!0,now:i}),l=UK(),u=l.length;if(l.length===0)return Sn=0,Ke.font=Ws,sC(t,n,i),lC(t,n),aC(0,0),Ve={profile:ci[qe],densityPct:gn,allocationStrategy:Ln,viewScale:zd((me=(se=Ci==null?void 0:Ci.camera)==null?void 0:se.positionCartographic)==null?void 0:me.height),candidateCount:0,observationCount:0,visibleCount:0,bracketPresentationOpacity:o,labelBudget:0,labelsByLayer:{},labeledKeys:[],solveRevision:Xt.solveRevision,demandByLayer:{},cohortByLayer:{},cohortCount:0,placementBuildCount:0,selectedCount:0,fadingCount:0,didSolve:!1},Ys=i,en=!1,{didSolve:!1,solveMs:0,fadingCount:0,animatingCount:0,solvePending:!1};const h=e.occluder,d=e.cameraPosition,f=e.keyhole,p=pa().outsideOpacity,g=e.viewProjectionMatrix,_=g[0],m=g[1],b=g[3],C=g[4],y=g[5],v=g[7],M=g[8],w=g[9],E=g[11],k=g[12],T=g[13],I=g[15];Ke.font=Ws,Sc||(Sc=Ke.measureText("0000000000").width/10||6);const R=Lt.tiers||null,S=Y=>R&&R[Y]||Lt.line,A=new Map,L=(Y,K,_e)=>{const he=Math.max(1,Math.min(Ja,Math.ceil(_e*Ja)));let Ce=Y.get(K);Ce||(Ce=new Array(Ja+1),Y.set(K,Ce));let ye=Ce[he];return ye||(ye={color:K,alpha:he/Ja,path:new Path2D},Ce[he]=ye),ye.path};let F=0;const P={full:0,partial:0,hidden:0},O={left:0,front:0,right:0};let D=0;const $=new Map,x=r?new Map:null,N=r?new Map:null;let G=0;for(let Y=0;Y0?(U=K.bracketHalfWidth,Le=K.bracketHalfHeight):(U=qe===Td?de?28:11:16,Le=qe===Td?de?22:7:10);if(pe<-U||pe>t+U||te<-Le||te>n+Le)continue;const ke=S(By(K)),Ne=si(pe,te,f),Se=QR(K.type,Ne,p);if(Se>0){const ce=(J=K.tier)==null?void 0:J.startsWith("transit_");(ce?Uy:Of)(L(ce?xc:A,ke,Se),pe,te,U,Le),F++,K.type==="AIR"&&O[ZR(pe,t)]++,Se>=1?P.full++:P.partial++}else P.hidden++;if(K.skipLabel){Se>0&&D++;continue}const Ue=String(K.id||""),rt=String(K.metric||"");if(!Ue&&!rt)continue;const Q=K._layerId||"unknown",X=K.sourceId??K.id??Y,ie=((Z=c.get(Q))==null?void 0:Z.has(X))||!1;if(!(!r&&!ie)){if(K._cohortSourceId=X,K._cohortPriority=zK(K),K._cohortBand=Se>=.999?8:Math.floor(Se*8),K._cohortHash=dv(Q,X),K._candidateScreenX=pe,K._candidateScreenY=te,K._candidateHalfW=U,K._candidateHalfH=Le,K._candidateColor=ke,K._candidatePrimary=Ue,K._candidateMicro=rt,r&&Ne>0){N.set(Q,(N.get(Q)||0)+1),x.has(Q)||x.set(Q,new hv(256));const ce=((ae=a==null?void 0:a.get(Q))==null?void 0:ae.has(X))||!1;x.get(Q).consider(K,ce)}if(ie){G++;const ce=cC(K,t,n,f,s,d);ce&&!$.has(ce.key)&&$.set(ce.key,ce)}}}const W=((le=(oe=Ci==null?void 0:Ci.camera)==null?void 0:oe.positionCartographic)==null?void 0:le.height)??1e9,V=eL(W,gn),H=Math.max(0,V-Math.min(V,D));let B=!1,q=0;if(r){const Y=oL(N,H,Ln,nC),K=[],_e={};for(const[Ce,ye]of x){const ve=ye.values(KR(Y.get(Ce)||0));for(const pe of ve){const te=OT(Ce,pe._cohortSourceId);let de=$.get(te);de||(G++,de=cC(pe,t,n,f,s,d),de&&$.set(de.key,de)),de&&K.push(de)}_e[Ce]=K.filter(pe=>pe.layerId===Ce).length}const he=performance.now();Xt.solve(K,{capacity:H,strategy:Ln,layerWeights:nC,demandByLayer:N,now:i,preserveIncumbents:!0}),q=performance.now()-he,Ys=i,en=!1,yi={demandByLayer:Object.fromEntries(N),cohortByLayer:_e,cohortCount:K.length},B=!0}const z=Oy(sp,i,PT),j=qe===Td?1:1.25;xT=z*o,Ke.lineWidth=j;for(const Y of A.values())for(const K of Y)K&&(Ke.globalAlpha=z*K.alpha*o,Ke.strokeStyle=K.color,Ke.stroke(K.path));const ne=Xt.renderEntries($,i),ee=AK(ne),re=fK(ne);Sn=0;for(const Y of ne)qK(Y,z,f);if(Ke.font=Ws,Ke.globalAlpha=1,B||!Ve){const Y=Xt.diagnostics()||{},K=Xt.selectedKeys.size;Ve={profile:ci[qe],densityPct:gn,allocationStrategy:Ln,viewScale:zd(W),candidateCount:yi.cohortCount,observationCount:u,candidatesByLayer:yi.cohortByLayer,demandByLayer:yi.demandByLayer,cohortByLayer:yi.cohortByLayer,cohortCount:yi.cohortCount,placementBuildCount:G,selectedCount:K,fadingCount:ee,didSolve:B,visibleCount:F,bracketOpacityCounts:P,aircraftBracketSectors:O,bracketPresentationOpacity:o,protectedVisibleCount:D,collectiveLabelBudget:V,ambientLabelBudget:H,labelsByLayer:Y.labelsByLayer||{},entitlementByLayer:Y.quotas||{},labeledKeys:Array.from(Xt.selectedKeys),labelAlphaByKey:Object.fromEntries(ne.map(_e=>[_e.candidate.key,_e.temporalAlpha*si(_e.placement.centerX,_e.placement.centerY,f)])),solveRevision:Xt.solveRevision,keyholeRadius:f.radius,keyholeFeatherPx:f.featherPx,calloutOcclusionCount:s.length}}else{const Y=Xt.selectedKeys.size;Ve.placementBuildCount=G,Ve.observationCount=u,Ve.selectedCount=Y,Ve.fadingCount=ee,Ve.didSolve=!1,Ve.visibleCount=F,Ve.bracketOpacityCounts=P,Ve.aircraftBracketSectors=O,Ve.bracketPresentationOpacity=o,Ve.protectedVisibleCount=D}return sC(t,n,i),lC(t,n),aC(F,u),{didSolve:B,solveMs:q,fadingCount:ee,animatingCount:re,solvePending:en}}async function XK(e,t,{signal:n}={}){if(![e,t].every(Number.isFinite))throw new Error("Valid coordinates are required");return ts.regional.getBrief(e,t,{signal:n})}class QK extends sq{constructor(t,n={}){super(t,{...n,services:{CITY_POIS:Ot,GLOBE_VIEW:ho,flyToGlobeView:_m,flyToPresetLocation:bm,flyToPOI:Cm,searchAndFlyTo:wa,interruptCameraMotion:St,IntelHUD:PW,ShareLinkManager:eK,OrbitController:rK,CelestialRing:uv,getKeyholeFadeTuning:pa,isCelestialRingStyleSupported:av,setKeyholeFadeTuning:rv,destroyTrackedReadout:om,initTrackedReadout:jv,destroyWorldOverlay:em,initWorldOverlay:Dv,destroyDetection:RK,initDetection:IK,cycleDetectionMode:LK,readDetectionDiagnostics:BK,getDetectionTuning:DK,getDetectionMode:xK,setDetectionModeByLabel:PK,suspendDetection:FK,resumeDetection:SK,setDetectionStyle:ST,setDetectionTuning:NK,isTr3b:Zr,toggleTr3b:Py,holdContinuousRender:ii,releaseContinuousRender:Vi,governorRequestRender:qt,setScopeMaskEnabled:jW,isScopeMaskEnabled:qW,setScopeMaskFeather:WW,getScopeMaskFeather:KW,setScopeTerminusOverride:BW,getScopeTerminusOverride:VW,clampScopeTerminusPct:kl,fetchRegionalBrief:XK,regionalDistanceM:jS,weatherCodeLabel:zS,LocationSearch:Fj,...n.services}})}}Cesium.Cartesian3.fromDegrees(-97.7431,30.2672,800),Cesium.Math.toRadians(0),Cesium.Math.toRadians(-35),Cesium.Cartesian3.fromDegrees(-122.4194,37.7749,1e3),Cesium.Math.toRadians(30),Cesium.Math.toRadians(-30),Cesium.Cartesian3.fromDegrees(-73.9857,40.7484,1200),Cesium.Math.toRadians(-20),Cesium.Math.toRadians(-30);function ZK(e){e.camera.setView({destination:Cesium.Cartesian3.fromDegrees(-97.7431,30.2672,25e3),orientation:{heading:Cesium.Math.toRadians(0),pitch:Cesium.Math.toRadians(-90),roll:0}});const t=setTimeout(()=>{e.isDestroyed()||e.camera.flyTo({destination:Cesium.Cartesian3.fromDegrees(-97.7431,30.2672,600),orientation:{heading:Cesium.Math.toRadians(15),pitch:Cesium.Math.toRadians(-30),roll:0},duration:4,easingFunction:Cesium.EasingFunction.CUBIC_IN_OUT})},500);return()=>{clearTimeout(t),e.isDestroyed()||e.camera.cancelFlight()}}function gi(e){return Math.min(1,Math.max(0,Number(e)||0))}function vo(e,t,n){return!Number.isFinite(Number(e))||n<=t?0:gi((Number(e)-t)/(n-t))}function JK(e){if(!e||!Number.isFinite(Number(e.weatherCode)))return{available:!1,cloud:0,rain:0,snow:0,fog:0,haze:0,droplets:0,storm:0,wind:0,windDirectionDeg:0};const t=Number(e.weatherCode),n=vo(e.cloudCoverPct,8,100),i=Math.max(0,Number(e.precipitationMm)||0),o=vo(e.windKph,4,90),r=Number(e.visibilityM),s=Number.isFinite(r)?vo(12e3-r,0,11500):0,a=t>=51&&t<=57,c=t>=61&&t<=67||t>=80&&t<=82||t>=95,l=t>=71&&t<=77||t>=85&&t<=86,u=t===45||t===48,h=t>=95,d=vo(i,.05,8),f=a?.12:c?h?.68:.28:0,p=l?.3:0,g=a||c?Math.max(f,d):0,_=l?Math.max(p,d):0,m=Math.max(u?.78:0,s),b=h?Math.max(.55,d):0,y=Math.max(n,h?.92:g||_?.7:u?.55:0);return{available:!0,cloud:gi(y),rain:gi(g),snow:gi(_),fog:gi(m),haze:gi(Math.max(m*.78,y*.14+(g+_)*.2)),droplets:gi(g*(.58+b*.42)),storm:gi(b),wind:o,windDirectionDeg:Number.isFinite(Number(e.windDirectionDeg))?(Number(e.windDirectionDeg)%360+360)%360:0}}function e9(e){const t=Math.max(0,Number(e)||0);return{precipitation:1-vo(t,6e3,14e3),cloud:1-vo(t,14e3,24e3),haze:1-vo(t,9e3,2e4)}}const BT=5*6e4,t9=1e3/12,n9=520,i9=320,VT=25e3,uC="godsEyeView.cockpitWeatherEffects.enabled",o9=` + attribute vec2 position; + + void main() { + gl_Position = vec4(position, 0.0, 1.0); + } +`,r9=` + precision highp float; + + uniform vec2 uResolution; + uniform vec2 uWind; + uniform float uTime; + uniform float uStrength; + + float hash(vec3 p) { + p = fract(p * vec3(443.8975, 397.2973, 491.1871)); + p += dot(p, p.yxz + 19.19); + return fract((p.x + p.y) * p.z); + } + + float noise(vec3 x) { + vec3 p = floor(x); + vec3 f = fract(x); + f = f * f * (3.0 - 2.0 * f); + return mix( + mix( + mix(hash(p), hash(p + vec3(1.0, 0.0, 0.0)), f.x), + mix(hash(p + vec3(0.0, 1.0, 0.0)), hash(p + vec3(1.0, 1.0, 0.0)), f.x), + f.y + ), + mix( + mix(hash(p + vec3(0.0, 0.0, 1.0)), hash(p + vec3(1.0, 0.0, 1.0)), f.x), + mix(hash(p + vec3(0.0, 1.0, 1.0)), hash(p + vec3(1.0, 1.0, 1.0)), f.x), + f.y + ), + f.z + ); + } + + float fbm(vec3 p) { + float value = 0.0; + float weight = 0.54; + for (int octave = 0; octave < 3; octave++) { + value += weight * noise(p); + p *= 2.03; + weight *= 0.48; + } + return value; + } + + float cloudDensity(vec3 p) { + vec3 drift = vec3(uWind.x, 0.0, uWind.y) * uTime; + float warp = fbm((p + drift * 0.42) * 0.42); + vec3 warped = p + drift + vec3(warp * 1.25, 0.0, warp * 0.82); + float field = fbm(warped * 0.5); + float lower = smoothstep(0.45, 1.25, p.y); + float upper = 1.0 - smoothstep(3.8, 5.1, p.y); + float threshold = mix(0.71, 0.52, uStrength); + return smoothstep(threshold, 0.86, field) * lower * upper; + } + + void main() { + vec2 uv = (gl_FragCoord.xy - 0.5 * uResolution.xy) / uResolution.y; + vec3 rayOrigin = vec3(0.0, 0.72, uTime * 0.035); + vec3 rayDirection = normalize(vec3(uv.x, uv.y * 0.92 + 0.18, 1.28)); + vec3 sunDirection = normalize(vec3(0.45, 0.28, 0.84)); + vec3 color = vec3(0.0); + float alpha = 0.0; + float distanceAlongRay = 0.15 + 0.06 * hash(rayDirection + uTime); + + for (int stepIndex = 0; stepIndex < 24; stepIndex++) { + vec3 point = rayOrigin + rayDirection * distanceAlongRay; + float density = cloudDensity(point); + if (density > 0.012) { + float lightDensity = cloudDensity(point + sunDirection * 0.38); + float absorption = exp(-lightDensity * 3.8); + float powder = 1.0 - exp(-density * 2.2); + float lighting = mix(0.22, 1.0, absorption * powder); + vec3 cloudColor = mix( + vec3(0.31, 0.36, 0.43), + vec3(0.96, 0.96, 0.93), + lighting + ); + float sampleAlpha = (1.0 - alpha) * density * (0.16 + uStrength * 0.13); + color += cloudColor * sampleAlpha; + alpha += sampleAlpha; + } + if (alpha > 0.92) break; + distanceAlongRay += 0.29; + } + + float visorFade = smoothstep(-0.82, -0.28, uv.y); + alpha *= visorFade * uStrength * 0.78; + color = alpha > 0.001 ? color / max(alpha, 0.001) : vec3(0.0); + gl_FragColor = vec4(color, clamp(alpha, 0.0, 0.82)); + } +`;function dC(e,t,n){const i=e.createShader(t);if(e.shaderSource(i,n),e.compileShader(i),e.getShaderParameter(i,e.COMPILE_STATUS))return i;const o=e.getShaderInfoLog(i)||"Unknown shader compilation error";throw e.deleteShader(i),new Error(o)}function HT(e,t){if(![e==null?void 0:e.latitude,e==null?void 0:e.longitude,t==null?void 0:t.latitude,t==null?void 0:t.longitude].every(Number.isFinite))return 1/0;const n=Cesium.Math.toRadians(e.latitude),i=Cesium.Math.toRadians(t.latitude),o=Cesium.Math.toRadians(t.latitude-e.latitude),r=Cesium.Math.toRadians(t.longitude-e.longitude),s=Math.sin(o/2)**2+Math.cos(n)*Math.cos(i)*Math.sin(r/2)**2;return 6371e3*2*Math.atan2(Math.sqrt(s),Math.sqrt(1-s))}function s9({nowMs:e,fetchedAt:t,anchor:n,point:i,hasWeather:o}){return!o||!Number.isFinite(e)||!Number.isFinite(t)?!0:e-t>=BT||HT(n,i)>=VT}function a9(e,t){const n=Math.max(1,Number(e)||1),i=Math.max(1,Number(t)||1),o=Math.min(.42,n9/n,i9/i);return{width:Math.max(1,Math.round(n*o)),height:Math.max(1,Math.round(i*o))}}function l9(e){return e==="1"}class c9{constructor(t,{weatherService:n=ts.weather}={}){this.weatherService=n,this.viewer=t,this.canvas=document.createElement("canvas"),this.canvas.id="cockpit-cloud-effects",this.canvas.setAttribute("aria-hidden","true"),document.body.appendChild(this.canvas),this.gl=null,this.program=null,this.locations=null,this.frame=null,this.refreshTimer=null,this.startupTimer=null,this.lastFrameMs=0,this.lastRefreshCheckMs=0,this.fetchedAt=0,this.anchor=null,this.weather=null,this.strength=0,this.targetStrength=0,this.windDirectionDeg=0,this.windStrength=0,this.pending=null,this.abort=null,this.destroyed=!1,this.reducedMotion=window.matchMedia("(prefers-reduced-motion: reduce)").matches,this.enabled=this.readEnabledPreference(),this.onResize=()=>this.resize(),this.onCockpitMode=i=>{var r;(((r=i==null?void 0:i.detail)==null?void 0:r.active)??document.body.classList.contains("cockpit-mode"))&&this.enabled?this.start():this.stop()},this.onEnabledChange=i=>{var r;const o=(r=i==null?void 0:i.detail)==null?void 0:r.enabled;this.setEnabled(typeof o=="boolean"?o:!this.enabled)},window.addEventListener("resize",this.onResize),window.addEventListener("gev:cockpit-mode-changed",this.onCockpitMode),window.addEventListener("gev:cockpit-weather-toggle",this.onEnabledChange),this.emitEnabledState()}readEnabledPreference(){try{return l9(localStorage.getItem(uC))}catch{return!1}}emitEnabledState(){window.dispatchEvent(new CustomEvent("gev:cockpit-weather-state",{detail:{enabled:this.enabled}}))}setEnabled(t){const n=!!t;this.enabled=n;try{localStorage.setItem(uC,n?"1":"0")}catch{}n?document.body.classList.contains("cockpit-mode")&&this.start():this.stop(),this.emitEnabledState()}initializeRenderer(){try{const t=this.canvas.getContext("webgl",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,powerPreference:"low-power"});if(!t)throw new Error("WebGL unavailable");const n=dC(t,t.VERTEX_SHADER,o9),i=dC(t,t.FRAGMENT_SHADER,r9),o=t.createProgram();if(t.attachShader(o,n),t.attachShader(o,i),t.linkProgram(o),t.deleteShader(n),t.deleteShader(i),!t.getProgramParameter(o,t.LINK_STATUS))throw new Error(t.getProgramInfoLog(o)||"Cloud shader link failed");const r=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,r),t.bufferData(t.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),t.STATIC_DRAW);const s=t.getAttribLocation(o,"position");t.enableVertexAttribArray(s),t.vertexAttribPointer(s,2,t.FLOAT,!1,0,0),this.gl=t,this.program=o,this.locations={resolution:t.getUniformLocation(o,"uResolution"),time:t.getUniformLocation(o,"uTime"),strength:t.getUniformLocation(o,"uStrength"),wind:t.getUniformLocation(o,"uWind")}}catch(t){console.warn("[Cockpit clouds] Renderer unavailable:",t),this.canvas.dataset.status="unavailable"}}resize(){if(!this.gl)return;const t=a9(window.innerWidth,window.innerHeight);this.canvas.width===t.width&&this.canvas.height===t.height||(this.canvas.width=t.width,this.canvas.height=t.height,this.gl.viewport(0,0,t.width,t.height))}cameraPoint(){var o,r;const t=(r=(o=this.viewer)==null?void 0:o.camera)==null?void 0:r.positionCartographic;if(!t)return null;const n=Cesium.Math.toDegrees(t.latitude),i=Cesium.Math.toDegrees(t.longitude);return[n,i].every(Number.isFinite)?{latitude:n,longitude:i,altitudeM:Math.max(0,Number(t.height)||0)}:null}start(){this.destroyed||!this.enabled||this.frame!==null||this.suspended||(this.gl||(this.initializeRenderer(),this.resize()),this.gl&&(this.canvas.dataset.cockpit="true",this.lastFrameMs=0,this.frame=requestAnimationFrame(t=>this.tick(t)),this.startupTimer!==null&&window.clearTimeout(this.startupTimer),this.startupTimer=window.setTimeout(()=>{this.startupTimer=null,document.body.classList.contains("cockpit-mode")&&this.refresh()},450)))}stop(){var t;this.frame!==null&&cancelAnimationFrame(this.frame),this.frame=null,this.refreshTimer!==null&&window.clearTimeout(this.refreshTimer),this.refreshTimer=null,this.startupTimer!==null&&window.clearTimeout(this.startupTimer),this.startupTimer=null,(t=this.abort)==null||t.abort(),this.abort=null,this.pending=null,this.strength=0,this.targetStrength=0,this.canvas.classList.remove("active"),this.canvas.dataset.cockpit="false",this.clear()}clear(){this.gl&&(this.gl.clearColor(0,0,0,0),this.gl.clear(this.gl.COLOR_BUFFER_BIT))}async refresh(){var o;if(this.destroyed||!this.enabled||this.pending||this.suspended||!document.body.classList.contains("cockpit-mode"))return this.pending;const t=this.cameraPoint();if(!t)return null;if(this.weather&&Date.now()-this.fetchedAt{if(this.abort!==i||i.signal.aborted)return null;if(!(r!=null&&r.weather))throw new Error("Cloud weather observation unavailable");return this.weather=r.weather,this.fetchedAt=Date.now(),this.anchor=t,this.applyWeather(r.weather,t.altitudeM),this.canvas.dataset.sourceStatus=r.status||"ready",r.weather}).catch(r=>{if(!(i.signal.aborted||this.abort!==i))return(r==null?void 0:r.name)!=="AbortError"&&(this.targetStrength=0,this.canvas.dataset.sourceStatus="unavailable"),null}).finally(()=>{this.abort===i&&(this.pending=null,this.abort=null)}),this.pending}applyWeather(t,n){const i=JK(t),o=e9(n);if(this.targetStrength=i.available?i.cloud*o.cloud:0,this.windDirectionDeg=i.windDirectionDeg||0,this.windStrength=i.wind||0,this.canvas.dataset.cloudStrength=this.targetStrength.toFixed(3),this.canvas.dataset.weatherCode=String((t==null?void 0:t.weatherCode)??"unknown"),this.reducedMotion&&document.body.classList.contains("cockpit-mode")){this.strength=this.targetStrength;const r=this.strength>.035;this.canvas.classList.toggle("active",r),r?this.render(0):this.clear()}}tick(t){if(this.destroyed||!this.enabled||!document.body.classList.contains("cockpit-mode")){this.stop();return}if(this.suspended){this.frame=null,this.refreshTimer!==null&&window.clearTimeout(this.refreshTimer),this.refreshTimer=null;return}if(t-this.lastRefreshCheckMs>=1e3){this.lastRefreshCheckMs=t;const o=this.cameraPoint();o&&s9({nowMs:Date.now(),fetchedAt:this.fetchedAt,anchor:this.anchor,point:o,hasWeather:!!this.weather})&&this.refresh()}const n=this.reducedMotion?1:.08;this.strength+=(this.targetStrength-this.strength)*n;const i=this.strength>.035;if(this.canvas.classList.toggle("active",i),i&&(this.reducedMotion||t-this.lastFrameMs>=t9)?(this.lastFrameMs=t,this.render(t/1e3)):i||this.clear(),this.reducedMotion){this.frame=null,this.refreshTimer=window.setTimeout(()=>{this.refreshTimer=null,this.tick(performance.now())},1e3);return}this.frame=requestAnimationFrame(o=>this.tick(o))}render(t){const n=this.gl;if(!n||!this.program||!this.locations)return;const i=Cesium.Math.toRadians(this.windDirectionDeg),o=.008+this.windStrength*.022;n.useProgram(this.program),n.uniform2f(this.locations.resolution,this.canvas.width,this.canvas.height),n.uniform1f(this.locations.time,t),n.uniform1f(this.locations.strength,Math.min(1,Math.max(0,this.strength))),n.uniform2f(this.locations.wind,Math.sin(i)*o,-Math.cos(i)*o),n.drawArrays(n.TRIANGLES,0,6)}getSnapshot(){return{enabled:this.enabled,active:this.canvas.classList.contains("active"),strength:this.targetStrength,weather:this.weather?{...this.weather}:null,renderSize:{width:this.canvas.width,height:this.canvas.height},sourceStatus:this.canvas.dataset.sourceStatus||"idle"}}setSuspended(t){this.suspended=!!t,this.suspended?(this.frame!==null&&cancelAnimationFrame(this.frame),this.frame=null,this.refreshTimer!==null&&window.clearTimeout(this.refreshTimer),this.refreshTimer=null,this.startupTimer!==null&&window.clearTimeout(this.startupTimer),this.startupTimer=null):document.body.classList.contains("cockpit-mode")&&this.start()}destroy(){this.destroyed=!0,this.stop(),window.removeEventListener("resize",this.onResize),window.removeEventListener("gev:cockpit-mode-changed",this.onCockpitMode),window.removeEventListener("gev:cockpit-weather-toggle",this.onEnabledChange),this.program&&this.gl&&this.gl.deleteProgram(this.program),this.canvas.remove()}}function u9(e,t){return new c9(e,t)}function d9({scene:{viewer:e,mapStackController:t,operations:n},loaderStatus:i,Controls:o=QK,services:r,catalog:s,placeSearch:a,defer:c}){const l=new o(e,{services:{...r,...n.surface.controlServices,searchAndFlyTo:n.searchAndFlyTo,fetchRegionalBrief:(...d)=>n.requests.regional.getBrief(...d),...Nk(s)},requestServices:n.requests,mapStackController:t,placeSearch:a});c(()=>l.orbitController.stop()),c(()=>l.hud.destroy()),c(()=>l.dispose());const u=null,h=u9(e,{weatherService:n.requests.weather});return c(()=>h==null?void 0:h.destroy()),l.hasShareState?i.textContent="Restoring shared view...":(i.textContent="Flying to Austin, TX...",c(ZK(e))),{styleManager:l,weatherEffects:u,cockpitCloudEffects:h}}function h9(e){return d9({catalog:(e==null?void 0:e.catalog)??UE(),...e})}function jn(e){return Array.isArray(e)?e.map(jn):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,jn(n)])):e}const kd=Symbol("superseded-visibility-intent"),f9=new Set(["enabled-only","enabled+options","enabled+mirrored-options"]);function Gn(e){return(e==null?void 0:e.name)==="AbortError"}function an(e,t){const n=new Error(`[Data] ${e} ${t} rejected the lifecycle transition`);return n.name="LifecycleRejectedError",n}function ds(e){const t=new Error(`[Data] ${e} rejected layer parameters`);return t.name="LayerParamsRejectedError",t}function m9(e){return e==="user"||e==="voice"||e==="tool"}function Ad(e,t,n){var i,o,r,s;if(m9(t))try{(r=((i=e.module)==null?void 0:i.cancelPendingRestore)||((o=e.module)==null?void 0:o.cancelPendingTrackingRestore))==null||r({origin:t,reason:n})}catch(a){console.warn(`[Data] ${((s=e.module)==null?void 0:s.id)||"layer"} pending restore cancellation error:`,a)}}function p9(e,t){const n=(e==null?void 0:e.error)||(e==null?void 0:e.lastError);return n?n instanceof Error?n:new Error(String(n)):(e==null?void 0:e.unavailable)===!0||(e==null?void 0:e.available)===!1?new Error(`${t} refresh unavailable`):null}class g9{constructor(t,{allowQaRegistration:n=!1}={}){this.viewer=t,this._activityListeners=new Set,this.layers=new Map,this._listeners=new Set,this._visibilityRequestListeners=new Set,this._beforeDestroyListeners=new Set,this._visibilityGuards=new Set,this._registrationsFinalized=!1,this._registrationDispositions=null,this._allowQaRegistration=n===!0,this._qaLayerIds=new Set}register(t){if(this._registrationsFinalized)throw new Error("Data-layer registrations are finalized");this._registerLayer(t)}registerForQa(t){if(!this._allowQaRegistration||!this._registrationsFinalized)throw new Error("QA layer registration is not authorized");return this._registerLayer(t),this._qaLayerIds.add(t.id),t.id}async unregisterForQa(t){if(!this._allowQaRegistration||!this._qaLayerIds.has(t))return!1;const n=await this.destroyLayer(t);return n&&this._qaLayerIds.delete(t),n}_registerLayer(t){if(!t||typeof t.id!="string"||!t.id)throw new Error("Data layer must provide a stable id");if(this.layers.has(t.id))throw new Error(`Duplicate data-layer id: ${t.id}`);this.layers.set(t.id,{module:t,enabled:!1,initialized:!1,intervalId:null,refreshing:!1,refreshEpoch:0,managerRefreshError:null,lifecycleState:"disabled",lifecycleUncertain:!1,visibilityIntentEpoch:0,visibilityIntentEnabled:!1,visibilityIntentOrigin:"programmatic",activeVisibilityIntent:null,latestQueuedAbsoluteIntent:null,pendingVisibilityAdoptionEpoch:0,visibilityIntentRecords:new Map,visibilityIntentFailures:new Map,paramsIntentEpoch:0,paramsIntentOrigin:"programmatic",destroying:!1,clearVisibilityReservation:null,toggleChain:Promise.resolve()})}finalizeRegistrations(t){if(this._registrationsFinalized)throw new Error("Data-layer registrations are already finalized");if(!Array.isArray(t))throw new Error("Layer serialization registry must be an array");const n=new Map;for(const s of t){if(!(s!=null&&s.id)||!(s!=null&&s.disposition))throw new Error("Layer serialization disposition is incomplete");if(n.has(s.id))throw new Error(`Duplicate layer serialization disposition: ${s.id}`);if(!f9.has(s.disposition))throw new Error(`Invalid layer serialization disposition: ${s.id}`);n.set(s.id,s.disposition)}const o=[...this.layers.keys()].filter(s=>!n.has(s)),r=[...n.keys()].filter(s=>!this.layers.has(s));if(o.length||r.length)throw new Error(`Layer serialization registry mismatch (missing: ${o.join(", ")||"none"}; extra: ${r.join(", ")||"none"})`);return this._registrationDispositions=n,this._registrationsFinalized=!0,!0}get registrationsFinalized(){return this._registrationsFinalized}_moduleStats(t){var n;if(!(t!=null&&t.initialized)||typeof((n=t.module)==null?void 0:n.getStats)!="function")return{count:0,lastUpdate:null};try{const i=t.module.getStats();return i&&typeof i=="object"?i:{count:0,lastUpdate:null}}catch(i){return console.warn(`[Data] ${t.module.id} getStats error:`,i),{count:0,lastUpdate:null,error:i}}}_normalizedStats(t){const n=this._moduleStats(t),i=t.lifecycleState==="enabling"||t.lifecycleState==="disabling";return{count:0,lastUpdate:null,...n,loading:i||n.loading===!0,refreshing:t.refreshing||n.refreshing===!0,managerRefreshError:t.managerRefreshError}}_invalidateRefresh(t,n,i="invalidated"){const o=n.refreshing,r=n.refreshEpoch;n.refreshEpoch+=1,n.refreshing=!1,o&&(this._publishActivity({type:"status"}),this._notifyListeners({type:"refresh-cancelled",layerId:t,enabled:n.enabled,refreshEpoch:r,reason:i}))}async _runPeriodicUpdate(t,n,{signal:i=null}={}){if(!n.enabled||n.lifecycleState!=="enabled"||n.destroying||n.refreshing||i!=null&&i.aborted)return!1;const o=++n.refreshEpoch;n.refreshing=!0,this._publishActivity({type:"status"}),this._notifyListeners({type:"refresh-transition",layerId:t,enabled:!0,refreshEpoch:o});let r,s=null;try{r=await n.module.update(this.viewer,{signal:i}),this._publishActivity({type:"data-updated",layerId:t}),r===!1&&(s=an(t,"refresh")),s||(s=p9(this._moduleStats(n),n.module.name||t))}catch(a){s=a}return i!=null&&i.aborted?(this.layers.get(t)===n&&!n.destroying&&n.enabled&&n.refreshEpoch===o&&(n.refreshing=!1,n.managerRefreshError=null,this._publishActivity({type:"status"}),this._notifyListeners({type:"refresh-cancelled",layerId:t,enabled:!0,refreshEpoch:o})),!1):this.layers.get(t)!==n||n.destroying||!n.enabled||n.refreshEpoch!==o?!1:(n.refreshing=!1,n.managerRefreshError=s?String(s.message||s):null,this._publishActivity({type:"status"}),s?(console.warn(`[Data] ${t} refresh error:`,s),this._notifyListeners({type:"refresh-failed",layerId:t,enabled:!0,refreshEpoch:o,phase:"refresh",error:s}),!1):(this._notifyListeners({type:"refresh",layerId:t,enabled:!0,refreshEpoch:o}),r!==!1))}async refreshLayer(t,{signal:n=null}={}){const i=this.layers.get(t);return!i||!i.enabled||i.lifecycleState!=="enabled"||i.destroying||n!=null&&n.aborted||i.refreshing&&(!await new Promise(r=>{var u;let s=!1;const a=h=>{var d;s||(s=!0,l(),(d=n==null?void 0:n.removeEventListener)==null||d.call(n,"abort",c),r(h))},c=()=>a(!1),l=this.subscribe(h=>{(h==null?void 0:h.layerId)===t&&["refresh","refresh-failed","refresh-cancelled"].includes(h.type)&&a(!0)});(u=n==null?void 0:n.addEventListener)==null||u.call(n,"abort",c,{once:!0}),queueMicrotask(()=>{i.refreshing||a(!0)})})||n!=null&&n.aborted||this.layers.get(t)!==i||!i.enabled||i.lifecycleState!=="enabled"||i.destroying)?!1:this._runPeriodicUpdate(t,i,{signal:n})}async resolveLayerTrackingTarget(t,n,{signal:i=null,origin:o="share-restore"}={}){var c;const r=this.layers.get(t),s={layerId:t,targetId:n,origin:o,refreshSucceeded:!1};if(!r||!r.enabled||r.destroying)return{...s,status:"unavailable",reason:"layer-unavailable"};if(typeof((c=r.module)==null?void 0:c.resolveTrackingRestoreTarget)!="function")return{...s,status:"unsupported",reason:"tracking-restore-unsupported"};if(i!=null&&i.aborted)return{...s,status:"cancelled",reason:String(i.reason||"aborted")};const a=await this.refreshLayer(t,{signal:i});if(i!=null&&i.aborted)return{...s,refreshSucceeded:a,status:"cancelled",reason:String(i.reason||"aborted")};if(this.layers.get(t)!==r||r.destroying||!r.enabled)return{...s,refreshSucceeded:a,status:"destroyed",reason:"layer-destroyed"};try{const l=await r.module.resolveTrackingRestoreTarget(n,{signal:i,origin:o,refreshSucceeded:a});if(i!=null&&i.aborted)return{...s,refreshSucceeded:a,status:"cancelled",reason:String(i.reason||"aborted")};const u=["found","missing","source-unavailable","cancelled","superseded","destroyed"].includes(l==null?void 0:l.status)?l.status:"source-unavailable";return{...s,refreshSucceeded:a,...l,status:u}}catch(l){return i!=null&&i.aborted||Gn(l)?{...s,refreshSucceeded:a,status:"cancelled",reason:String((i==null?void 0:i.reason)||(l==null?void 0:l.message)||"aborted"),errorClass:"AbortError"}:{...s,refreshSucceeded:a,status:"source-unavailable",reason:String((l==null?void 0:l.message)||l),errorClass:(l==null?void 0:l.name)||"Error"}}}_armUpdateLoop(t,n){const i=Number(n.module.refreshInterval),o=Number(n.module.updateInterval),r=i>0?i:o>0?o:0;r>0?n.intervalId=setInterval(()=>{this._runPeriodicUpdate(t,n)},r):o===0&&(n.intervalId=setInterval(()=>{n.enabled&&this._publishActivity({type:"status"})},n.module.statsRefreshInterval||1e3))}toggle(t,{origin:n="programmatic",notificationToken:i=null}={}){const o=this.layers.get(t);return!o||o.destroying?Promise.resolve(!1):this._setEnabledWithIntent(t,!this.isEffectivelyEnabled(t),{origin:n,notificationToken:i,notifyWillChangeBeforeEffective:!0}).promise}_enqueueToggle(t,n){const i=t.toggleChain.catch(()=>{}).then(n);return t.toggleChain=i,i}_setLifecycleTransition(t,n,i){t.lifecycleState=i,this._syncModuleLifecyclePresentation(t),this._publishActivity({type:"status"}),this._notifyListeners({...n,type:"visibility-transition",lifecycleState:i,settledEnabled:t.enabled})}_settleLifecycle(t){t.lifecycleState=t.enabled?"enabled":"disabled",this._syncModuleLifecyclePresentation(t)}_syncModuleLifecyclePresentation(t){if(typeof t.module.setLifecyclePresentation=="function")try{t.module.setLifecyclePresentation({lifecycleState:t.lifecycleState,enabled:t.enabled,uncertain:t.lifecycleUncertain})}catch(n){console.warn(`[Data] ${t.module.id} lifecycle presentation error:`,n)}}_visibilityCancellationMetadata(t,n,i,o,r=!1){const s=Number.isInteger(n)&&t.visibilityIntentEpoch>n,a={...Number.isInteger(n)?{intentEpoch:n}:{},phase:o,cancellationReason:r?"resource-abort":s||(i==null?void 0:i.reason)===kd?"superseded":"caller-abort",...s?{successorIntentEpoch:t.visibilityIntentEpoch,successorEnabled:t.visibilityIntentEnabled,successorOrigin:t.visibilityIntentOrigin}:{}},c=t.visibilityIntentRecords.get(n);return c&&Object.assign(c,a),a}_setVisibilityIntentPhase(t,n,i){if(!Number.isInteger(n))return;const o=t.visibilityIntentRecords.get(n);o&&(o.phase=i)}async _doToggle(t,n,i,{signal:o=null,targetEnabled:r=!t.enabled,notificationToken:s=null,intentEpoch:a=null,suppressWillChangeNotification:c=!1,beforeEnableParams:l=null}={}){const u=!!r,h=(_,m)=>{Number.isInteger(a)&&t.visibilityIntentFailures.set(a,{phase:_,error:m||an(n,_)})},d=()=>a!==null&&a!==t.visibilityIntentEpoch,f=()=>!d()&&(t.pendingVisibilityAdoptionEpoch=0,this._settleLifecycle(t),!d())?!0:(t.lifecycleState=t.visibilityIntentEnabled?"enabling":"disabling",t.pendingVisibilityAdoptionEpoch=t.visibilityIntentEpoch,this._syncModuleLifecyclePresentation(t),!1),p={type:"visibility-will-change",layerId:n,enabled:u,origin:i,...Number.isInteger(a)?{intentEpoch:a}:{},...s?{notificationToken:s}:{}};if(o!=null&&o.aborted)return!1;c||this._notifyListeners(p);const g=await this._visibilityBlockReason(p);if(o!=null&&o.aborted)return this._notifyListeners({...p,type:"visibility-cancelled",...this._visibilityCancellationMetadata(t,a,o,"guard")}),!1;if(g)return this._publishActivity({type:"status"}),this._notifyListeners({...p,type:"visibility-blocked",reason:g}),!1;if(this._setLifecycleTransition(t,p,u?"enabling":"disabling"),u){let _=null;const m=()=>{t.intervalId&&(clearInterval(t.intervalId),t.intervalId=null);try{_=Promise.resolve(t.module.disable(this.viewer)).catch(y=>(console.warn(`[Data] ${n} cancelled-enable cleanup error:`,y),!1))}catch(y){console.warn(`[Data] ${n} cancelled-enable cleanup error:`,y),_=Promise.resolve(!1)}},b=async(y,v=!1)=>{o==null||o.removeEventListener("abort",m),t.intervalId&&(clearInterval(t.intervalId),t.intervalId=null),await _;let M=!1;try{M=await t.module.disable(this.viewer)!==!1}catch(w){console.warn(`[Data] ${n} cancelled-enable final cleanup error:`,w)}return t.enabled=!M,t.lifecycleUncertain=!M,f(),this._publishActivity({type:"status"}),M||h("cancel-enable-cleanup",an(n,"cancel-enable-cleanup")),this._notifyListeners({...p,type:M?"visibility-cancelled":"visibility-failed",...M?this._visibilityCancellationMetadata(t,a,o,y,v):{},...M?{}:{phase:"cancel-enable-cleanup"}}),!1},C=async(y,v)=>{t.intervalId&&(clearInterval(t.intervalId),t.intervalId=null);let M=!1;try{M=await t.module.disable(this.viewer)!==!1}catch(w){console.warn(`[Data] ${n} failed-enable cleanup error:`,w)}return t.enabled=!M,t.lifecycleUncertain=!M,f(),console.warn(`[Data] ${n} ${y} error:`,v),h(y,v),this._publishActivity({type:"status"}),this._notifyListeners({...p,type:"visibility-failed",phase:y,error:v}),o==null||o.removeEventListener("abort",m),!1};if(o==null||o.addEventListener("abort",m,{once:!0}),!t.initialized){this._setVisibilityIntentPhase(t,a,"init");try{if(await t.module.init(this.viewer,{signal:o})===!1)throw an(n,"init");t.initialized=!0}catch(y){return o!=null&&o.aborted||Gn(y)?b("init",Gn(y)&&!(o!=null&&o.aborted)):C("init",y)}}if(o!=null&&o.aborted)return b("init");if(l){this._setVisibilityIntentPhase(t,a,"params");const y=this._applyLayerParamsIntent(n,l.params,{origin:l.origin,paramsIntentEpoch:l.paramsIntentEpoch});if(l.result=y,!y.succeeded)return o!=null&&o.aborted||y.cancellationReason?b("params"):C("params",y.error||ds(n))}if(o!=null&&o.aborted)return b("params");t.lifecycleUncertain=!1,this._setVisibilityIntentPhase(t,a,"enable");try{if(await t.module.enable(this.viewer,{signal:o})===!1)throw an(n,"enable")}catch(y){return o!=null&&o.aborted||Gn(y)?b("enable",Gn(y)&&!(o!=null&&o.aborted)):C("enable",y)}if(o!=null&&o.aborted)return b("enable");this._setVisibilityIntentPhase(t,a,"update");try{if(await t.module.update(this.viewer,{signal:o})===!1)throw an(n,"update")}catch(y){return o!=null&&o.aborted||Gn(y)?b("update",Gn(y)&&!(o!=null&&o.aborted)):C("update",y)}if(o!=null&&o.aborted)return b("update");if(t.managerRefreshError=null,t.enabled=!0,t.lifecycleUncertain=!1,this._setVisibilityIntentPhase(t,a,"settle"),!f()||o!=null&&o.aborted)return b("settle");t.intervalId&&(clearInterval(t.intervalId),t.intervalId=null),this._armUpdateLoop(n,t),o==null||o.removeEventListener("abort",m)}else{this._invalidateRefresh(n,t,"layer-disabled");const _=async(m="disable",b=!1)=>{let C=!1,y=null;try{C=await t.module.enable(this.viewer)!==!1,C||(y=an(n,"cancel-disable-compensation"))}catch(M){y=M,console.warn(`[Data] ${n} cancelled-disable cleanup error:`,M)}let v=!1;if(!C)try{v=await t.module.disable(this.viewer)!==!1}catch(M){console.warn(`[Data] ${n} cancelled-disable final cleanup error:`,M)}return t.enabled=C||!v,t.lifecycleUncertain=!C&&!v,f(),!t.enabled&&t.intervalId&&(clearInterval(t.intervalId),t.intervalId=null),this._publishActivity({type:"status"}),C||h("cancel-disable-compensation",y||an(n,"cancel-disable-compensation")),this._notifyListeners({...p,type:C?"visibility-cancelled":"visibility-failed",...C?this._visibilityCancellationMetadata(t,a,o,m,b):{},...C?{}:{phase:"cancel-disable-compensation",error:y}}),!1};try{if(await t.module.disable(this.viewer,{signal:o})===!1)throw an(n,"disable")}catch(m){return o!=null&&o.aborted||Gn(m)?_("disable",Gn(m)&&!(o!=null&&o.aborted)):(t.enabled=!0,t.lifecycleUncertain=!0,f(),console.warn(`[Data] ${n} disable error:`,m),h("disable",m),this._publishActivity({type:"status"}),this._notifyListeners({...p,type:"visibility-failed",phase:"disable",error:m}),!1)}if(o!=null&&o.aborted)return _("disable");if(t.intervalId&&(clearInterval(t.intervalId),t.intervalId=null),t.enabled=!1,t.lifecycleUncertain=!1,!f()||o!=null&&o.aborted)return _("settle")}return this._publishActivity({type:"status"}),this._publishActivity({type:"visibility-settled",layerId:n}),this._notifyListeners({type:"visibility",layerId:n,enabled:t.enabled,origin:i,...Number.isInteger(a)?{intentEpoch:a}:{},...s?{notificationToken:s}:{}}),!0}setEnabled(t,n,{origin:i="programmatic",signal:o=null,notificationToken:r=null}={}){return this._setEnabledWithIntent(t,n,{origin:i,signal:o,notificationToken:r}).promise}_setEnabledWithIntent(t,n,{origin:i="programmatic",signal:o=null,notificationToken:r=null,notifyWillChangeBeforeEffective:s=!1,beforeEnableParams:a=null}={}){var m;const c=this.layers.get(t);if(!c)return{intentEpoch:null,promise:Promise.resolve()};const l=!!n;if(c.destroying)return{intentEpoch:null,promise:Promise.resolve(l===!1)};Ad(c,i,"explicit-visibility");const u=++c.visibilityIntentEpoch;c.visibilityIntentEnabled=l,c.visibilityIntentOrigin=i;let h;const d=new Promise(b=>{h=b}),f={intentEpoch:u,enabled:l,origin:i,phase:"queued",settled:d,resolve:h};c.visibilityIntentRecords.set(u,f);for(const[b,C]of c.visibilityIntentRecords){if(c.visibilityIntentRecords.size<=16)break;b!==u&&C.completed&&c.visibilityIntentRecords.delete(b)}s&&this._notifyListeners({type:"visibility-will-change",layerId:t,enabled:l,origin:i,intentEpoch:u,...r?{notificationToken:r}:{}}),c.visibilityIntentEpoch===u&&(c.latestQueuedAbsoluteIntent={intentEpoch:u,enabled:l}),this._notifyVisibilityRequest({type:"visibility-requested",layerId:t,enabled:l,origin:i,intentEpoch:u,...r?{notificationToken:r}:{}}),(m=c.activeVisibilityIntent)==null||m.controller.abort(kd);const p=()=>{var b;((b=c.latestQueuedAbsoluteIntent)==null?void 0:b.intentEpoch)===u&&(c.latestQueuedAbsoluteIntent=null)},g=async()=>{const b={type:"visibility-will-change",layerId:t,enabled:l,origin:i,intentEpoch:u,...r?{notificationToken:r}:{}};if(u!==c.visibilityIntentEpoch)return this._notifyListeners({...b,type:"visibility-cancelled",...this._visibilityCancellationMetadata(c,u,null,"queued")}),!1;if(o!=null&&o.aborted)return c.pendingVisibilityAdoptionEpoch===u&&(c.pendingVisibilityAdoptionEpoch=0,this._settleLifecycle(c),this._publishActivity({type:"status"})),this._notifyListeners({...b,type:"visibility-cancelled",...this._visibilityCancellationMetadata(c,u,o,"queued")}),!1;if(c.pendingVisibilityAdoptionEpoch===u&&c.enabled===l&&!c.lifecycleUncertain){const M=await this._visibilityBlockReason(b);if(u!==c.visibilityIntentEpoch)return c.pendingVisibilityAdoptionEpoch===u&&(c.pendingVisibilityAdoptionEpoch=c.visibilityIntentEpoch),c.lifecycleState=c.visibilityIntentEnabled?"enabling":"disabling",this._syncModuleLifecyclePresentation(c),this._publishActivity({type:"status"}),this._notifyListeners({...b,type:"visibility-cancelled",...this._visibilityCancellationMetadata(c,u,null,"adoption")}),!1;if(o!=null&&o.aborted)return c.pendingVisibilityAdoptionEpoch===u&&(c.pendingVisibilityAdoptionEpoch=0,this._settleLifecycle(c),this._publishActivity({type:"status"}),this._notifyListeners({...b,type:"visibility-cancelled",...this._visibilityCancellationMetadata(c,u,o,"adoption")})),!1;if(M){if(c.pendingVisibilityAdoptionEpoch=0,this._publishActivity({type:"status"}),c.enabled===l){const w=new AbortController,E={intentEpoch:u,enabled:!l,controller:w};if(c.activeVisibilityIntent=E,c.latestQueuedAbsoluteIntent={intentEpoch:u,enabled:!l},this._notifyListeners({...b,type:"visibility-blocked",reason:M}),u!==c.visibilityIntentEpoch||w.signal.aborted)return c.activeVisibilityIntent===E&&(c.activeVisibilityIntent=null),c.lifecycleState=c.visibilityIntentEnabled?"enabling":"disabling",c.pendingVisibilityAdoptionEpoch=c.visibilityIntentEpoch,this._syncModuleLifecyclePresentation(c),!1;try{await this._doToggle(c,t,i,{signal:w.signal,targetEnabled:!l,notificationToken:r,intentEpoch:u})}finally{c.activeVisibilityIntent===E&&(c.activeVisibilityIntent=null)}return!1}return this._notifyListeners({...b,type:"visibility-blocked",reason:M}),this._settleLifecycle(c),!1}return c.pendingVisibilityAdoptionEpoch=0,this._settleLifecycle(c),u!==c.visibilityIntentEpoch?(c.lifecycleState=c.visibilityIntentEnabled?"enabling":"disabling",c.pendingVisibilityAdoptionEpoch=c.visibilityIntentEpoch,this._syncModuleLifecyclePresentation(c),!1):(this._publishActivity({type:"status"}),this._notifyListeners({type:"visibility",layerId:t,enabled:l,origin:i,intentEpoch:u,...r?{notificationToken:r}:{}}),!0)}if(c.enabled===l&&!c.lifecycleUncertain)return(c.lifecycleState==="enabling"||c.lifecycleState==="disabling")&&this._settleLifecycle(c),this._publishActivity({type:"status"}),this._notifyListeners({type:"visibility",layerId:t,enabled:l,origin:i,intentEpoch:u,...r?{notificationToken:r}:{}}),!0;c.pendingVisibilityAdoptionEpoch=0;const C=new AbortController,y=()=>C.abort(o==null?void 0:o.reason);o==null||o.addEventListener("abort",y,{once:!0});const v={intentEpoch:u,enabled:l,controller:C};c.activeVisibilityIntent=v;try{return await this._doToggle(c,t,i,{signal:C.signal,targetEnabled:l,notificationToken:r,intentEpoch:u,suppressWillChangeNotification:s,beforeEnableParams:a})}finally{o==null||o.removeEventListener("abort",y),c.activeVisibilityIntent===v&&(c.activeVisibilityIntent=null)}},_=this._enqueueToggle(c,async()=>{try{return await g()}finally{p()}});return _.then(b=>{const C=c.visibilityIntentFailures.get(u)||null;c.visibilityIntentFailures.delete(u),f.completed=!0,f.result=b,f.error=(C==null?void 0:C.error)||null,f.settledEnabled=c.enabled,f.uncertain=c.lifecycleUncertain,f.resolve({intentEpoch:u,enabled:l,origin:i,phase:(C==null?void 0:C.phase)||f.phase,result:b,...C!=null&&C.error?{error:C.error}:{},settledEnabled:c.enabled,uncertain:c.lifecycleUncertain,succeeded:b!==!1&&c.enabled===l&&!c.lifecycleUncertain,cancellationReason:f.cancellationReason||null,successorIntentEpoch:f.successorIntentEpoch??null,successorEnabled:f.successorEnabled??null,successorOrigin:f.successorOrigin??null})},b=>{c.visibilityIntentFailures.delete(u),f.completed=!0,f.error=b,f.resolve({intentEpoch:u,enabled:l,origin:i,phase:f.phase,result:!1,error:b,settledEnabled:c.enabled,uncertain:c.lifecycleUncertain,succeeded:!1,cancellationReason:f.cancellationReason||null,successorIntentEpoch:f.successorIntentEpoch??null,successorEnabled:f.successorEnabled??null,successorOrigin:f.successorOrigin??null})}),{intentEpoch:u,promise:_}}async _waitForVisibilityIntent(t,n){var o,r;const i=(r=(o=this.layers.get(t))==null?void 0:o.visibilityIntentRecords)==null?void 0:r.get(n);return i?i.settled:null}async _waitForAuthoritativeVisibilityIntent(t,n){const i=this.layers.get(t);if(!i||!Number.isInteger(n))return null;let o=n,r=null;for(;Number.isInteger(o);){if(r=await this._waitForVisibilityIntent(t,o),!r)return null;const s=i.visibilityIntentEpoch>o?i.visibilityIntentEpoch:r.successorIntentEpoch;if(!Number.isInteger(s)||s<=o)break;if(r.cancellationReason!=="superseded")return null;o=s}return r}_effectiveEnabled(t){return t.clearVisibilityReservation&&t.visibilityIntentEpoch===t.clearVisibilityReservation.intentEpoch?!1:t.latestQueuedAbsoluteIntent?t.latestQueuedAbsoluteIntent.enabled:t.lifecycleState==="enabling"?!0:t.lifecycleState==="disabling"?!1:t.enabled}isEffectivelyEnabled(t){const n=this.layers.get(t);return n?this._effectiveEnabled(n):!1}getEnabledLayerIds(){return new Set([...this.layers].filter(([,t])=>this._effectiveEnabled(t)).map(([t])=>t))}async clearSelectedLayers({origin:t="user",notificationToken:n=null}={}){var c;const i=Symbol("clear-selected-layers"),o=[...this.layers].filter(([,l])=>this._effectiveEnabled(l)).map(([l,u])=>({layerId:l,intentEpoch:u.visibilityIntentEpoch})).reverse();for(const{layerId:l,intentEpoch:u}of o){const h=this.layers.get(l);h&&(h.clearVisibilityReservation={clearBatchId:i,intentEpoch:u})}const r=o.map(({layerId:l})=>l),s=new Map;try{for(const{layerId:l,intentEpoch:u}of o){const h=this.layers.get(l);if(h&&h.visibilityIntentEpoch!==u){s.set(l,{superseded:!0});continue}try{const f=h.visibilityIntentEpoch+1,p=await this.setEnabled(l,!1,{origin:t,...n?{notificationToken:n}:{}});s.set(l,{result:p,superseded:h.visibilityIntentEpoch!==f})}catch(f){s.set(l,{error:f})}}}finally{for(const{layerId:l}of o){const u=this.layers.get(l);((c=u==null?void 0:u.clearVisibilityReservation)==null?void 0:c.clearBatchId)===i&&(u.clearVisibilityReservation=null)}}const a=r.map(l=>{const u=this.getLayerLifecycleState(l)||{enabled:!1,lifecycleState:"missing",uncertain:!0},h=s.get(l)||{},d=!u.enabled&&u.lifecycleState==="disabled"&&!u.uncertain;return{id:l,requested:!1,cleared:d,result:h.result,error:h.error||null,superseded:h.superseded===!0,...u}});return{targetIds:r,items:a,clearedIds:a.filter(l=>l.cleared).map(l=>l.id),notClearedIds:a.filter(l=>!l.cleared).map(l=>l.id)}}async restoreEnabledLayerIds(t,{origin:n="programmatic",excludeLayerIds:i=[],notificationToken:o=null,signal:r=null}={}){const s=new Set(t||[]),a=new Set(i||[]),c=[...this.layers.keys()].filter(_=>{if(a.has(_))return!1;const m=this.layers.get(_);return!(m!=null&&m.destroying&&!s.has(_))}),l={origin:n,...o?{notificationToken:o}:{},...r?{signal:r}:{}},u=c.map(_=>this._setEnabledWithIntent(_,s.has(_),l)),h=await Promise.allSettled(u.map((_,m)=>this._waitForAuthoritativeVisibilityIntent(c[m],_.intentEpoch))),d=h.flatMap((_,m)=>{var w;if(_.status==="rejected")return[c[m]];const b=_.value,C=c[m],y=this.getLayerLifecycleState(C),v=s.has(C);return!b||b.error||!y||y.enabled!==v||y.lifecycleState!==(v?"enabled":"disabled")||y.uncertain||((w=this.layers.get(C))==null?void 0:w.latestQueuedAbsoluteIntent)?[C]:[]});if(d.length===0)return;const f=c.indexOf(d[0]),p=h[f],g=p.status==="rejected"?p.reason:new Error(`Failed to restore layer "${c[f]}" visibility`);throw g.failedLayerIds=[...new Set([...Array.isArray(g.failedLayerIds)?g.failedLayerIds:[],...d])],g}async waitForLayerSettled(t){const n=this.layers.get(t);n&&await n.toggleChain.catch(()=>{})}_reserveLayerParamsIntent(t,n,i="programmatic"){var s;const o=this.layers.get(t);if(!o||o.destroying||typeof((s=o.module)==null?void 0:s.setParams)!="function")return null;Ad(o,i,"explicit-params");const r=++o.paramsIntentEpoch;return o.paramsIntentOrigin=i,this._notifyListeners({type:"params-requested",layerId:t,params:jn(n||{}),origin:i,paramsIntentEpoch:r}),r}_applyLayerParamsIntent(t,n,{origin:i="programmatic",paramsIntentEpoch:o=null}={}){const r=this.layers.get(t);if(!r||!r.module||typeof r.module.setParams!="function")return{succeeded:!1,error:ds(t),params:null};if(!Number.isInteger(o)||r.paramsIntentEpoch!==o){const s={succeeded:!1,cancellationReason:"superseded",params:null};return this._notifyListeners({type:"params-cancelled",layerId:t,origin:i,paramsIntentEpoch:o,cancellationReason:s.cancellationReason,successorParamsIntentEpoch:r.paramsIntentEpoch,successorOrigin:r.paramsIntentOrigin}),s}try{if(r.module.setParams(n||{},{origin:i,paramsIntentEpoch:o})===!1)throw ds(t);if(r.paramsIntentEpoch!==o){const c={succeeded:!1,cancellationReason:"superseded",params:null};return this._notifyListeners({type:"params-cancelled",layerId:t,origin:i,paramsIntentEpoch:o,cancellationReason:c.cancellationReason,successorParamsIntentEpoch:r.paramsIntentEpoch,successorOrigin:r.paramsIntentOrigin}),c}const a=this.getLayerParams(t)||jn(n||{});return this._publishActivity({type:"status"}),this._publishActivity({type:"params-settled",layerId:t}),this._notifyListeners({type:"params",layerId:t,params:a,requestedParams:jn(n||{}),origin:i,paramsIntentEpoch:o}),{succeeded:!0,params:a,paramsIntentEpoch:o}}catch(s){return console.warn(`[Data] ${t} setParams error:`,s),this._notifyListeners({type:"params-failed",layerId:t,params:jn(n||{}),origin:i,paramsIntentEpoch:o,error:s}),{succeeded:!1,error:s,params:null,paramsIntentEpoch:o}}}setLayerParams(t,n,{origin:i="programmatic"}={}){const o=this._reserveLayerParamsIntent(t,n,i);return Number.isInteger(o)?this._applyLayerParamsIntent(t,n,{origin:i,paramsIntentEpoch:o}).succeeded:!1}cancelPendingLayerRestore(t,{origin:n="programmatic",reason:i="cancelled"}={}){var s,a;const o=this.layers.get(t),r=((s=o==null?void 0:o.module)==null?void 0:s.cancelPendingRestore)||((a=o==null?void 0:o.module)==null?void 0:a.cancelPendingTrackingRestore);if(typeof r!="function")return!1;try{return r.call(o.module,{origin:n,reason:i}),!0}catch(c){return console.warn(`[Data] ${t} pending restore cancellation error:`,c),!1}}adoptLayerParams(t,n,{origin:i="programmatic"}={}){const o=jn(n||{}),r=this._reserveLayerParamsIntent(t,o,i);if(!Number.isInteger(r))return!1;const s=this.getLayerParams(t);if(!(s&&Object.entries(o).every(([c,l])=>Object.is(s[c],l)))){const c=ds(t);return this._notifyListeners({type:"params-failed",layerId:t,params:o,origin:i,paramsIntentEpoch:r,error:c}),!1}return this._publishActivity({type:"status"}),this._publishActivity({type:"params-settled",layerId:t}),this._notifyListeners({type:"params",layerId:t,params:s,requestedParams:o,origin:i,paramsIntentEpoch:r}),!0}adoptLayerVisibility(t,n,{origin:i="programmatic",adoptedFromSelection:o=!1}={}){const r=this.layers.get(t),s=!!n;return!r||r.enabled!==s||r.lifecycleUncertain?!1:(Ad(r,i,"superseded-by-explicit-visibility-adoption"),this._publishActivity({type:"status"}),this._notifyListeners({type:"visibility",layerId:t,enabled:s,origin:i,intentEpoch:r.visibilityIntentEpoch,adopted:!0,adoptedFromSelection:!!o}),!0)}async restoreLayerState(t,{enabled:n=!1,params:i=null}={},{origin:o="programmatic",signal:r=null}={}){if(!this._registrationsFinalized)throw new Error("Layer restore requires finalized registrations");const s=this.layers.get(t),a=!!n;if(!s)return{layerId:t,targetEnabled:a,origin:o,phase:"missing",settledEnabled:!1,lifecycleState:"missing",lifecycleUncertain:!1,appliedOptions:{},errorClass:"UnknownLayer",persistenceWrite:!1,succeeded:!1};const c=i&&typeof i=="object"&&Object.keys(i).length?jn(i):null;let l=null,u=null;if(c){const b=this._reserveLayerParamsIntent(t,c,o);Number.isInteger(b)?a&&!s.enabled?u={params:c,origin:o,paramsIntentEpoch:b,result:null}:l=this._applyLayerParamsIntent(t,c,{origin:o,paramsIntentEpoch:b}):l={succeeded:!1,error:ds(t)}}const h=this._setEnabledWithIntent(t,a,{origin:o,signal:r,beforeEnableParams:u}),d=await this._waitForVisibilityIntent(t,h.intentEpoch),f=(d==null?void 0:d.cancellationReason)==="superseded"?await this._waitForAuthoritativeVisibilityIntent(t,h.intentEpoch):d;l=l||(u==null?void 0:u.result);const p=this.getLayerLifecycleState(t),g=!c||(l==null?void 0:l.succeeded)===!0,_=(f==null?void 0:f.succeeded)===!0&&(p==null?void 0:p.enabled)===a&&(p==null?void 0:p.uncertain)===!1,m=(l==null?void 0:l.error)||(f==null?void 0:f.error)||(d==null?void 0:d.error)||null;return{layerId:t,targetEnabled:a,origin:o,phase:(d==null?void 0:d.phase)||(r!=null&&r.aborted?"reserved":"unknown"),completionPhase:(f==null?void 0:f.phase)||null,settledEnabled:!!(p!=null&&p.enabled),lifecycleState:(p==null?void 0:p.lifecycleState)||"missing",lifecycleUncertain:!!(p!=null&&p.uncertain),appliedOptions:g&&c?c:{},intentEpoch:h.intentEpoch,authoritativeIntentEpoch:(f==null?void 0:f.intentEpoch)??h.intentEpoch,authoritativeEnabled:(f==null?void 0:f.enabled)??null,authoritativeOrigin:(f==null?void 0:f.origin)??null,paramsIntentEpoch:(l==null?void 0:l.paramsIntentEpoch)??(u==null?void 0:u.paramsIntentEpoch)??null,cancellationReason:(d==null?void 0:d.cancellationReason)||(l==null?void 0:l.cancellationReason)||null,successorIntentEpoch:(d==null?void 0:d.successorIntentEpoch)??null,successorEnabled:(d==null?void 0:d.successorEnabled)??null,successorOrigin:(d==null?void 0:d.successorOrigin)??null,errorClass:(m==null?void 0:m.name)||(r!=null&&r.aborted?"AbortError":null),...m?{error:String(m.message||m)}:{},persistenceWrite:!1,succeeded:g&&_}}getLayerParams(t){const n=this.layers.get(t);if(!n||!n.module||typeof n.module.getParams!="function")return null;try{const i=n.module.getParams();return!i||typeof i!="object"?null:jn(i)}catch(i){return console.warn(`[Data] ${t} getParams error:`,i),null}}async destroyLayer(t){var o;const n=this.layers.get(t);if(!n||n.destroying)return!1;n.destroying=!0,this._invalidateRefresh(t,n,"layer-destroyed");const i=++n.visibilityIntentEpoch;n.visibilityIntentEnabled=!1,n.visibilityIntentOrigin="teardown",n.latestQueuedAbsoluteIntent={intentEpoch:i,enabled:!1},n.clearVisibilityReservation=null,(o=n.activeVisibilityIntent)==null||o.controller.abort(kd),n.paramsIntentEpoch+=1,n.paramsIntentOrigin="teardown",await n.toggleChain.catch(()=>{});for(const r of this._beforeDestroyListeners)try{await r({type:"before-destroy",layerId:t})}catch(s){console.warn("[Data] before-destroy listener error:",s)}if(await n.toggleChain.catch(()=>{}),this.layers.get(t)!==n)return!1;if(n.latestQueuedAbsoluteIntent=null,n.enabled){try{if(await n.module.disable(this.viewer)===!1)throw an(t,"destroy-disable")}catch(r){return console.warn(`[Data] ${t} disable error:`,r),n.destroying=!1,n.visibilityIntentEnabled=n.enabled,this._settleLifecycle(n),this._publishActivity({type:"status"}),!1}n.intervalId&&(clearInterval(n.intervalId),n.intervalId=null),n.enabled=!1}if(typeof n.module.destroy=="function")try{if(await n.module.destroy(this.viewer)===!1)throw an(t,"destroy")}catch(r){return console.warn(`[Data] ${t} destroy error:`,r),n.destroying=!1,n.visibilityIntentEnabled=n.enabled,this._settleLifecycle(n),this._publishActivity({type:"status"}),!1}return this.layers.delete(t),this._qaLayerIds.delete(t),!0}async destroyAll(){this._publishActivity({type:"destroy-all"});for(const t of[...this.layers.keys()])await this.destroyLayer(t)}isEnabled(t){const n=this.layers.get(t);return n?n.enabled:!1}getLayerLifecycleState(t){const n=this.layers.get(t);return n?Object.freeze({enabled:n.enabled,lifecycleState:n.lifecycleState,uncertain:n.lifecycleUncertain}):null}getAll(){const t=[];for(const[n,i]of this.layers)t.push({id:n,name:i.module.name,icon:i.module.icon,source:i.module.source,showInTogglePanel:i.module.showInTogglePanel!==!1,requiresKeyId:i.module.requiresKeyId||null,enabled:i.enabled,lifecycleState:i.lifecycleState,lifecycleUncertain:i.lifecycleUncertain,stats:this._normalizedStats(i)});return t}subscribe(t){return typeof t!="function"?()=>{}:(this._listeners.add(t),()=>this._listeners.delete(t))}subscribeVisibilityRequests(t){return typeof t!="function"?()=>{}:(this._visibilityRequestListeners.add(t),()=>this._visibilityRequestListeners.delete(t))}addVisibilityGuard(t){return typeof t!="function"?()=>{}:(this._visibilityGuards.add(t),()=>this._visibilityGuards.delete(t))}subscribeBeforeDestroy(t){return typeof t!="function"?()=>{}:(this._beforeDestroyListeners.add(t),()=>this._beforeDestroyListeners.delete(t))}_notifyListeners(t){for(const n of this._listeners)try{n(t)}catch(i){console.warn("[Data] listener error:",i)}}_notifyVisibilityRequest(t){for(const n of this._visibilityRequestListeners)try{n(t)}catch(i){console.warn("[Data] visibility request listener error:",i)}}async _visibilityBlockReason(t){for(const n of this._visibilityGuards)try{const i=await n(t);if(typeof i=="string"&&i.trim())return i.trim();if(i&&typeof i.reason=="string"&&i.reason.trim())return i.reason.trim()}catch(i){console.warn("[Data] visibility guard error:",i)}return null}subscribeActivity(t){return typeof t!="function"?()=>{}:(this._activityListeners.add(t),()=>this._activityListeners.delete(t))}_publishActivity(t){for(const n of this._activityListeners)try{n(t)}catch(i){console.warn("[Data] activity listener error:",i)}}}class _9{constructor(t,{requestRender:n=qt,invalidateDetection:i=OK}={}){this.manager=t,this._panel=null,this.pendingVisible=!1,this._unsubscribe=t.subscribeActivity(o=>{if(o.type==="status")this.refresh();else if(o.type==="destroy-all")this.destroy();else{const r=o.type==="data-updated"?`layer-tick:${o.layerId}`:o.type==="visibility-settled"?"layer-visibility":o.type==="params-settled"?`layer-params:${o.layerId}`:null;if(!r)return;n(r),o.type!=="params-settled"&&i(r)}})}get panel(){return this._panel||(this._panel=new Oj({getLayers:()=>this.manager.getAll(),isEnabled:t=>this.manager.isEnabled(t),setEnabled:(t,n,i)=>this.manager.setEnabled(t,n,i),setLayerParams:(t,n,i)=>this.manager.setLayerParams(t,n,i),getRowControls:t=>{var i,o;const n=(i=this.manager.layers.get(t))==null?void 0:i.module;try{return((o=n==null?void 0:n.getRowControls)==null?void 0:o.call(n))||null}catch(r){return console.warn(`[Data] ${t} getRowControls error:`,r),null}},hasRowControls:t=>{var n,i;return typeof((i=(n=this.manager.layers.get(t))==null?void 0:n.module)==null?void 0:i.getRowControls)=="function"},subscribeRowControls:(t,n)=>{var o,r;const i=(o=this.manager.layers.get(t))==null?void 0:o.module;return(r=i==null?void 0:i.setRowControlsListener)==null||r.call(i,n),()=>{var s;return(s=i==null?void 0:i.setRowControlsListener)==null?void 0:s.call(i,null)}},onHiddenRefresh:()=>{this.pendingVisible=!0}})),this._panel}mount(t){this.panel.mount(t)}refresh(){var t;(t=this._panel)==null||t._refreshTogglePanel()}flushVisible(){this.pendingVisible&&(this.pendingVisible=!1,this.refresh())}destroy(){var t,n;(t=this._panel)==null||t.destroy(),this._panel=null,this.pendingVisible=!1,(n=this._unsubscribe)==null||n.call(this),this._unsubscribe=null}}function b9({scene:{viewer:e},controls:{styleManager:t},catalog:n,allowQaRegistration:i,onData:o,defer:r}){var c;const s=new g9(e,{allowQaRegistration:i});r(async()=>{if(await s.destroyAll(),s.layers.size)throw new Error(`Data layers could not be destroyed: ${[...s.layers.keys()].join(", ")}`)});const a=new _9(s);if(r(()=>a.destroy()),o==null||o(s),!(n!=null&&n.layers)||!(n!=null&&n.metadata))throw new TypeError("An application layer catalog is required");for(const l of n.layers)s.register(l);for(const l of n.layers)(c=l.attachDataManager)==null||c.call(l,s);if(s.finalizeRegistrations(n.metadata),i){window.__gevQaRegisterLayer=(h,d)=>{if(h!==s)throw new Error("QA layer manager mismatch");return s.registerForQa(d)},window.__gevQaUnregisterLayer=(h,d)=>{if(h!==s)throw new Error("QA layer manager mismatch");return s.unregisterForQa(d)};const l=window.__gevQaRegisterLayer,u=window.__gevQaUnregisterLayer;r(()=>{window.__gevQaRegisterLayer===l&&delete window.__gevQaRegisterLayer,window.__gevQaUnregisterLayer===u&&delete window.__gevQaUnregisterLayer})}return a.mount(document.getElementById("data-toggles")),t.attachDataManager(s),{dataManager:s,catalog:n,presentation:a}}function C9(e){return b9({catalog:(e==null?void 0:e.catalog)??UE(),...e})}function y9(e=document){return Object.fromEntries(Object.entries({panel:"scene-panel",select:"scene-select",new:"scene-new-btn",delete:"scene-delete-btn",capture:"scene-capture-btn",update:"scene-update-shot-btn",shots:"scene-shot-list",start:"scene-start-btn",stop:"scene-stop-btn",next:"scene-next-btn",export:"scene-export-btn",import:"scene-import-btn",file:"scene-import-file",download:"scene-download-btn",status:"scene-status",progress:"scene-progress-fill",runtime:"scene-runtime"}).map(([n,i])=>[n,e.getElementById(i)]))}function v9(e,{scenes:t,selectedSceneId:n}){if(e){e.textContent="";for(const i of t){const o=document.createElement("option");o.value=i.id,o.textContent=i.title,e.appendChild(o)}n&&(e.value=n)}}function M9(e,t,{listen:n,select:i,rename:o,load:r,remove:s}){var c,l,u;if(!e)return;const a=t.scenes.find(h=>h.id===t.selectedSceneId);if(e.textContent="",!a||a.shots.length===0){const h=document.createElement("div");h.className="scene-shot-empty",h.textContent="No shots yet. Use CAPTURE SHOT to save current look.",e.appendChild(h);return}for(const h of a.shots){const d=document.createElement("div");d.className="scene-shot-row",d.dataset.sceneShotId=h.id,d.classList.toggle("active",h.id===t.selectedShotId);const f=document.createElement("div");f.className="scene-shot-top";const p=document.createElement("div");p.className="scene-shot-label",p.textContent=h.title,n(p,"click",()=>i(h.id)),n(p,"dblclick",()=>{const v=window.prompt("Shot title",h.title);v&&o(a.id,h.id,v)});const g=document.createElement("div");g.className="scene-shot-actions";const _=document.createElement("button");_.className="scene-shot-btn",_.textContent="LOAD",n(_,"click",()=>r(a.id,h.id));const m=document.createElement("button");m.className="scene-shot-btn scene-shot-danger",m.textContent="DEL",n(m,"click",()=>s(a.id,h.id)),g.appendChild(_),g.appendChild(m),f.appendChild(p),f.appendChild(g);const b=document.createElement("div");b.className="scene-shot-meta";const C=((l=(c=h.visual)==null?void 0:c.detection)==null?void 0:l.mode)||"OFF",y=((u=h.visual)==null?void 0:u.style)||"normal";b.textContent=`${y.toUpperCase()} · ${C} · ${h.durationSec.toFixed(1)}s + ${h.holdSec.toFixed(1)}s`,d.appendChild(f),d.appendChild(b),e.appendChild(d)}}function hC(e,t){for(const n of(e==null?void 0:e.children)||[])n.classList.toggle("active",n.dataset.sceneShotId===t)}function w9(e,t,n){var i;for(const o of["start","next","select","new","delete","capture","update","export","import"])e[o]&&(e[o].disabled=t);e.stop&&(e.stop.disabled=!t),e.download&&(e.download.disabled=!n),(i=e.panel)==null||i.classList.toggle("running",t)}function E9(e,t){if(!e)return;const n=Math.round(Math.max(0,Math.min(1,t))*100);e.style.width=`${n}%`,e.textContent=`${n}%`}function fC(e,t){e&&(e.textContent=t,e.classList.toggle("active",!!t))}class T9{constructor({read:t,actions:n,subscribe:i,elements:o=y9()}){if(this.read=t,this.actions=n,this.elements=o,this.destroyed=!1,this.actionGeneration=0,this.removers=[],this.rowRemovers=[],this.playbackKeyRemover=null,!!o.select){i?this.unsubscribe=i(r=>this.present(r)):(this.renderSceneSelect(),this.renderShotList()),this.listen(o.select,"change",()=>this.run("selectScene",o.select.value));for(const[r,s]of Object.entries({capture:"capture",update:"update",next:"next",export:"export",download:"download"}))this.listen(o[r],"click",()=>this.run(s));this.listen(o.new,"click",()=>this.createScene()),this.listen(o.delete,"click",()=>this.deleteSelectedScene()),this.listen(o.start,"click",()=>this.run("start",this.read().selectedSceneId)),this.listen(o.stop,"click",()=>this.run("stop","Stopped")),this.listen(o.import,"click",()=>{var r;return(r=o.file)==null?void 0:r.click()}),this.listen(o.file,"change",async()=>{var s,a;const r=(a=(s=o.file)==null?void 0:s.files)==null?void 0:a[0];r&&(await this.run("import",r),this.destroyed||(o.file.value=""))}),i||(this.updateStatus("Ready"),this.setProgress(0),this.setButtons(!1))}}present({state:t,change:n,initial:i}){if(this.destroyed)return;const o=n==null?void 0:n.type;(i||["scene-options-changed","scene-created","scene-deleted","project-imported"].includes(o))&&this.renderSceneSelect(),(i||["shots-changed","scene-created","scene-deleted","shot-captured","shot-updated","shot-renamed","shot-deleted","project-imported"].includes(o))&&this.renderShotList(),o==="selection-changed"&&hC(this.elements.shots,t.selectedShotId),(i||o==="buttons-changed")&&this.setButtons(t.running),(i||o==="progress-changed")&&this.setProgress(t.progress),(i||o==="status-changed")&&this.updateStatus(t.status),(i||o==="runtime-changed")&&this.updateRuntime(t.runtime),(i||o==="playback-presentation")&&this.setPlaybackActive(t.playbackActive),(i||o==="playback-keyboard")&&this.setPlaybackKeyboardEnabled(t.keyboardEnabled),o==="project-exported"&&this.updateStatus(t.status),o==="shot-loaded"&&this.updateStatus(t.status),o==="run-event"&&n.event==="shot_start"&&this.setButtons(t.running)}listen(t,n,i,o=this.removers){if(!t)return;const r=s=>{if(!this.destroyed)return i(s)};t.addEventListener(n,r),o.push(()=>t.removeEventListener(n,r))}run(t,...n){if(this.destroyed)return;const i=++this.actionGeneration,o=()=>{!this.destroyed&&i===this.actionGeneration&&this.updateStatus("Scene action failed")};try{const r=this.actions[t](...n);return r!=null&&r.then?Promise.resolve(r).catch(o):r}catch{o()}}renderSceneSelect(){this.destroyed||v9(this.elements.select,this.read())}createScene(){if(this.destroyed)return;const t=window.prompt("New scene name",`Scene ${this.read().scenes.length+1}`);t&&this.run("create",t)}deleteSelectedScene(){if(this.destroyed)return;const t=this.read(),n=t.scenes.find(i=>i.id===t.selectedSceneId);n&&window.confirm(`Delete scene "${n.title}" and all shots?`)&&this.run("deleteScene")}deleteShot(t,n){if(this.destroyed)return;const i=this.read().scenes.find(r=>r.id===t),o=i==null?void 0:i.shots.find(r=>r.id===n);o&&window.confirm(`Delete shot "${o.title}"?`)&&this.run("deleteShot",t,n)}renderShotList(){if(!this.destroyed){for(const t of this.rowRemovers.splice(0))t();M9(this.elements.shots,this.read(),{listen:(t,n,i)=>this.listen(t,n,i,this.rowRemovers),select:t=>{this.run("selectShot",t),this.destroyed||hC(this.elements.shots,this.read().selectedShotId)},rename:(t,n,i)=>this.run("renameShot",t,n,i),load:(t,n)=>this.run("load",t,n),remove:(t,n)=>this.deleteShot(t,n)})}}setButtons(t){this.destroyed||w9(this.elements,t,this.read().hasRun)}setProgress(t){this.destroyed||E9(this.elements.progress,t)}updateStatus(t){!this.destroyed&&this.elements.status&&(this.elements.status.textContent=t)}updateRuntime(t){this.destroyed||fC(this.elements.runtime,t)}setPlaybackActive(t){this.destroyed&&t||document.body.classList.toggle("scene-playback-mode",t)}setPlaybackKeyboardEnabled(t){var n;if(!t)(n=this.playbackKeyRemover)==null||n.call(this),this.playbackKeyRemover=null;else if(!this.destroyed&&!this.playbackKeyRemover){const i=o=>{!this.destroyed&&o.key==="Escape"&&this.read().running&&this.run("stop","Stopped (Esc)")};document.addEventListener("keydown",i),this.playbackKeyRemover=()=>document.removeEventListener("keydown",i)}}destroy(){var t;if(!this.destroyed){this.destroyed=!0,this.actionGeneration++,(t=this.unsubscribe)==null||t.call(this),this.unsubscribe=null,this.setPlaybackKeyboardEnabled(!1);for(const n of[...this.removers.splice(0),...this.rowRemovers.splice(0)])n();this.elements.shots&&(this.elements.shots.textContent=""),fC(this.elements.runtime,""),this.setPlaybackActive(!1)}}}const k9=[{id:"flights-radar",title:"Global Flights Radar",durationSec:30,style:"retro",ui:{hidePanels:!0,hudMode:"minimal",safeFrame:"16:9"},layers:{flights:!0,satellites:!1,earthquakes:!1,traffic:!1},post:{bloom:62,sharpen:!0,detectionMode:"OFF"},cameraPath:[{lat:20,lon:-30,alt:19e6,heading:25,pitch:-65,roll:0,duration:6,hold:1},{lat:46,lon:2,alt:8e6,heading:40,pitch:-52,roll:0,duration:5,hold:1},{lat:35,lon:139,alt:42e5,heading:22,pitch:-46,roll:0,duration:5,hold:1},{lat:37.6,lon:-122.4,alt:17e5,heading:8,pitch:-40,roll:0,duration:5,hold:1},{lat:0,lon:-20,alt:12e6,heading:-10,pitch:-70,roll:0,duration:4,hold:0}]},{id:"orbital-watch",title:"Orbital Watch",durationSec:32,style:"surveillance",ui:{hidePanels:!0,hudMode:"full",safeFrame:"16:9"},layers:{flights:!1,satellites:!0,earthquakes:!1,traffic:!1},post:{bloom:58,sharpen:!1,detectionMode:"SPARSE",styleParams:{surveillance:{gain:.62,bloom:.38,scanlineStr:.9,pixelation:2.1}}},cameraPath:[{lat:28,lon:-82,alt:22e6,heading:0,pitch:-82,roll:0,duration:7,hold:1},{lat:10,lon:20,alt:12e6,heading:18,pitch:-74,roll:0,duration:5,hold:1},{lat:35.7,lon:139.7,alt:65e5,heading:24,pitch:-64,roll:0,duration:5,hold:1},{lat:48.8,lon:2.3,alt:3e6,heading:32,pitch:-58,roll:0,duration:5,hold:1},{lat:30,lon:-25,alt:15e6,heading:-20,pitch:-78,roll:0,duration:4,hold:0}]},{id:"thermal-threats",title:"Thermal Threat Board",durationSec:26,style:"thermal",ui:{hidePanels:!0,hudMode:"full",safeFrame:"16:9"},layers:{flights:!1,satellites:!1,earthquakes:!0,traffic:!1},post:{bloom:72,sharpen:!0,detectionMode:"OFF",styleParams:{thermal:{sensitivity:.84,bloom:.78,mode:0,pixelation:1.9}}},cameraPath:[{lat:37,lon:-121,alt:52e5,heading:20,pitch:-62,roll:0,duration:5,hold:1},{lat:35.7,lon:140,alt:31e5,heading:5,pitch:-55,roll:0,duration:5,hold:1},{lat:-36.8,lon:174.7,alt:26e5,heading:-12,pitch:-50,roll:0,duration:5,hold:1},{lat:38,lon:-10,alt:9e6,heading:12,pitch:-70,roll:0,duration:4,hold:0}]},{id:"city-overload",title:"City Overload",durationSec:30,style:"surveillance",ui:{hidePanels:!0,hudMode:"minimal",safeFrame:"9:16"},layers:{flights:!0,satellites:!0,earthquakes:!1,traffic:!0},post:{bloom:65,sharpen:!0,detectionMode:"PANOPTIC",styleParams:{surveillance:{gain:.68,bloom:.42,scanlineStr:1,pixelation:2.4}}},cameraPath:[{lat:40.73,lon:-74,alt:15e5,heading:25,pitch:-44,roll:0,duration:5,hold:1},{lat:40.73,lon:-74,alt:55e4,heading:58,pitch:-36,roll:0,duration:4,hold:1},{lat:40.73,lon:-74,alt:26e4,heading:102,pitch:-33,roll:0,duration:4,hold:1},{lat:34.05,lon:-118.24,alt:12e5,heading:45,pitch:-42,roll:0,duration:5,hold:1},{lat:51.5,lon:-.12,alt:12e5,heading:22,pitch:-44,roll:0,duration:5,hold:0}]},{id:"omniscience-pullback",title:"Omniscience Pullback",durationSec:36,style:"retro",ui:{hidePanels:!0,hudMode:"full",safeFrame:"16:9"},layers:{flights:!0,satellites:!0,earthquakes:!0,traffic:!0},post:{bloom:68,sharpen:!0,detectionMode:"SPARSE",styleParams:{retro:{pixelation:4.4,distortion:.42,instability:.58}}},cameraPath:[{lat:35.68,lon:139.76,alt:28e4,heading:30,pitch:-26,roll:0,duration:5,hold:1},{lat:35.68,lon:139.76,alt:9e5,heading:26,pitch:-38,roll:0,duration:4,hold:1},{lat:35.68,lon:139.76,alt:38e5,heading:18,pitch:-52,roll:0,duration:5,hold:1},{lat:20,lon:110,alt:95e5,heading:8,pitch:-66,roll:0,duration:5,hold:1},{lat:5,lon:30,alt:18e6,heading:-8,pitch:-78,roll:0,duration:6,hold:0}]}],mC=Object.freeze(["selectedFlightsTrackingId","selectedMilitaryTrackingId","selectedSatTrackingId"]);function A9(e){if(!e||typeof e!="object")return;if(!mC.some(n=>Object.hasOwn(e,n)))return e;const t={};for(const[n,i]of Object.entries(e))mC.includes(n)||(t[n]=i);return Object.keys(t).length?t:void 0}const I9="__scene-exclusivity-probe__";function R9(e){return e?sT({contextMode:e,change:{layerId:I9,enabled:!0}})!==null:!1}function L9(e,t){const n=t instanceof Set?t:t?new Set(t):null,i=[];for(const[o,r]of Object.entries(e||{}))n&&!n.has(o)||i.push({id:o,enabled:!!(r&&r.enabled),params:r&&r.params?A9(r.params):void 0});return i}const pC="godsEyeView.sceneProject.v2",Kr=3,Xs=4,P9=.9;function Yr(e){return`${e}-${Math.random().toString(36).slice(2,10)}`}function Oc(e){return JSON.parse(JSON.stringify(e))}function $T(e){return e&&typeof e=="object"?{enabled:!!e.enabled,params:e.params&&typeof e.params=="object"?Oc(e.params):void 0}:{enabled:!!e}}function x9(e={},{projectVersion:t=Kr,fallbackIntensity:n=50}={}){const i=Number(e.version),o=Number.isFinite(i)?i:t>=Kr?ti:1,r=Number.isFinite(Number(e.intensity))?Number(e.intensity):n;return{enabled:!!e.enabled,intensity:ca(r,o),version:ti}}function F9(e){const t=e.post||{},n=e.ui||{},i=t.styleParams&&typeof t.styleParams=="object"?Oc(t.styleParams):{},o={};for(const[u,h]of Object.entries(e.layers||{}))o[u]=$T(h);const r=n.hudMode||"minimal",s=r!=="off",a=r==="minimal"?"minimal":"tactical",l=(e.cameraPath||[]).map((u,h)=>({id:Yr("shot"),title:`Shot ${h+1}`,durationSec:Math.max(.2,u.duration||Xs),holdSec:Math.max(0,u.hold||0),camera:{lat:u.lat,lon:u.lon,alt:u.alt,heading:u.heading||0,pitch:u.pitch||-40,roll:u.roll||0},visual:{style:e.style||"normal",bloom:{enabled:typeof t.bloom=="number"?t.bloom>0:!!t.bloom,intensity:typeof t.bloom=="number"?ca(t.bloom,1):oi,version:ti},sharpen:{enabled:typeof t.sharpen=="boolean"?t.sharpen:!!t.sharpen,intensity:65},hud:{visible:s,variant:a},detection:{mode:t.detectionMode||"OFF",density:35},styleParams:i},layers:Oc(o)}));return{id:e.id||Yr("scene"),title:e.title||"Untitled Scene",shots:l}}function Qs(){return{version:Kr,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),scenes:k9.map(F9)}}function GT(e,t=0,{projectVersion:n=Kr}={}){const i=(e==null?void 0:e.camera)||{},o=(e==null?void 0:e.visual)||{},r=o.bloom||{},s=o.sharpen||{},a=o.hud||{},c=o.detection||{};return{id:(e==null?void 0:e.id)||Yr("shot"),title:(e==null?void 0:e.title)||`Shot ${t+1}`,durationSec:Math.max(.2,Number(e==null?void 0:e.durationSec)||Xs),holdSec:Math.max(0,Number(e==null?void 0:e.holdSec)||0),camera:{lat:Number(i.lat)||0,lon:Number(i.lon)||0,alt:Math.max(100,Number(i.alt)||800),heading:Number(i.heading)||0,pitch:Number(i.pitch)||-35,roll:Number(i.roll)||0},visual:{style:o.style||"normal",bloom:x9(r,{projectVersion:n,fallbackIntensity:50}),sharpen:{enabled:!!s.enabled,intensity:Math.max(0,Math.min(100,Number.isFinite(Number(s.intensity))?Number(s.intensity):65))},hud:{visible:typeof a.visible=="boolean"?a.visible:!0,variant:typeof a.variant=="string"?a.variant:"tactical"},detection:{mode:typeof c.mode=="string"?c.mode:"OFF",density:Math.max(0,Math.min(100,Number.isFinite(Number(c.density))?Number(c.density):35))},styleParams:o.styleParams&&typeof o.styleParams=="object"?Oc(o.styleParams):{}},layers:Object.fromEntries(Object.entries((e==null?void 0:e.layers)||{}).map(([l,u])=>[l,$T(u)]))}}function gC(e){if(!e||typeof e!="object")return Qs();const t=Number.isFinite(Number(e.version))?Number(e.version):1,i=(Array.isArray(e.scenes)?e.scenes:[]).map((o,r)=>{const a=(Array.isArray(o==null?void 0:o.shots)?o.shots:[]).map((c,l)=>GT(c,l,{projectVersion:t}));return{id:(o==null?void 0:o.id)||Yr("scene"),title:(o==null?void 0:o.title)||`Scene ${r+1}`,shots:a}}).filter(o=>o.shots.length>0||o.title);return i.length?{version:Kr,createdAt:e.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),scenes:i}:Qs()}class S9{constructor(t,n,i){var o,r,s;this._destroyed=!1,this._pendingWork=new Set,this.viewer=t,this.styleManager=n,this.dataManager=i,this._running=!1,this._runToken=null,this._loadGeneration=0,this._runAbort=null,this._loadAbort=null,this._progressTimer=null,this._activeRun=null,this._lastRun=null,this._lastRunJson="",this._project=this._loadProject(),this._selectedSceneId=((o=this._project.scenes[0])==null?void 0:o.id)||null,this._selectedShotId=((s=(r=this._project.scenes[0])==null?void 0:r.shots[0])==null?void 0:s.id)||null,this._presentation={status:"Ready",progress:0,runtime:"",playbackActive:!1,keyboardEnabled:!1},this._state=wc(()=>({...this.getPlaybackStatus(),...this._presentation,hasRun:!!this._lastRunJson})),this._initUI()}_trackWork(t){this._pendingWork||(this._pendingWork=new Set),this._pendingWork.add(t);const n=()=>this._pendingWork.delete(t);return t.then(n,n),t}destroy(){var t;return this._destroyPromise?this._destroyPromise:(this._destroyed=!0,(t=this._controls)==null||t.destroy(),this._state.destroy(),this._destroyPromise=Promise.resolve().then(async()=>{var n;this.stopScene("Stopped"),(n=this._loadAbort)==null||n.abort(),this._loadGeneration++,this.viewer.camera.cancelFlight(),clearTimeout(this._storageToastTimer),await Promise.allSettled(this._pendingWork||[]),clearInterval(this._progressTimer)}),this._destroyPromise)}_loadProject(){try{const t=localStorage.getItem(pC);return t?gC(JSON.parse(t)):Qs()}catch{return Qs()}}_saveProject(){this._project.updatedAt=new Date().toISOString();try{localStorage.setItem(pC,JSON.stringify(this._project))}catch(t){console.warn("[Scenes] Could not persist project (storage unavailable):",t),this._toastStorageError()}}_toastStorageError(){const t="Scene not saved — browser storage unavailable";this._updateStatus(t);try{const n=document.getElementById("toast");n&&(n.textContent=t,n.classList.add("visible"),clearTimeout(this._storageToastTimer),this._storageToastTimer=setTimeout(()=>{n.classList.remove("visible")},2600))}catch{}}subscribe(t,n){return this._state.subscribe(t,n)}_publish(t){var n;(n=this._state)==null||n.publish(t)}_shotOutcome(t,n,i,o=n.shots.indexOf(i)){t==="shot-loaded"&&(this._presentation.status=`Loaded: ${n.title} / ${i.title}`),this._publish({type:t,sceneId:n.id,sceneTitle:n.title,shot:i,index:o})}_initUI(){this._controls=new T9({subscribe:t=>this.subscribe(t),read:()=>({scenes:this._project.scenes,selectedSceneId:this._selectedSceneId,selectedShotId:this._selectedShotId,running:this._running,hasRun:!!this._lastRunJson}),actions:{selectScene:t=>{var n,i;this._selectedSceneId=t,this._selectedShotId=((i=(n=this._getSelectedScene())==null?void 0:n.shots[0])==null?void 0:i.id)||null,this._renderShotList()},selectShot:t=>{this._selectedShotId=t,this._publish({type:"selection-changed"})},renameShot:(t,n,i)=>{const{scene:o,shot:r}=this._getShot(t,n);r&&(r.title=i.trim()||r.title,this._saveProject(),this._shotOutcome("shot-renamed",o,r))},create:t=>this._createScene(t),deleteScene:()=>this._deleteSelectedScene(),capture:()=>this.captureShot(),update:()=>this.updateSelectedShot(),start:t=>this.startScene(t),stop:t=>this.stopScene(t),next:()=>this.runNextScene(),export:()=>this.exportProject(),import:t=>this.importProjectFile(t),download:()=>this.downloadLastRunMetadata(),load:(t,n)=>this.loadShot(t,n),deleteShot:(t,n)=>this.deleteShot(t,n)}})}_renderSceneSelect(){var t;this._project.scenes.some(n=>n.id===this._selectedSceneId)||(this._selectedSceneId=((t=this._project.scenes[0])==null?void 0:t.id)||null),this._publish({type:"scene-options-changed"})}_renderShotList(){const t=this._getSelectedScene();t!=null&&t.shots.length&&!t.shots.some(n=>n.id===this._selectedShotId)&&(this._selectedShotId=t.shots[0].id),this._publish({type:"shots-changed"})}_getSelectedScene(){return this._project.scenes.find(t=>t.id===this._selectedSceneId)||null}_getShot(t,n){const i=this._project.scenes.find(r=>r.id===t),o=i==null?void 0:i.shots.find(r=>r.id===n);return{scene:i,shot:o}}_createScene(t){if(!t)return;const n={id:Yr("scene"),title:t.trim()||`Scene ${this._project.scenes.length+1}`,shots:[]};this._project.scenes.push(n),this._selectedSceneId=n.id,this._selectedShotId=null,this._saveProject(),this._publish({type:"scene-created",scene:n})}_deleteSelectedScene(){var n,i,o;const t=this._getSelectedScene();t&&(this._project.scenes=this._project.scenes.filter(r=>r.id!==t.id),this._project.scenes.length||(this._project=Qs()),this._selectedSceneId=((n=this._project.scenes[0])==null?void 0:n.id)||null,this._selectedShotId=((o=(i=this._project.scenes[0])==null?void 0:i.shots[0])==null?void 0:o.id)||null,this._saveProject(),this._publish({type:"scene-deleted",scene:t}))}_captureLayerStates(){const t={};for(const n of this.dataManager.getAll()){const i=this.dataManager.getLayerParams(n.id);t[n.id]={enabled:!!n.enabled,...i?{params:i}:{}}}return t}captureShot(){const t=this._getSelectedScene();if(!t)return;const n=this.styleManager.getCameraState();if(!n){this._updateStatus("Cannot capture shot: camera not ready");return}const i=GT({id:Yr("shot"),title:`Shot ${t.shots.length+1}`,durationSec:Xs,holdSec:P9,camera:n,visual:this.styleManager.getVisualState(),layers:this._captureLayerStates()},t.shots.length);t.shots.push(i),this._selectedShotId=i.id,this._saveProject(),this._shotOutcome("shot-captured",t,i),this._updateStatus(`Captured: ${t.title} / ${i.title}`)}updateSelectedShot(){const t=this._getSelectedScene();if(!t)return;const n=t.shots.find(o=>o.id===this._selectedShotId);if(!n){this._updateStatus("Select a shot first");return}const i=this.styleManager.getCameraState();i&&(n.camera=i,n.visual=this.styleManager.getVisualState(),n.layers=this._captureLayerStates(),this._saveProject(),this._shotOutcome("shot-updated",t,n),this._updateStatus(`Updated: ${t.title} / ${n.title}`))}deleteShot(t,n){var s;const{scene:i,shot:o}=this._getShot(t,n);if(!i||!o)return;const r=i.shots.indexOf(o);i.shots=i.shots.filter(a=>a.id!==o.id),this._selectedShotId=((s=i.shots[0])==null?void 0:s.id)||null,this._saveProject(),this._shotOutcome("shot-deleted",i,o,r)}loadShot(t,n,i){return this._destroyed?Promise.resolve({started:!1,reason:"destroyed"}):this._trackWork(this._loadShot(t,n,i))}async _loadShot(t,n,{flyDuration:i=2.2}={}){var c;if(this._running)return;const{scene:o,shot:r}=this._getShot(t,n);if(!o||!r||!this._claimCameraOwnership())return;(c=this._loadAbort)==null||c.abort();const s=new AbortController;this._loadAbort=s;const a=this._loadToken(++this._loadGeneration,s.signal);this._selectedSceneId=o.id,this._selectedShotId=r.id,this._renderSceneSelect(),this._renderShotList(),await this.styleManager.applyVisualState(r.visual,{isCurrent:()=>!a.cancelled}),!a.cancelled&&(await this._applyLayerStates(r.layers||{},a),!a.cancelled&&(await this._flyCamera(r.camera,i,a),!a.cancelled&&(this._loadAbort===s&&(this._loadAbort=null),this._shotOutcome("shot-loaded",o,r),this._updateRuntime(""))))}_loadToken(t,n=void 0){const i=this;return{signal:n,get cancelled(){return i._loadGeneration!==t}}}_claimCameraOwnership(){var n;return typeof((n=this.styleManager)==null?void 0:n.runImmediateNavigation)!="function"?!0:this.styleManager.runImmediateNavigation("scene",()=>!0)===!1?(this._updateStatus("Camera unavailable — exit cockpit first"),!1):!0}_buildPlaybackQueue(t,{single:n=!1}={}){if(!this._project.scenes.length)return[];const i=Math.max(0,this._project.scenes.findIndex(s=>s.id===t)),o=n?this._project.scenes.slice(i,i+1):[...this._project.scenes.slice(i),...this._project.scenes.slice(0,i)],r=[];for(const s of o)for(const a of s.shots)r.push({scene:s,shot:a});return r}listScenes(){return this._project.scenes.map(t=>({id:t.id,title:t.title,shots:t.shots.length}))}findSceneByQuery(t){const n=String(t??"").trim().toLowerCase();if(!n)return null;const i=this._project.scenes.find(o=>o.id===t)||this._project.scenes.find(o=>o.title.toLowerCase()===n)||this._project.scenes.find(o=>o.title.toLowerCase().includes(n));return i?{id:i.id,title:i.title,shots:i.shots.length}:null}getPlaybackStatus(){return{running:this._running,selectedSceneId:this._selectedSceneId,selectedShotId:this._selectedShotId,elapsedMs:this._activeRun?Math.max(0,Date.now()-Date.parse(this._activeRun.startedAt)):null,estimatedDurationMs:this._activeRun?Math.round(this._activeRun.estimatedDurationSec*1e3):null,sceneCount:this._project.scenes.length}}get running(){return this._running}startScene(t,n){return this._destroyed?Promise.resolve({started:!1,reason:"destroyed"}):this._trackWork(this._startScene(t,n))}async _startScene(t,{single:n=!1}={}){var s,a;if(this._running)return{started:!1,reason:"already-running"};const i=this._buildPlaybackQueue(t||this._selectedSceneId||((s=this._project.scenes[0])==null?void 0:s.id),{single:n});if(!i.length)return this._updateStatus("No shots to run"),{started:!1,reason:"no-shots"};if(!this._claimCameraOwnership())return{started:!1,reason:"camera-unavailable"};(a=this._loadAbort)==null||a.abort(),this._loadAbort=null,this._loadGeneration++,this._running=!0,this._setPlaybackActive(!0),this._setButtons(!0),this._setProgress(0),this._runAbort=new AbortController,this._runToken={cancelled:!1,signal:this._runAbort.signal};const o=this._runToken;this.styleManager.setRecordingMode(!0,{hidePanels:!0,hudMode:"full",safeFrame:"16:9"});const r=i.reduce((c,l)=>c+(l.shot.durationSec||0)+(l.shot.holdSec||0),0);this._activeRun={recipeId:`project-${Kr}`,title:"Editable Scene Run",startedAt:new Date().toISOString(),estimatedDurationSec:r,scenesRun:i.length,events:[]},this._startProgressTicker(r||1),this._logEvent("scene_run_start",{count:i.length}),this._setPlaybackKeyboardEnabled(!0);try{for(let c=0;c!o.cancelled}),o.cancelled||(await this._applyLayerStates(u.layers||{},o),o.cancelled)||(await this._flyCamera(u.camera,u.durationSec||Xs,o),o.cancelled)||(await this._sleep((u.holdSec||0)*1e3,o),o.cancelled))break;this._logEvent("shot_end",{sceneId:l.id,shotId:u.id,index:c})}o.cancelled||(this._setProgress(1),this._updateStatus("Scene run complete"),this._logEvent("scene_run_complete",{}))}catch(c){this._updateStatus(`Error: ${c.message||"run failed"}`),this._logEvent("scene_run_error",{message:c.message||"unknown error"})}finally{this._finishRun()}}async runNextScene(){var i;if(this._destroyed||this._running)return;const t=this._buildPlaybackQueue(this._selectedSceneId||((i=this._project.scenes[0])==null?void 0:i.id));if(!t.length)return;let n=t[0];if(this._selectedShotId){const o=t.findIndex(r=>r.shot.id===this._selectedShotId);o>=0&&(n=t[(o+1)%t.length])}await this.loadShot(n.scene.id,n.shot.id)}stopScene(t="Stopped"){var n;!this._running||!this._runToken||(this._runToken.cancelled=!0,(n=this._runAbort)==null||n.abort(),this.viewer.camera.cancelFlight(),this._updateStatus(t),this._logEvent("scene_stopped",{reason:t}))}exportProject(){const n=`scene-presets-${new Date().toISOString().replace(/[:.]/g,"-")}.json`,i=JSON.stringify(this._project,null,2),o=new Blob([i],{type:"application/json"}),r=URL.createObjectURL(o),s=document.createElement("a");s.href=r,s.download=n,document.body.appendChild(s),s.click(),s.remove(),URL.revokeObjectURL(r),this._presentation.status="Project exported",this._publish({type:"project-exported",project:this._project})}async importProjectFile(t){var n,i,o;try{const r=await t.text();if(this._destroyed)return;const s=JSON.parse(r);this._project=gC(s),this._selectedSceneId=((n=this._project.scenes[0])==null?void 0:n.id)||null,this._selectedShotId=((o=(i=this._project.scenes[0])==null?void 0:i.shots[0])==null?void 0:o.id)||null,this._saveProject(),this._publish({type:"project-imported",project:this._project}),this._updateStatus(`Imported ${t.name}`)}catch{this._updateStatus("Import failed (invalid JSON)")}}downloadLastRunMetadata(){if(!this._lastRunJson)return;const n=`scene-run-${new Date().toISOString().replace(/[:.]/g,"-")}.json`,i=new Blob([this._lastRunJson],{type:"application/json"}),o=URL.createObjectURL(i),r=document.createElement("a");r.href=o,r.download=n,document.body.appendChild(r),r.click(),r.remove(),URL.revokeObjectURL(o)}async _applyLayerStates(t,n=null){const i=[],o=[],r=()=>({applied:i,refused:o,cancelled:!0});if(n!=null&&n.cancelled||(await this._exitIsolatingContextMode(),n!=null&&n.cancelled))return r();const s=n==null?void 0:n.signal,a=new Set(this.dataManager.getAll().map(c=>c.id));for(const{id:c,enabled:l,params:u}of L9(t,a)){const h=await this.dataManager.setEnabled(c,l,s?{signal:s}:void 0);if(n!=null&&n.cancelled)return r();if(h===!1){o.push(c),console.warn(`[Scenes] Layer refused: ${c} → ${l?"on":"off"}`);continue}i.push(c),u&&this.dataManager.setLayerParams(c,u)}return o.length&&(this._updateStatus(`Layers refused: ${o.join(", ")}`),this._logEvent("shot_layers_refused",{layerIds:[...o]})),{applied:i,refused:o,cancelled:!1}}async _exitIsolatingContextMode(){var o,r;if(typeof((o=this.styleManager)==null?void 0:o.getContextModeState)!="function"||typeof((r=this.styleManager)==null?void 0:r.setContextMode)!="function")return!1;const t=this.styleManager.getContextModeState()||{},n=t.entering||t.mode||null;if(!R9(n))return!1;const i=await this.styleManager.setContextMode("off");return i&&i.ok===!1?(console.warn(`[Scenes] Could not exit ${n}:`,i.error||"unknown reason"),this._updateStatus(`Could not exit ${n} — scene layers may be refused`),this._logEvent("context_mode_exit_failed",{mode:n,error:i.error||null}),!1):(this._logEvent("context_mode_exited",{mode:n}),!0)}async _flyCamera(t,n,i){var s,a;if(!t||i.cancelled)return;(a=(s=this.styleManager)==null?void 0:s.clearSearchedLocation)==null||a.call(s);const o=Math.max(.2,Number(n)||Xs),r=Cesium.Cartesian3.fromDegrees(t.lon,t.lat,t.alt);await new Promise(c=>{let l=!1,u;const h=()=>{l||(l=!0,clearTimeout(u),c())};this.viewer.camera.flyTo({destination:r,orientation:{heading:Cesium.Math.toRadians(t.heading||0),pitch:Cesium.Math.toRadians(t.pitch||-35),roll:Cesium.Math.toRadians(t.roll||0)},duration:o,easingFunction:Cesium.EasingFunction.CUBIC_IN_OUT,complete:h,cancel:h}),l||(u=setTimeout(h,(o+.6)*1e3))})}async _sleep(t,n){if(t<=0||n.cancelled)return;const i=Date.now()+t;for(;Date.now()setTimeout(o,70))}}_startProgressTicker(t){clearInterval(this._progressTimer);const n=Date.now(),i=Math.max(1e3,t*1e3);this._progressTimer=setInterval(()=>{if(!this._running)return;const o=Date.now()-n;this._setProgress(o/i)},100)}_finishRun(){var t,n;clearInterval(this._progressTimer),this._progressTimer=null,this._setPlaybackKeyboardEnabled(!1),(t=this._runAbort)==null||t.abort(),this._runAbort=null,this.styleManager.setRecordingMode(!1),this._setPlaybackActive(!1),this._updateRuntime(""),this._running=!1,this._activeRun&&(this._activeRun.endedAt=new Date().toISOString(),this._activeRun.wasCancelled=((n=this._runToken)==null?void 0:n.cancelled)||!1,this._lastRun=this._activeRun,this._lastRunJson=JSON.stringify(this._activeRun,null,2),this._activeRun=null),this._runToken=null,this._setButtons(!1)}_setButtons(t){this._publish({type:"buttons-changed",running:t})}_setPlaybackActive(t){this._presentation.playbackActive=t,this._publish({type:"playback-presentation"})}_setPlaybackKeyboardEnabled(t){this._presentation.keyboardEnabled=t,this._publish({type:"playback-keyboard"})}_setProgress(t){this._presentation.progress=t,this._publish({type:"progress-changed"})}_updateStatus(t){this._presentation.status=t,this._publish({type:"status-changed"})}_updateRuntime(t){this._presentation.runtime=t,this._publish({type:"runtime-changed"})}_logEvent(t,n){this._activeRun&&(this._publish({type:"run-event",event:t,detail:n||null}),this._activeRun.events.push({t:new Date().toISOString(),type:t,payload:n||null}))}}const N9=Object.freeze(["area","line","pin"]),UT=Object.freeze({area:3,line:2,pin:1}),Bc=512,D9=.5,O9=1,B9=1;function pf(e){const t=String(e||"").toLowerCase();return t==="line"||t==="path"||t==="route"?"line":t==="pin"||t==="point"||t==="marker"?"pin":"area"}function hs(e="area"){return{shape:pf(e),vertices:[]}}function zT(e,t){const i=a=>a*Math.PI/180,o=i(t.lat-e.lat),r=i(t.lon-e.lon),s=Math.sin(o/2)**2+Math.cos(i(e.lat))*Math.cos(i(t.lat))*Math.sin(r/2)**2;return 2*6371e3*Math.asin(Math.sqrt(Math.min(1,s)))}function _C(e,t,{minSeparationM:n=D9}={}){if(!e||!jT(t))return{added:!1,reason:"invalid"};const i={lon:t.lon,lat:t.lat,height:Number.isFinite(t.height)?t.height:0};if(e.shape==="pin")return e.vertices=[i],{added:!0};if(e.vertices.length>=Bc)return{added:!1,reason:"full"};const o=e.vertices[e.vertices.length-1];return o&&zT(o,i)!jT(t))?"invalid":e.vertices.length<(UT[e.shape]||1)?"too-few":e.shape==="line"&&qT(e.vertices){let i=n.lon;for(;i-t>180;)i-=360;for(;i-t<-180;)i+=360;return{...n,lon:i}})}function $9(e){if(!Number.isFinite(e)||e>=-180&&e<180)return e;const t=((e+180)%360+360)%360-180;return Object.is(t,-0)?0:t}function KT(e){if(!e||e.length<3)return 0;const t=WT(e),n=t.reduce((s,a)=>s+a.lat,0)/t.length,i=111320*Math.cos(n*Math.PI/180),o=111320;let r=0;for(let s=0;sn+i.lon,0)/t.length),lat:t.reduce((n,i)=>n+i.lat,0)/t.length}}function U9(e){if(!e)return"";if(e.shape==="line"){const t=qT(e.vertices);return t>=1e3?`${(t/1e3).toFixed(t>=1e4?0:1)} km`:`${Math.round(t)} m`}if(e.shape==="area"){const t=KT(e.vertices);return t>=1e6?`${(t/1e6).toFixed(2)} km²`:t>=1e4?`${(t/1e4).toFixed(1)} ha`:`${Math.round(t)} m²`}return""}function z9(e,{label:t="",color:n="primary"}={}){if(!H9(e))return null;const i=String(t||"").trim(),o=e.vertices.map(a=>[a.lon,a.lat]);if(e.shape==="area")return{type:"area",manual:!0,ring:j9(o),label:i||null,color:n};if(e.shape==="line")return{type:"route",manual:!0,path:o,label:i||null,color:n};const[r,s]=o[0];return{type:"pin",manual:!0,latitude:s,longitude:r,label:i||null,color:n}}function j9(e){if(!Array.isArray(e)||e.length<3)return e;const[t,n]=e[0],[i,o]=e[e.length-1];return t===i&&n===o?e:[...e,[t,n]]}function el(e){if(!e)return"Pick a shape, then click the map.";const t=e.vertices.length;if(e.shape==="pin")return t?"Enter to place the pin, Esc to cancel.":"Click where the pin goes.";const n=UT[e.shape]-t;if(n>0)return`Click ${n} more point${n===1?"":"s"}.`;if(lp(e)==="degenerate")return e.shape==="area"?"Those points are in a line — move one off it to enclose an area.":"That line has no length — click somewhere further away.";const i=t>=Bc?` · ${Bc}-point limit reached`:"";return`${U9(e)} · double-click or Enter to finish, Backspace undoes, Esc cancels.${i}`}typeof window<"u"&&!window.__CESIUM__&&(window.__CESIUM__=Cesium);let q9=0;const W9=new Set(["primary","amber","cyan","green","red"]),K9=new Set(["building","compound","district","street","point_feature"]),Y9=22e3,YT=1200,X9=120,XT=[8e3,25e3],Q9=2;async function Z9(e,{delaysMs:t=XT,isStale:n=()=>!1,waitFn:i=no}={}){let o=!1;for(let r=0;;r+=1){let s;try{s=await e()}catch{s=null}if(UM(s)){if(o||r>=t.length)return;const a=Number.isFinite(s.retryAfterMs)?s.retryAfterMs:0;if(await i(Math.max(a,t[r])),n())return;o=!0;continue}if(s!==void 0)return s;if(r>=t.length||(await i(t[r]),n()))return}}function J9(e){const t=String(e??"").trim().toLowerCase();return t?t.split(",")[0].trim()||t:null}function e7({placeSearch:e=No,viewer:t,renderer:n,outlineRetryDelaysMs:i=XT,resolveTarget:o=GM}){const r=new Map;let s=!1,a=null,c=0,l=0;const u=new Set,h=[];let d=0;const f=new Set;function p(x){for(const N of f)try{N(x)}catch{}}function g(){for(const x of u)try{x.abort()}catch{}u.clear()}function _(){for(;h.length;){const x=h.shift();x.anno._outlineTask===x&&(x.anno._outlineTask=null),b(x.controller)}}function m(x){x._retain=(x._retain||0)+1,u.add(x)}function b(x){x._retain=(x._retain||0)-1,x._retain<=0&&u.delete(x)}function C(){r.size>0?ii("annotations"):Vi("annotations")}function y(x){try{n.remove(x)}catch{}}function v(){if(s||a!=null)return;const x=()=>{const N=performance.now();let G=!1,W=!1;for(const V of r.values()){const H=n7(V,N);if(H!==V.alpha&&(V.alpha=H,G=!0),V.alpha<=0&&V.expiring){r.delete(V.id),n.remove(V),G=!0;continue}i7(V,N)&&(W=!0)}if(G&&(n.sync(r),C()),r.size===0||!W){cancelAnimationFrame(a),a=null;return}a=requestAnimationFrame(x)};a=requestAnimationFrame(x)}async function M(x,N={}){if(s)return{ok:!1,drawn:0,failed:0,ids:[],results:[],error:"destroyed"};const G=Array.isArray(x)?x:[x];N.clearPrevious&&A();const W=N.persist!==!1,V=new AbortController;m(V);const H=l,B=()=>H!==l||V.signal.aborted,q=[],z=[];let j=null,ne=!1;const ee=await Promise.allSettled(G.map(se=>w(se,V.signal,N.flyTo===!0)));try{for(let se=0;se=X9){ne=!0,q.push(Id(me,"annotation limit reached"));continue}r.set(Z.id,Z),C();try{n.add(Z)}catch(oe){throw y(Z),r.delete(Z.id),C(),oe}z.push(Z.id),j||(j=Z),typeof J.resolveOutline=="function"&&E(Z,J.resolveOutline,H,V),q.push(I(Z,J,Z.id))}catch(J){if(B())break;q.push(Id(me,(J==null?void 0:J.message)||"annotation failed",Array.isArray(J==null?void 0:J.failedTargets)?J.failedTargets:null))}}}finally{b(V)}if(B())return{ok:!1,drawn:0,failed:q.length,ids:[],results:q,aborted:!0};z.length&&(n.sync(r),v()),N.flyTo&&j?O(j):z.length&&F(z);const re=q.filter(se=>se.ok).length;return{ok:re>0,drawn:re,failed:q.length-re,ids:z,results:q,capped:ne}}async function w(x,N,G=!1){const W=gf(x==null?void 0:x.type);if(l7(x,W))return c7(x,W,t);if(W==="route"){const H=Array.isArray(x.points)?x.points:[];if(H.length<2)throw new Error("a route needs at least 2 waypoints");const B=[],q=[];for(const ee of H){const re=ee.target??ee.name??null,se=await o({placeSearch:e,viewer:t,target:re,latitude:ee.latitude,longitude:ee.longitude,screenX:ee.screenX,screenY:ee.screenY,footprint:!1,allowDistant:G,signal:N});se?B.push(se):q.push(re||"a waypoint")}if(q.length){const ee=new Error("could not locate one or more route waypoints");throw ee.failedTargets=q,ee}const z=d7(x.mode),j=await h7(B.map(ee=>[ee.lon,ee.lat]),z,N,e);if(j)return{path:j.geometry.map(([ee,re])=>({lon:ee,lat:re,height:0})),distanceM:j.distanceM,durationS:j.durationS,mode:z,source:B[0].source,fallback:!1};let ne=0;for(let ee=1;eeW!==l||V.signal.aborted||!r.has(N.id)}),W!==l||V.signal.aborted||!r.has(N.id))return;if(N.pendingOutline=!1,H){N.ring=H.ring,N.footprintKind=H.footprintKind||null,N.buildingHeight=H.buildingHeight||null,N.synthesized=!!H.synthesized,Number.isFinite(H.lat)&&Number.isFinite(H.lon)&&(N.anchor={lon:H.lon,lat:H.lat,height:Number.isFinite(H.height)?H.height:N.anchor.height}),n.update(N);for(const B of r.values())B.id===N.id||B.type!=="area"||B.pendingOutline||!B.anchor||Math.abs(B.anchor.lon-N.anchor.lon)>=5e-4||Math.abs(B.anchor.lat-N.anchor.lat)>=5e-4||!!B.synthesized==!!N.synthesized&&(B.footprintKind||null)===(N.footprintKind||null)&&bC(B.ring,N.ring)&&(r.delete(B.id),n.remove(B))}n.sync(r),p({id:N.id,label:N.label||null,target:N.targetKey||null,status:H?"resolved":"failed",...H&&N.synthesized?{approximate:!0}:{}})}finally{N._outlineTask===x&&(N._outlineTask=null),b(V),d-=1,k()}}function I(x,N,G){return{ok:!0,id:G,type:x.type,label:x.label,latitude:CC(x.anchor.lat),longitude:CC(x.anchor.lon),resolvedVia:N.source,outline:!!x.ring,...x.pendingOutline?{outlinePending:!0}:{},...x.synthesized?{approximate:!0}:{},...x.type==="route"?{fallback:!!x.fallback,mode:x.mode,distanceM:x.distanceM,durationS:x.durationS}:{}}}function R(x){if(!x.anchor)return null;const N=(V,H)=>V&&H&&Math.abs(V.lon-H.lon)<5e-4&&Math.abs(V.lat-H.lat)<5e-4,G=bC,W=(V,H)=>{const B=V?V.length:0,q=H?H.length:0;if(B!==q)return!1;for(let z=0;z({lon:ee.lon,lat:ee.lat,height:ee.height}));return{...z,label:f7(z.label,N.distanceM,N.durationS,N.mode,N.fallback),anchor:ne[0],to:null,path:ne,ring:null,mode:N.mode||null,distanceM:N.distanceM??null,durationS:N.durationS??null,fallback:!!N.fallback}}return W==="arrow"?{...z,label:m7(z.label,N.distanceM),anchor:{lon:N.from.lon,lat:N.from.lat,height:N.from.height},to:{lon:N.to.lon,lat:N.to.lat,height:N.to.height},ring:null}:{...z,anchor:{lon:N.lon,lat:N.lat,height:N.height},to:null,ring:N.ring||null,footprintKind:N.footprintKind||null,buildingHeight:N.buildingHeight||null,synthesized:!!N.synthesized,pendingOutline:typeof N.resolveOutline=="function",targetKey:J9(x==null?void 0:x.target),intentKey:(x==null?void 0:x.intent)==="around_the_thing"?"around":"thing",viewport:N.viewport||null}}function A(){if(l+=1,g(),_(),!!r.size){for(const x of r.values())n.remove(x);r.clear(),n.sync(r),C()}}function L(){const x=performance.now();for(const N of r.values())N.expiring=!0,N.ttlMs=0,N.fadeStart=x;v()}function F(x){try{if(performance.now()r.get(H)).filter(Boolean);if(!N.length)return;const G=[];for(const H of N)H.anchor&&G.push(H.anchor),H.to&&G.push(H.to);if(!G.length||G.some(H=>P(H)))return;if(console.log(`[Annotations] auto-framing ${N.length} off-screen mark(s)`),c=performance.now()+2600,N.length===1){O(N[0]);return}const W=G.map(H=>Cesium.Cartesian3.fromDegrees(H.lon,H.lat,H.height||0)),V=Cesium.BoundingSphere.fromPoints(W);t.camera.flyToBoundingSphere(V,{offset:new Cesium.HeadingPitchRange(t.camera.heading,Cesium.Math.toRadians(-35),Math.max(900,V.radius*2.6)),duration:1.6})}catch{}}function P(x){try{const N=t.camera,G=Cesium.Cartesian3.fromDegrees(x.lon,x.lat,x.height||0);return N.frustum.computeCullingVolume(N.position,N.direction,N.up).computeVisibility(new Cesium.BoundingSphere(G,1))===Cesium.Intersect.OUTSIDE?!1:new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84,N.position).isPointVisible(G)}catch{return!0}}function O(x){try{const N=x.to?{lon:(x.anchor.lon+x.to.lon)/2,lat:(x.anchor.lat+x.to.lat)/2}:x.anchor,G=x.ring?s7(x.ring):r7(x.viewport)||600;t.camera.flyToBoundingSphere(new Cesium.BoundingSphere(Cesium.Cartesian3.fromDegrees(N.lon,N.lat,x.anchor.height||0),G),{offset:new Cesium.HeadingPitchRange(t.camera.heading,Cesium.Math.toRadians(-35),G*2.4),duration:1.8})}catch{}}const D={annotate:M,clear:A,destroy(){if(!s){s=!0;try{A()}finally{a!=null&&cancelAnimationFrame(a),a=null,f.clear(),Vi("annotations"),n.destroy()}}},fadeOutAll:L,count:()=>r.size,list:()=>Array.from(r.values()),onOutlineEvent(x){return s||typeof x!="function"?()=>{}:(f.add(x),()=>f.delete(x))},async demo(){return M([{type:"highlight",target:"Palace of Fine Arts, San Francisco",label:"Palace of Fine Arts",color:"amber"},{type:"area",target:"Presidio of San Francisco",label:"The Presidio (former Army base)",color:"green",footprint:!0},{type:"pin",target:"Letterman Digital Arts Center, San Francisco",label:"ILM / Lucasfilm",color:"cyan"},{type:"arrow",target:"Palace of Fine Arts, San Francisco",toTarget:"Marina District, San Francisco",label:"next to the Marina"}],{flyTo:!0,clearPrevious:!0,persist:!0})},async tour(){return A(),$({lon:-122.4486,lat:37.796,height:520,heading:0,pitch:-26,duration:3}),s?{ok:!1}:(await no(3200),await M([{type:"highlight",target:"Palace of Fine Arts, San Francisco",label:"Palace of Fine Arts",color:"amber"}],{persist:!0}),s?{ok:!1}:(await no(2600),await M([{type:"arrow",target:"Palace of Fine Arts, San Francisco",toTarget:"Marina Green, San Francisco",label:"next to the Marina",color:"cyan"}],{persist:!0}),s?{ok:!1}:(await no(2600),$({lon:-122.4545,lat:37.788,height:1500,heading:18,pitch:-32,duration:3}),s?{ok:!1}:(await no(3200),await M([{type:"area",target:"Presidio of San Francisco",label:"The Presidio — a former Army base",color:"green",footprint:!0}],{persist:!0}),s?{ok:!1}:(await no(2800),await M([{type:"pin",target:"Letterman Digital Arts Center, San Francisco",label:"ILM / Lucasfilm",color:"red"}],{persist:!0}),s?{ok:!1}:(await no(2600),await M([{type:"route",color:"amber",label:"Crissy Field shoreline",points:[{target:"Palace of Fine Arts, San Francisco"},{target:"Crissy Field, San Francisco"},{target:"Fort Point, San Francisco"}]}],{persist:!0}),{ok:!0,steps:6}))))))}};function $({lon:x,lat:N,height:G,heading:W=0,pitch:V=-30,duration:H=2.5}){if(!s)try{t.camera.flyTo({destination:Cesium.Cartesian3.fromDegrees(x,N,G),orientation:{heading:Cesium.Math.toRadians(W),pitch:Cesium.Math.toRadians(V),roll:0},duration:H})}catch{}}return D}function no(e){return new Promise(t=>setTimeout(t,e))}function bC(e,t){const n=e?e.length:0,i=t?t.length:0;if(n!==i)return!1;for(let o=0;o=1e-5||Math.abs(e[o][1]-t[o][1])>=1e-5)return!1;return!0}function t7(e){const t=gf(e==null?void 0:e.type);return t==="route"&&Array.isArray(e==null?void 0:e.points)?e.points.map(n=>(n==null?void 0:n.target)??(n==null?void 0:n.name)).filter(Boolean):t==="arrow"?[e==null?void 0:e.target,e==null?void 0:e.toTarget].filter(Boolean):e!=null&&e.target?[e.target]:[]}function Id(e,t,n){const i=n&&n.length?n:t7(e);return{ok:!1,label:(e==null?void 0:e.label)||(e==null?void 0:e.target)||i[0]||null,target:(e==null?void 0:e.target)??null,failedTargets:i.length?i:null,error:t}}function gf(e){const t=String(e||"").toLowerCase();return t==="area"||t==="polygon"||t==="outline"||t==="compound"?"area":t==="route"||t==="path"||t==="line"?"route":t==="arrow"||t==="vector"||t==="connector"?"arrow":t==="label"||t==="callout"||t==="text"?"label":t==="pin"||t==="marker"||t==="point"?"pin":"highlight"}function n7(e,t){const n=(t-e.bornAt)/260,i=n>=1?1:Math.max(0,n);if(e.ttlMs==null&&!e.expiring)return i;const o=e.fadeStart!=null?e.fadeStart:e.createdAt+(e.ttlMs||0);if(t0?Math.max(300,Math.min(t*.7,o7)):null}catch{return null}}function s7(e){let t=1/0,n=-1/0,i=1/0,o=-1/0;for(const[s,a]of e)an&&(n=a),so&&(o=s);const r=Cesium.Cartesian3.distance(Cesium.Cartesian3.fromDegrees(i,t),Cesium.Cartesian3.fromDegrees(o,n));return Math.max(300,r*.7)}function a7(e){const t=String(e||"").trim();return t?t.slice(0,80):null}function CC(e){return Number.isFinite(e)?Math.round(e*1e5)/1e5:null}function l7(e,t){return!e||e.manual!==!0?!1:t==="route"?Array.isArray(e.path)&&e.path.length>=2:t==="area"?Array.isArray(e.ring)&&e.ring.length>=3:Number.isFinite(Number(e.latitude))&&Number.isFinite(Number(e.longitude))}function yC(e){return(Array.isArray(e)?e:[]).map(t=>Array.isArray(t)?[Number(t[0]),Number(t[1])]:[Number((t==null?void 0:t.lon)??(t==null?void 0:t.longitude)),Number((t==null?void 0:t.lat)??(t==null?void 0:t.latitude))]).filter(([t,n])=>Number.isFinite(t)&&Number.isFinite(n)&&Math.abs(n)<=90&&Math.abs(t)<=180)}function c7(e,t,n){if(t==="route"){const r=yC(e.path).map(([a,c])=>({lon:a,lat:c,height:0}));if(r.length<2)throw new Error("a drawn line needs at least 2 points");let s=0;for(let a=1;a({lon:u,lat:h}))),c=a.lon,l=a.lat;return{lon:c,lat:l,height:_h(n,c,l),ring:r,footprintKind:"area",buildingHeight:null,synthesized:!1,source:"manual"}}const i=Number(e.longitude),o=Number(e.latitude);return{lon:i,lat:o,height:_h(n,i,o),ring:null,source:"manual"}}function u7(e){if(e.length<2)return e;const[t,n]=e[0],[i,o]=e[e.length-1];return t===i&&n===o?e.slice(0,-1):e}function d7(e){const t=String(e||"").toLowerCase();return t==="car"||t==="drive"||t==="driving"?"car":t==="bike"||t==="cycle"||t==="cycling"||t==="bicycle"?"bike":"foot"}async function h7(e,t,n,i){var o;try{return await((o=i.route)==null?void 0:o.call(i,e,t,{signal:n}))||null}catch{return null}}function _f(e,t){const i=l=>l*Math.PI/180,o=i(t.lat-e.lat),r=i(t.lon-e.lon),s=i(e.lat),a=i(t.lat),c=Math.sin(o/2)**2+Math.cos(s)*Math.cos(a)*Math.sin(r/2)**2;return 2*6371e3*Math.asin(Math.min(1,Math.sqrt(c)))}function QT(e){return Number.isFinite(e)?e>=1e3?`${(e/1e3).toFixed(e>=1e4?0:1)} km`:`${Math.round(e/10)*10} m`:null}function f7(e,t,n,i,o){const r=QT(t);if(!r)return e;const s=Number.isFinite(n)?Math.max(1,Math.round(n/60)):null,a=i==="car"?"drive":i==="bike"?"ride":"walk";if(i==="manual")return e?`${e} — ${r}`:r;let c;return o?c=`${r} · direct line (no route)`:c=s!=null?`${r} · ${s} min ${a}`:r,e?`${e} — ${c}`:c}function m7(e,t){const n=QT(t);return n?e?`${e} — ${n}`:n:e}const ni="http://www.w3.org/2000/svg",vC={primary:"#8be9ff",amber:"#ffb547",cyan:"#39d0ff",green:"#5dff9f",red:"#ff6b6b"},Rd=800,MC=6e3,wC=.32,p7=34,g7=18,_7=5,EC=4;function b7(e){return e>Rd?e>=MC?wC:1-(e-Rd)/(MC-Rd)*(1-wC):1}function C7(e,{overlayPaintRect:t=Iv,activeTrackedReadoutId:n=zv}={}){M7();const{layer:i,svg:o,defs:r}=y7();document.body.appendChild(i);const s=e.scene,a=new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84,s.camera.positionWC),c=new Map,l=new Cesium.Cartesian2,u=new Cesium.Cartesian3,h=new Map,d=600,f=8e3;let p=0;function g(){if(!(h.size<=d)){for(const[F,P]of h){if(h.size<=d)break;P.gen!==p&&h.delete(F)}for(;h.size>f;){const F=h.keys().next().value;if(F===void 0)break;h.delete(F)}}}const _=()=>R();s.postRender.addEventListener(_);function m(F){return vC[F.color]||vC.primary}function b(F,P){const O=`${F.toFixed(5)},${P.toFixed(5)}`,D=h.get(O);if(D&&D.settled)return D.gen=p,h.delete(O),h.set(O,D),D.h;try{if(s.clampToHeightSupported&&typeof s.clampToHeight=="function"){const x=s.clampToHeight(Cesium.Cartesian3.fromDegrees(F,P,0));if(x){const N=Cesium.Cartographic.fromCartesian(x).height;if(Number.isFinite(N)&&N>-430&&N<9e3)return h.set(O,{h:N,settled:!0,gen:p}),g(),N}}}catch{}const $=D?D.h:0;return h.set(O,{h:$,settled:!1,gen:p}),g(),$}function C(F){const P=m(F),O=Un("g",{class:"gev-anno",opacity:"0"}),D={};F.type==="area"&&F.ring&&F.ring.length>=3?(D.poly=Un("polygon",{class:F.synthesized?"gev-anno-area":"gev-anno-area gev-draw",fill:P,stroke:P,"fill-opacity":F.synthesized?"0.08":"0.14","stroke-width":"2.5",...F.synthesized?{"stroke-dasharray":"9 7"}:{},filter:"url(#gev-sketch)"}),O.appendChild(D.poly),D.label=tl(F.label,P),D.label&&O.appendChild(D.label.node)):F.type==="arrow"&&F.to?(D.path=Un("path",{class:"gev-anno-arrow gev-draw",fill:"none",stroke:P,"stroke-width":"3","marker-end":`url(#gev-arrow-${F.color||"primary"})`,filter:"url(#gev-sketch)"}),TC(r,F.color||"primary",P),O.appendChild(D.path),D.label=tl(F.label,P),D.label&&O.appendChild(D.label.node)):F.type==="route"&&Array.isArray(F.path)&&F.path.length>=2?(D.poly=Un("polyline",{class:"gev-anno-arrow gev-draw",fill:"none",stroke:P,"stroke-width":"3","marker-end":`url(#gev-arrow-${F.color||"primary"})`,filter:"url(#gev-sketch)"}),TC(r,F.color||"primary",P),O.appendChild(D.poly),D.dots=F.path.map(()=>{const $=Un("circle",{class:"gev-anno-dot",fill:P,stroke:"#06121c","stroke-width":"2",r:"4"});return O.appendChild($),$}),D.label=tl(F.label,P),D.label&&O.appendChild(D.label.node)):(F.type!=="label"&&(D.ringOuter=Un("circle",{class:"gev-anno-ring gev-pulse",fill:"none",stroke:P,"stroke-width":"2",r:"34"}),D.ringInner=Un("circle",{class:"gev-anno-ring",fill:P,"fill-opacity":"0.12",stroke:P,"stroke-width":"2.5",r:"18",filter:"url(#gev-sketch)"}),O.appendChild(D.ringOuter),O.appendChild(D.ringInner)),D.dot=Un("circle",{class:"gev-anno-dot",fill:P,stroke:"#06121c","stroke-width":"2",r:F.type==="label"?"4":"5"}),O.appendChild(D.dot),D.leader=Un("line",{class:"gev-anno-leader",stroke:P,"stroke-width":"1.5","stroke-opacity":"0.7"}),O.appendChild(D.leader),D.label=tl(F.label,P),D.label&&O.appendChild(D.label.node)),c.set(F.id,{anno:F,group:O,parts:D});try{o.appendChild(O),requestAnimationFrame(()=>O.classList.add("gev-in"));for(const $ of O.querySelectorAll(".gev-draw"))$.addEventListener("transitionend",x=>{x.propertyName==="stroke-dashoffset"&&($.style.strokeDasharray="none")},{once:!0});R()}catch($){c.delete(F.id);try{O.remove()}catch{}throw c.size===0&&h.clear(),$}}function y(F,{empty:P=!1}={}){var D,$;const O=c.get(F.id);if(!O){P||C(F);return}if(O.anno=F,P){for(const x of Array.from(O.group.children))x.remove();O.parts={},O.hidden=!0,R();return}if(O.hidden=!1,F.type==="label"&&O.parts.dot){(D=O.parts.ringOuter)==null||D.remove(),($=O.parts.ringInner)==null||$.remove(),delete O.parts.ringOuter,delete O.parts.ringInner,O.parts.dot.setAttribute("r",String(EC)),R();return}}function v(F,P){const O=Cesium.Cartesian3.fromDegrees(F,P,b(F,P));if(Cesium.Cartesian3.subtract(O,s.camera.positionWC,u),Cesium.Cartesian3.dot(u,s.camera.directionWC)<=0||!a.isPointVisible(O))return null;const D=Cesium.SceneTransforms.worldToWindowCoordinates(s,O,l);if(!D||!Number.isFinite(D.x)||!Number.isFinite(D.y))return null;const $=s.canvas.clientWidth||s.canvas.width,x=s.canvas.clientHeight||s.canvas.height;return D.x<-$||D.x>2*$||D.y<-x||D.y>2*x?null:{x:D.x,y:D.y}}const M=8,w=.22,E=18,k=new Cesium.Cartesian2;function T(F,P){if(P<=F.near)return F.nearValue;if(P>=F.far)return F.farValue;const O=(P-F.near)/(F.far-F.near);return F.nearValue+O*(F.farValue-F.nearValue)}function I(){var q,z,j,ne,ee,re;const F=n(),P=F?t(Fo,F):null;let O=P==null?void 0:P.x,D=P?P.x+P.w:void 0,$=P==null?void 0:P.y,x=P?P.y+P.h:void 0;const N=e.trackedEntity,G=Cesium.JulianDate.now(),W=typeof(N==null?void 0:N.gevDisplayPosition)=="function"?N.gevDisplayPosition():null,V=W?Cesium.SceneTransforms.worldToWindowCoordinates(s,W,k):null,H=N==null?void 0:N.billboard;if(H&&V&&Number.isFinite(V.x)&&Number.isFinite(V.y)){const se=((z=(q=H.width)==null?void 0:q.getValue)==null?void 0:z.call(q,G))??28,me=((ne=(j=H.height)==null?void 0:j.getValue)==null?void 0:ne.call(j,G))??28;let be=1;const J=(re=(ee=H.scaleByDistance)==null?void 0:ee.getValue)==null?void 0:re.call(ee,G);J&&(be=T(J,Cesium.Cartesian3.distance(s.camera.positionWC,W)));const Z=se*be/2,ae=me*be/2,oe=V.x-Z,le=V.x+Z,Y=V.y-ae,K=V.y+ae;O=Number.isFinite(O)?Math.min(O,oe):oe,D=Number.isFinite(D)?Math.max(D,le):le,$=Number.isFinite($)?Math.min($,Y):Y,x=Number.isFinite(x)?Math.max(x,K):K}if(![O,D,$,x].every(Number.isFinite))return null;const B=M;return{left:O-B,right:D+B,top:$-B,bottom:x+B}}function R(){var x;if(!c.size)return;p+=1;const F=I();a.cameraPosition=s.camera.positionWC;const P=s.canvas.clientHeight||s.canvas.height,O=s.canvas.clientWidth||s.canvas.width;o.setAttribute("viewBox",`0 0 ${O} ${P}`);const D=b7(((x=e.camera.positionCartographic)==null?void 0:x.height)??1e3);for(const N of c.values()){const{anno:G,group:W,parts:V}=N;if(N.hidden){W.style.display="none";continue}if(W.setAttribute("opacity",String(G.alpha??1)),G.type==="area"&&V.poly){const H=[];let B=0,q=0,z=0;for(const[j,ne]of G.ring){const ee=v(j,ne);ee&&(H.push(`${ee.x.toFixed(1)},${ee.y.toFixed(1)}`),B+=ee.x,q+=ee.y,z++)}H.length>=3?(V.poly.setAttribute("points",H.join(" ")),W.style.display="",V.label&&nl(V.label,B/z,q/z-6,!0)):W.style.display="none"}else if(G.type==="arrow"&&V.path){const H=v(G.anchor.lon,G.anchor.lat),B=v(G.to.lon,G.to.lat);if(H&&B){const q=(H.x+B.x)/2,z=(H.y+B.y)/2,j=B.x-H.x,ne=B.y-H.y,ee=Math.hypot(j,ne)||1,re=Math.min(60,ee*.18),se=q-ne/ee*re,me=z+j/ee*re;V.path.setAttribute("d",`M ${H.x.toFixed(1)} ${H.y.toFixed(1)} Q ${se.toFixed(1)} ${me.toFixed(1)} ${B.x.toFixed(1)} ${B.y.toFixed(1)}`),W.style.display="",V.label&&nl(V.label,q+(se-q)*.5,z+(me-z)*.5-8,!0)}else W.style.display="none"}else if(G.type==="route"&&V.poly){const H=G.path.map(q=>v(q.lon,q.lat)),B=[];for(const q of H)q&&B.push(`${q.x.toFixed(1)},${q.y.toFixed(1)}`);if(B.length>=2){V.poly.setAttribute("points",B.join(" ")),V.dots.forEach((z,j)=>{const ne=H[j];ne?(z.setAttribute("cx",ne.x.toFixed(1)),z.setAttribute("cy",ne.y.toFixed(1)),z.style.display=""):z.style.display="none"}),W.style.display="";const q=H.filter(Boolean)[Math.floor(H.filter(Boolean).length/2)];V.label&&q&&nl(V.label,q.x,q.y-12,!0)}else W.style.display="none"}else{const H=v(G.anchor.lon,G.anchor.lat);if(H){W.style.display="";const B=G.type==="label"?EC:_7;if(V.dot&&(V.dot.setAttribute("cx",H.x.toFixed(1)),V.dot.setAttribute("cy",H.y.toFixed(1)),V.dot.setAttribute("r",(B*D).toFixed(1))),V.ringOuter&&(V.ringOuter.setAttribute("cx",H.x.toFixed(1)),V.ringOuter.setAttribute("cy",H.y.toFixed(1)),V.ringOuter.setAttribute("r",(p7*D).toFixed(1))),V.ringInner&&(V.ringInner.setAttribute("cx",H.x.toFixed(1)),V.ringInner.setAttribute("cy",H.y.toFixed(1)),V.ringInner.setAttribute("r",(g7*D).toFixed(1))),V.label){const q=H.x+18*D,z=H.y-34*D;nl(V.label,q,z,!1),V.leader&&(V.leader.setAttribute("x1",H.x.toFixed(1)),V.leader.setAttribute("y1",H.y.toFixed(1)),V.leader.setAttribute("x2",q.toFixed(1)),V.leader.setAttribute("y2",(z+V.label.height).toFixed(1)),V.label._leader=V.leader)}}else W.style.display="none"}}const $=[];for(const N of c.values()){const G=N.parts.label;G&&G.sized&&N.group.style.display!=="none"&&Number.isFinite(G._x)&&$.push(G)}$.length>1&&v7($);for(const N of c.values()){const{anno:G,group:W}=N;if(W.style.display==="none")continue;const V=N._trackedFade??1;let H=!1;if(F){let z=null;try{z=W.getBBox()}catch{z=null}if(z&&(z.width!==0||z.height!==0)){const j=V<.5?E:0;H=z.x<=F.right+j&&z.x+z.width>=F.left-j&&z.y<=F.bottom+j&&z.y+z.height>=F.top-j}}const B=H?0:1,q=V+(B-V)*w;N._trackedFade=Math.abs(q-B)<.02?B:q,N._trackedFade!==1&&W.setAttribute("opacity",String((G.alpha??1)*N._trackedFade))}}function S(F){const P=c.get(F.id);if(!P)return;P.group.classList.remove("gev-in"),P.group.classList.add("gev-out");const O=P.group;window.setTimeout(()=>{try{O.remove()}catch{}},360),c.delete(F.id),c.size===0&&h.clear()}function A(){R()}function L(){try{s.postRender.removeEventListener(_)}catch{}try{i.remove()}catch{}c.clear(),h.clear()}return{add:C,update:y,remove:S,sync:A,destroy:L}}function y7(){const e=document.createElement("div");e.className="gev-screen-whiteboard";const t=document.createElementNS(ni,"svg");t.setAttribute("class","gev-screen-whiteboard-svg"),t.setAttribute("preserveAspectRatio","none");const n=document.createElementNS(ni,"defs");return n.innerHTML=` + + + + `,t.appendChild(n),e.appendChild(t),{layer:e,svg:t,defs:n}}function tl(e,t){if(!e)return null;const n=document.createElementNS(ni,"g");n.setAttribute("class","gev-anno-callout");const i=document.createElementNS(ni,"rect");i.setAttribute("rx","5"),i.setAttribute("class","gev-anno-card");const o=document.createElementNS(ni,"text");o.setAttribute("class","gev-anno-text"),o.setAttribute("x","9"),o.setAttribute("y","16"),o.textContent=e;const r=document.createElementNS(ni,"rect");r.setAttribute("class","gev-anno-accent"),r.setAttribute("width","3"),r.setAttribute("rx","1.5"),r.setAttribute("fill",t),n.appendChild(i),n.appendChild(r),n.appendChild(o);const s={node:n,rect:i,text:o,accent:r,width:0,height:26,sized:!1};return requestAnimationFrame(()=>ZT(s)),s}function ZT(e){try{const t=e.text.getBBox(),n=Math.max(24,t.width+18),i=Math.max(22,t.height+10);e.rect.setAttribute("width",String(n)),e.rect.setAttribute("height",String(i)),e.accent.setAttribute("height",String(i-8)),e.accent.setAttribute("x","0"),e.accent.setAttribute("y","4"),e.width=n,e.height=i,e.sized=!0}catch{}}function nl(e,t,n,i){e.sized||ZT(e);const o=i?t-e.width/2:t;e._x=o,e._y=n,e.node.setAttribute("transform",`translate(${o.toFixed(1)}, ${n.toFixed(1)})`)}function v7(e){e.sort((t,n)=>t._y-n._y);for(let t=0;to._x,s=n._yo._y;r&&s&&(n._y=o._y+o.height+5,n.node.setAttribute("transform",`translate(${n._x.toFixed(1)}, ${n._y.toFixed(1)})`),n._leader&&(n._leader.setAttribute("x2",n._x.toFixed(1)),n._leader.setAttribute("y2",n._y.toFixed(1))))}}}function TC(e,t,n){if(e.querySelector(`#gev-arrow-${t}`))return;const i=document.createElementNS(ni,"marker");i.setAttribute("id",`gev-arrow-${t}`),i.setAttribute("viewBox","0 0 10 10"),i.setAttribute("refX","8"),i.setAttribute("refY","5"),i.setAttribute("markerWidth","7"),i.setAttribute("markerHeight","7"),i.setAttribute("orient","auto-start-reverse");const o=document.createElementNS(ni,"path");o.setAttribute("d","M 0 0 L 10 5 L 0 10 z"),o.setAttribute("fill",n),i.appendChild(o),e.appendChild(i)}function Un(e,t){const n=document.createElementNS(ni,e);for(const[i,o]of Object.entries(t))n.setAttribute(i,o);return n}function M7(){if(document.getElementById("gev-screen-whiteboard-styles"))return;const e=document.createElement("style");e.id="gev-screen-whiteboard-styles",e.textContent=` + .gev-screen-whiteboard { position: fixed; inset: 0; pointer-events: none; z-index: 90; } + .gev-screen-whiteboard-svg { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; } + /* No CSS opacity transition here on purpose: group opacity is driven per-frame in JS + (the 260ms fade-in via computeAlpha, and the tracked-entity z-order ease). A CSS + transition fought those per-frame writes and made the tracked-fade opacity oscillate + (flicker). Fade-OUT keeps its own transition via .gev-anno.gev-out below. */ + .gev-anno-ring { filter: drop-shadow(0 0 6px currentColor); } + .gev-anno-dot { filter: drop-shadow(0 0 5px rgba(255,255,255,0.6)); } + .gev-anno-area { filter: drop-shadow(0 0 5px currentColor); } + .gev-anno-arrow { filter: drop-shadow(0 0 4px currentColor); stroke-linecap: round; } + .gev-anno-leader { stroke-dasharray: 2 3; } + .gev-anno-card { fill: rgba(8,18,28,0.78); stroke: rgba(255,255,255,0.14); stroke-width: 1; } + .gev-anno-text { fill: #eaf6ff; font: 600 13px "JetBrains Mono", ui-monospace, monospace; letter-spacing: 0.02em; } + /* draw-on: outlined shapes reveal their stroke */ + .gev-draw { stroke-dasharray: 1400; stroke-dashoffset: 1400; } + .gev-anno.gev-in .gev-draw { transition: stroke-dashoffset 900ms ease-out; stroke-dashoffset: 0; } + /* opacity-only fade-in: a CSS transform here would override the SVG transform + attribute used to POSITION the callout and snap it to 0,0. */ + .gev-anno-callout { opacity: 0; } + .gev-anno.gev-in .gev-anno-callout { animation: gev-pop 320ms ease-out both; } + .gev-anno.gev-out { opacity: 0 !important; transition: opacity 320ms ease; } + .gev-pulse { animation: gev-ring-pulse 1.8s ease-in-out infinite; transform-box: fill-box; transform-origin: center; } + @keyframes gev-ring-pulse { 0%,100% { opacity: 0.9; stroke-width: 2; } 50% { opacity: 0.35; stroke-width: 3.5; } } + @keyframes gev-pop { from { opacity: 0; } to { opacity: 1; } } + `,document.head.appendChild(e)}function w7(e){const t=gw(e),n=C7(e),i=new Map;function o(l){const u={};if(i.set(l.id,u),l.type==="area"&&l.ring&&l.ring.length>=3)u.worldProxy=nr(l,{label:null}),t.add(u.worldProxy),l.label&&(u.screenProxy=nr(l,{type:"label",ring:null}),n.add(u.screenProxy));else if(l.type==="route"&&Array.isArray(l.path)&&l.path.length>=2){if(u.worldProxy=nr(l,{label:null}),t.add(u.worldProxy),l.label){const h=l.path[Math.floor(l.path.length/2)];u.screenProxy=nr(l,{type:"label",path:null,anchor:{lon:h.lon,lat:h.lat,height:h.height}}),n.add(u.screenProxy)}}else u.screenProxy=l,n.add(l)}function r(l){const u=i.get(l.id);if(!u){o(l);return}if(l.type!=="area"||!l.ring||l.ring.length<3)return;u.worldProxy||(u.worldProxy=nr(l,{label:null}),t.add(u.worldProxy));const h=nr(l,{type:"label",ring:null});u.screenProxy?n.update(h,{empty:!l.label}):l.label&&n.add(h),u.screenProxy=u.screenProxy||l.label?h:null}function s(l){const u=i.get(l.id);if(!u)return;let h=null;if(u.worldProxy)try{t.remove(u.worldProxy),u.worldProxy=null}catch(d){h=d}if(u.screenProxy)try{n.remove(u.screenProxy),u.screenProxy=null}catch(d){h=h||d}if(!u.worldProxy&&!u.screenProxy&&i.delete(l.id),h)throw h}function a(l){t.sync(l),n.sync(l)}function c(){t.destroy(),n.destroy(),i.clear()}return{add:o,update:r,remove:s,sync:a,destroy:c}}function nr(e,t){return Object.assign(Object.create(e),t)}function E7({viewer:e,tileset:t=null,placeSearch:n,resolver:i}){if(t)try{t.enableCollision=!0}catch{}const o=w7(e),r=e7({viewer:e,renderer:o,placeSearch:n,resolveTarget:i==null?void 0:i.resolveAnnotationTarget});return window.__gevAnnotations=r,r}const T7="draw",JT="gev-draw-preview",k7=["primary","amber","cyan","green","red"],il={primary:"#8be9ff",amber:"#ffb547",cyan:"#39d0ff",green:"#5dff9f",red:"#ff6b6b"};function A7({viewer:e,annotations:t}){const n=document.getElementById("draw-toggle"),i=document.getElementById("draw-mode-row"),o=document.getElementById("draw-label-row"),r=document.getElementById("draw-label-input"),s=document.getElementById("draw-color-select"),a=document.getElementById("draw-clear"),c=document.getElementById("draw-hint");if(!e||!t||!n)return null;let l=!1,u=!1,h=null,d="area",f="primary",p=null,g=null,_=null,m=null,b=null,C=0;const y=[],v=[],M=(B,q,z,j)=>{B&&(B.addEventListener(q,z,j),v.push([B,q,z,j]))},w=new Cesium.CustomDataSource(JT);let E=Promise.resolve(e.dataSources.add(w)).catch(()=>null);const k=B=>{c&&(c.textContent=B)},T=()=>h.vertices.map(B=>Cesium.Cartesian3.fromDegrees(B.lon,B.lat,B.height||0)),I=w.entities.add({show:!1,polyline:{positions:new Cesium.CallbackProperty(()=>{if(!h)return[];const B=T();return b&&h.shape!=="pin"&&B.push(b),h.shape==="area"&&B.length>=3&&B.push(B[0]),B},!1),width:3,material:new Cesium.PolylineDashMaterialProperty({color:Cesium.Color.fromCssColorString(il.primary).withAlpha(.9),dashLength:16}),depthFailMaterial:new Cesium.PolylineDashMaterialProperty({color:Cesium.Color.fromCssColorString(il.primary).withAlpha(.35),dashLength:16}),clampToGround:!1}}),R=()=>{if(u)return;if(y.forEach(q=>w.entities.remove(q)),y.length=0,!h){I.show=!1,k(el(null)),e.scene.requestRender();return}const B=Cesium.Color.fromCssColorString(il[f]||il.primary);I.polyline.material=new Cesium.PolylineDashMaterialProperty({color:B.withAlpha(.9),dashLength:16}),I.show=h.shape!=="pin";for(const q of h.vertices)y.push(w.entities.add({position:Cesium.Cartesian3.fromDegrees(q.lon,q.lat,q.height||0),point:{pixelSize:8,color:B,outlineColor:Cesium.Color.BLACK.withAlpha(.6),outlineWidth:2,disableDepthTestDistance:Number.POSITIVE_INFINITY}}));k(el(h)),e.scene.requestRender()},S=B=>{const q=e.scene.canvas,z=q.clientWidth||q.width||1,j=q.clientHeight||q.height||1;return WM(e,B.x/z,B.y/j)},A=B=>{if(!h||u)return;const q=S(B.position);if(!q)return;const{added:z,reason:j}=_C(h,q);if(z){R();return}j==="full"?k(`That shape already has ${Bc} points — finish it or press Backspace.`):j==="invalid"&&k("That point is off the globe — click on the world.")},L=B=>{if(!h||h.shape==="pin"||u)return;const q=S(B.endPosition);b=q?Cesium.Cartesian3.fromDegrees(q.lon,q.lat,q.height||0):null,e.scene.requestRender()},F=async()=>{if(u||!h)return null;const B=lp(h);if(B!=="ok")return B!=="too-few"&&k(el(h)),null;const q=z9(h,{label:(r==null?void 0:r.value)||"",color:f});if(!q)return null;h=hs(d),b=null,R(),r&&(r.value="");const z=C;try{const j=await t.annotate([q],{persist:!0,flyTo:!1});return u||z!==C||(j==null?void 0:j.drawn)===0&&k("That shape could not be placed."),j}catch(j){return u||z!==C||k(`Could not place the shape: ${(j==null?void 0:j.message)||j}`),null}},P=()=>{h&&(C+=1,h=hs(d),b=null,R())},O=()=>{C+=1,b=null,h&&(h=hs(d)),t.clear(),R(),!u&&!l&&k("Board cleared.")},D=B=>{const q=B.target;return!q||q===r?!1:q.tagName==="INPUT"||q.tagName==="TEXTAREA"||q.isContentEditable},$=B=>{const q=B.target;return!q||q===r?!0:typeof q.closest=="function"&&q.closest('button, a, select, [role="button"], [role="radio"]')?!1:q===document.body||q===e.scene.canvas||q.tagName==="CANVAS"},x=B=>{var q;if(!(!l||u||D(B))){if(B.key==="Enter"){(q=h==null?void 0:h.vertices)!=null&&q.length&&$(B)&&(B.preventDefault(),F());return}if(B.key==="Escape"){B.preventDefault(),B.stopImmediatePropagation(),h!=null&&h.vertices.length?P():N(!1);return}B.key==="Backspace"&&B.target!==r&&V9(h)&&(B.preventDefault(),R())}};function N(B){return u||B===l?l:B&&(g=vy(T7),!g)?(k(`${Zs()} is using the pointer — close it first.`),l):(l=B,n.classList.toggle("active",l),n.setAttribute("aria-pressed",String(l)),i==null||i.classList.toggle("visible",l),o==null||o.classList.toggle("visible",l),document.body.classList.toggle("gev-drawing",l),l?(h=hs(d),G(),R()):(C+=1,h=null,b=null,W(),Bd(g),g=null,R()),l)}function G(){if(p)return;p=new Cesium.ScreenSpaceEventHandler(e.scene.canvas),p.setInputAction(A,Cesium.ScreenSpaceEventType.LEFT_CLICK),p.setInputAction(L,Cesium.ScreenSpaceEventType.MOUSE_MOVE),p.setInputAction(()=>{F()},Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);const B=e.screenSpaceEventHandler;m=B.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)||null,_=B.getInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)||null,B.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK),B.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK),M(document,"keydown",x,!0)}function W(){p&&(p.destroy(),p=null),m&&(e.screenSpaceEventHandler.setInputAction(m,Cesium.ScreenSpaceEventType.LEFT_CLICK),m=null),_&&(e.screenSpaceEventHandler.setInputAction(_,Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK),_=null);for(let B=v.length-1;B>=0;B-=1){const[q,z,j,ne]=v[B];j===x&&(q.removeEventListener(z,j,ne),v.splice(B,1))}}M(n,"click",()=>N(!l));const V=[...(i==null?void 0:i.querySelectorAll(".pp-mode-btn[data-shape]"))||[]];for(const B of V)M(B,"click",()=>{d=pf(B.dataset.shape);for(const q of V){const z=q===B;q.classList.toggle("active",z),q.setAttribute("aria-checked",String(z))}l&&(C+=1,h=hs(d),b=null,R())});M(s,"change",()=>{f=k7.includes(s.value)?s.value:"primary",R()}),M(a,"click",O),M(r,"keydown",B=>{var q;B.key==="Enter"&&((q=h==null?void 0:h.vertices)!=null&&q.length)&&(B.preventDefault(),F())}),k(el(null));const H={get active(){return l},get shape(){return d},get session(){return h},setActive:N,setShape(B){const q=i==null?void 0:i.querySelector(`.pp-mode-btn[data-shape="${pf(B)}"]`);q==null||q.click()},addVertex(B,q,z=0){if(!h)return!1;const j=_C(h,{lon:B,lat:q,height:z});return j.added&&R(),j.added},finish:F,cancel:P,clearAll:O,shapes:N9,diagnostics(){var B,q,z,j;return{active:l,destroyed:u,sceneHandler:!!p,domListeners:v.length,previewDataSources:I7(e),previewEntities:u?0:w.entities.values.length,pointerOwner:Zs(),stockSingleClick:!!((q=(B=e.screenSpaceEventHandler)==null?void 0:B.getInputAction)!=null&&q.call(B,Cesium.ScreenSpaceEventType.LEFT_CLICK)),stockDoubleClick:!!((j=(z=e.screenSpaceEventHandler)==null?void 0:z.getInputAction)!=null&&j.call(z,Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK))}},whenSettled(){return E},destroy(){if(u)return E;C+=1,l&&N(!1),u=!0,W(),Bd(g),g=null;for(const[B,q,z,j]of v.splice(0))B.removeEventListener(q,z,j);return y.length=0,w.entities.removeAll(),E=E.then(()=>{try{e.dataSources.remove(w,!0)}catch{}}),document.body.classList.remove("gev-drawing"),n.classList.remove("active"),n.setAttribute("aria-pressed","false"),i==null||i.classList.remove("visible"),o==null||o.classList.remove("visible"),c&&(c.textContent=""),window.__gevDrawTool===H&&delete window.__gevDrawTool,E}};return window.__gevDrawTool=H,H}function I7(e){var i;const t=e==null?void 0:e.dataSources;if(!t)return 0;let n=0;for(let o=0;o +
    AI AGENT
    +
    OFF
    +
    + + ~$0.00 +
    + + + +
    +
    VOICE STANDBY
    +
    + + + `;const i=document.getElementById("command-dock");if(i){const o=document.getElementById("location-bar"),r=document.getElementById("control-panel");i.appendChild(t),o&&i.insertBefore(o,t),r&&i.appendChild(r)}else document.body.appendChild(t);(n=t.querySelector(".gev-voice-error-dismiss"))==null||n.addEventListener("click",()=>{t.classList.add("error-dismissed")})}return{root:t,button:t.querySelector("#gev-voice-button"),buttonLabel:t.querySelector(".gev-mic-label"),status:t.querySelector("#gev-voice-status"),detail:t.querySelector("#gev-voice-detail"),helpDetail:t.querySelector(".gev-voice-help-detail"),errorDetail:t.querySelector("#gev-voice-error-detail"),tierButton:t.querySelector("#gev-voice-tier"),costValue:t.querySelector("#gev-voice-cost-value")}}function L7({createAdapter:e,runner:t,signal:n}){if(typeof e!="function"||typeof t!="function")throw new TypeError("Voice requires an adapter factory and action runner");const i=new AbortController,o=new Set,r=new Set;let s,a="idle",c=!1,l=0,u=0;function h(){l++;for(const _ of r)_.abort();r.clear()}function d(_){if(!(c||!_||typeof _.type!="string")){if(_.type==="disposed"){p(!1);return}_.type==="state"&&(a=_.state,["idle","error","connecting"].includes(a)&&h()),_.type==="interruption"&&h();for(const m of[...o])try{m(_)}catch{}}}async function f(_,m,b={}){if(c||i.signal.aborted||["idle","error"].includes(a))throw ol();const C=new AbortController,y=l;r.add(C);const v=AbortSignal.any([i.signal,C.signal,...b.signal?[b.signal]:[]]),M=()=>!v.aborted&&y===l&&(!b.isCurrent||b.isCurrent());try{if(!M()||(d({type:"action-call",name:_,arguments:m}),!M()))throw ol();const w=await t(_,m,{...b,signal:v,isCurrent:M});if(!M())throw ol();return d({type:"action-result",name:_,result:w}),w}finally{r.delete(C)}}function p(_=!0){c||(c=!0,u++,a="idle",h(),i.abort(),n==null||n.removeEventListener("abort",g),o.clear(),_&&(s==null||s.stop({removeUi:!0})))}const g=()=>p();try{s=e({emit:d,runAction:f,signal:i.signal});for(const _ of["start","stop","sendText","sendMapEvent"])if(typeof(s==null?void 0:s[_])!="function")throw new TypeError("Voice adapter must implement "+_)}catch(_){throw p(),_}return n==null||n.addEventListener("abort",g,{once:!0}),n!=null&&n.aborted&&p(),{adapter:s,signal:i.signal,get state(){return a},get disposed(){return c},isActive:()=>!c&&!["idle","error"].includes(a),subscribe(_){return c?()=>{}:(o.add(_),()=>o.delete(_))},async start(_){if(c||!["idle","error"].includes(a))return;d({type:"state",state:"connecting"});const m=++u;try{await s.start(_)}catch(b){if(!c&&m===u)try{s.stop({preserveStatus:!0})}finally{d({type:"state",state:"error",detail:b.message})}}},stop(_={}){if(_.removeUi)return p();if(!c){u++,h();try{s.stop(_)}finally{_.preserveStatus||d({type:"state",state:"idle",detail:"Voice off"})}}},sendText:_=>!c&&s.sendText(_),sendMapEvent:_=>!c&&s.sendMapEvent(_),destroy:()=>p()}}function ol(){return new DOMException("Voice action cancelled","AbortError")}function P7({runner:e,dataManager:t,annotations:n=null,createSession:i,createController:o,backend:r,signal:s,debugSink:a,createControl:c=R7}){var m,b,C,y;(b=(m=window.__gevVoiceCommands)==null?void 0:m.stop)==null||b.call(m,{removeUi:!0});const l=c({reset:!0}),u=L7({runner:e,signal:s,createAdapter:v=>{var M,w;return i({...v,runner:e,ui:l,dataManager:t,backend:r,debugSink:a,createController:o,radioLayer:((w=(M=t==null?void 0:t.layers)==null?void 0:M.get("radio"))==null?void 0:w.module)||null})}}),h=u.adapter,d=h.capabilities||{};l.tierButton&&(l.tierButton.hidden=!d.costControls),l.costValue&&(l.costValue.hidden=!d.costControls),d.pushToTalk||(l.button.setAttribute("aria-label","Toggle voice control"),l.helpDetail&&(l.helpDetail.textContent="Activate to toggle voice"));const f=h.controller||u;f.session=u;const p=u.subscribe(v=>{var M;v.type==="state"&&(l.root.dataset.status=v.state,l.status.textContent=v.state==="idle"?"OFF":v.state.toUpperCase(),l.detail.textContent=v.detail||(v.state==="idle"?"Voice off":"Voice active"),l.button.setAttribute("aria-pressed",String(u.isActive())),l.errorDetail&&(l.errorDetail.textContent=v.state==="error"?v.detail||"Voice could not be started.":""),v.state==="error"&&((M=l.root.classList)==null||M.remove("error-dismissed")))}),g=(C=n==null?void 0:n.onOutlineEvent)==null?void 0:C.call(n,v=>{u.sendMapEvent({type:"map_annotation_outline",...v})}),_=()=>{var v;(v=h.ignoreButtonClick)!=null&&v.call(h)||(u.isActive()?u.stop():u.start({pushToTalk:!1}))};return l.button.addEventListener("click",_),u.signal.addEventListener("abort",()=>{l.button.removeEventListener("click",_),g==null||g(),p(),l.root.remove()},{once:!0}),u.disposed?(l.button.removeEventListener("click",_),g==null||g(),p(),l.root.remove()):(y=h.bindControls)==null||y.call(h),window.__gevVoiceCommands=f,f}function x7(e){var n,i;const t=e==null?void 0:e.type;if(t==="input_audio_buffer.speech_started")return{type:"interruption",reason:"user-speech"};if(t==="conversation.item.input_audio_transcription.completed")return{type:"transcript",role:"user",text:e.transcript||"",final:!0,itemId:e.item_id||null};if(["response.output_audio_transcript.delta","response.output_audio_transcript.done","response.output_text.delta","response.output_text.done","response.audio_transcript.delta","response.audio_transcript.done","response.text.delta","response.text.done"].includes(t)){const o=t.endsWith(".done");return{type:"transcript",role:"assistant",text:o?e.transcript??e.text??"":e.delta||"",final:o,itemId:e.item_id||null,responseId:e.response_id||null}}return t==="response.done"?{type:"completion",responseId:((n=e.response)==null?void 0:n.id)||null,status:((i=e.response)==null?void 0:i.status)||"unknown"}:null}const Xr=Object.freeze({standard:Object.freeze({tier:"standard",id:"gpt-realtime-2",label:"STANDARD",rates:Object.freeze({textInput:4,textCachedInput:.4,textOutput:24,audioInput:32,audioCachedInput:.4,audioOutput:64,imageInput:5,imageCachedInput:.5})}),mini:Object.freeze({tier:"mini",id:"gpt-realtime-2.1-mini",label:"MINI",rates:Object.freeze({textInput:.6,textCachedInput:.06,textOutput:2.4,audioInput:10,audioCachedInput:.3,audioOutput:20,imageInput:.8,imageCachedInput:.08})})}),Vc="standard";Object.freeze(Object.keys(Xr));function Mi(e){return ek(e)?Xr[String(e).trim().toLowerCase()]:Xr[Vc]}function ek(e){const t=typeof e=="string"?e.trim().toLowerCase():"";return Object.prototype.hasOwnProperty.call(Xr,t)}function F7(){return Object.values(Xr).reduce((e,t)=>t.rates.audioOutput>e.rates.audioOutput?t:e)}function S7(e){const t=typeof e=="string"?e.trim():"";for(const i of Object.values(Xr))if(i.id===t)return{...i,recognized:!0};const n=F7();return{...n,id:t||n.id,recognized:!1}}const kC=Object.freeze({warnUsd:2,capUsd:5}),tk="off";function Pr(e){const t=(n,i)=>{if(typeof n=="string"&&n.trim().toLowerCase()===tk||n===1/0)return 1/0;if(n==null)return i;const o=Number(n);return Number.isFinite(o)?o>0?o:1/0:i};return Object.freeze({warnUsd:t(e==null?void 0:e.warnUsd,kC.warnUsd),capUsd:t(e==null?void 0:e.capUsd,kC.capUsd)})}function N7(e){const t=Pr(e),n=i=>Number.isFinite(i)?i:tk;return{warnUsd:n(t.warnUsd),capUsd:n(t.capUsd)}}const ft=e=>{const t=Number(e);return Number.isFinite(t)&&t>0?t:0};function D7(e){const t=(e==null?void 0:e.input_token_details)||null,n=(e==null?void 0:e.output_token_details)||null,i=(t==null?void 0:t.cached_tokens_details)||null,o=ft(e==null?void 0:e.input_tokens),r=ft(e==null?void 0:e.output_tokens);let s,a,c,l,u,h;t?(l=ft(i==null?void 0:i.text_tokens),u=ft(i==null?void 0:i.audio_tokens),h=ft(i==null?void 0:i.image_tokens),!i&&ft(t.cached_tokens)>0&&(u=Math.min(ft(t.cached_tokens),ft(t.audio_tokens))),s=Math.max(0,ft(t.text_tokens)-l),a=Math.max(0,ft(t.audio_tokens)-u),c=Math.max(0,ft(t.image_tokens)-h)):(s=0,a=o,c=0,l=0,u=0,h=0);const d=Math.max(0,o-(s+a+c+l+u+h));a+=d;const f=n?ft(n.text_tokens):0;let p=n?ft(n.audio_tokens):r;const g=Math.max(0,r-(f+p));return p+=g,{textIn:s,audioIn:a,imageIn:c,textCached:l,audioCached:u,imageCached:h,textOut:f,audioOut:p,inputTotal:o,outputTotal:r}}function O7(e,t){if(!e||!t)return 0;const n=D7(e),i=(n.textIn*ft(t.textInput)+n.textCached*ft(t.textCachedInput)+n.textOut*ft(t.textOutput)+n.audioIn*ft(t.audioInput)+n.audioCached*ft(t.audioCachedInput)+n.audioOut*ft(t.audioOutput)+n.imageIn*ft(t.imageInput)+n.imageCached*ft(t.imageCachedInput))/1e6;return Number.isFinite(i)&&i>0?i:0}function ar(e){const t=Number.isFinite(Number(e))?Math.max(0,Number(e)):0;return t>0&&t<.01?"~$0.01":`~$${t.toFixed(2)}`}function fs(e={}){const t=e.modelId?S7(e.modelId):{...Mi(e.tier),recognized:!0},n=Pr(e.limits);let i=0,o=0,r=!1,s=!1,a=!1;const c=(l=!1,u=!1)=>({tier:t.tier,modelId:t.id,ratesRecognized:t.recognized!==!1,totalUsd:i,responses:o,warnUsd:n.warnUsd,capUsd:n.capUsd,level:s?"cap":r?"warn":"ok",warnCrossed:l,capCrossed:u,capReached:s,incomplete:a,display:ar(i)+(a?"*":""),note:a?"Estimate is incomplete — a response was still in flight when the session ended, so its usage was never reported.":null});return{model:t,limits:n,record(l){const u=O7(l,t.rates);u>0&&(i+=u,o+=1);let h=!1,d=!1;return!r&&i>=n.warnUsd&&(r=!0,h=!0),!s&&i>=n.capUsd&&(s=!0,d=!0),c(h,d)},state:()=>c(),markIncomplete(){return a=!0,c()},reset(){return i=0,o=0,r=!1,s=!1,a=!1,c()}}}function B7({tokenEndpoint:e="/api/realtime/token",callsEndpoint:t="https://api.openai.com/v1/realtime/calls",tokenTransport:n=(...s)=>fetch(...s),connectionTransport:i=(...s)=>fetch(...s),timeoutMs:o=3e4,signal:r}={}){const s=a=>AbortSignal.any([r,a,AbortSignal.timeout(o)].filter(Boolean));return Object.freeze({protocol:"openai-realtime",async requestToken({tier:a=Vc,signal:c}={}){var g,_,m,b,C,y,v,M;c=s(c),c.throwIfAborted();const l=e.includes("?")?"&":"?",u=`${e}${l}tier=${encodeURIComponent(Mi(a).tier)}`,h=await n(u,{signal:c,cache:"no-store",redirect:"error"});c.throwIfAborted();const d=await h.json().catch(()=>null);if(c.throwIfAborted(),!h.ok){const w=typeof(d==null?void 0:d.error)=="string"?d.error:(g=d==null?void 0:d.error)==null?void 0:g.message;throw new Error(w||`Realtime token failed: HTTP ${h.status}`)}const f=(d==null?void 0:d.value)||((_=d==null?void 0:d.client_secret)==null?void 0:_.value)||(d==null?void 0:d.client_secret);if(typeof f!="string"||!f)throw new Error("Realtime token response did not include a client secret");const p=(d==null?void 0:d.expires_at)??((m=d==null?void 0:d.client_secret)==null?void 0:m.expires_at);if(p!=null&&(!Number.isFinite(p)||p*1e3<=Date.now()))throw new Error("Realtime client secret has expired; reconnect to request a new one");return{token:f,model:((C=(b=h.headers)==null?void 0:b.get)==null?void 0:C.call(b,"X-GEV-Voice-Model"))||((y=d==null?void 0:d.session)==null?void 0:y.model)||null,tier:((M=(v=h.headers)==null?void 0:v.get)==null?void 0:M.call(v,"X-GEV-Voice-Tier"))||null,expiresAt:p}},async negotiate({offerSdp:a,credential:c,signal:l}){var d,f;if(l=s(l),l.throwIfAborted(),c.expiresAt!=null&&c.expiresAt*1e3<=Date.now())throw new Error("Realtime client secret has expired; reconnect to request a new one");const u=await i(t,{method:"POST",body:a,signal:l,redirect:"error",cache:"no-store",headers:{Authorization:`Bearer ${c.token}`,"Content-Type":"application/sdp"}});if(l.throwIfAborted(),!u.ok)throw await((f=(d=u.body)==null?void 0:d.cancel)==null?void 0:f.call(d).catch(()=>{})),new Error(`Realtime SDP failed: HTTP ${u.status}`);const h=await u.text();return l.throwIfAborted(),h}})}const AC={idle:"OFF",connecting:"CONNECTING",listening:"LISTENING",executing:"EXECUTING",error:"ERROR"},V7=2500,H7=500,IC=6e3,$7=1200*900,RC=200*1024,cp=30,nk="gev-realtime-errors",bf="/api/realtime/debug-log",ik="godsEyeView.voiceCost.tier",ok="godsEyeView.voiceCost.limits",G7=.12,U7=.04;function pu(e){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function LC(e){var t;try{const n=(t=pu(e))==null?void 0:t.getItem(ik);return ek(n)?Mi(n).tier:Vc}catch{return Vc}}function z7(e,t){var i;const n=Mi(e).tier;try{(i=pu(t))==null||i.setItem(ik,n)}catch{}return n}function PC(e){var t;try{const n=(t=pu(e))==null?void 0:t.getItem(ok);return Pr(n?JSON.parse(n):null)}catch{return Pr(null)}}function j7(e,t){var i;const n=Pr(e);try{(i=pu(t))==null||i.setItem(ok,JSON.stringify(N7(n)))}catch{}return n}function xC({status:e="idle",speaker:t="idle",pushToTalkKeyHeld:n=!1}={}){return e==="connecting"||e==="executing"||t==="user"||t==="ai"||!!n}function q7(e){return!!(e!=null&&e.ok&&e.action==="control_radio"&&["play","resume","select","next","previous"].includes(e.radioAction))}async function W7(e,{prepareRadio:t,stopVoice:n,cancelRadio:i,isCurrent:o=()=>!0}={}){if(!(e!=null&&e.ok)||!e.radioPlaybackRequested)return{handled:!1,result:e};try{const r=await(t==null?void 0:t()),s=!!(o!=null&&o());return!r||!s?(i==null||i(),{handled:!0,cancelled:!s,result:{...e,ok:!1,audioState:s?"error":"stopped",error:s?e.error||"Radio playback could not start":"Radio playback handoff was cancelled"}}):(n==null||n(),{handled:!0,result:{...e,ok:!0,audioState:"playing"}})}catch(r){return i==null||i(),{handled:!0,result:{...e,ok:!1,audioState:"error",error:(r==null?void 0:r.message)||"Radio playback could not start"}}}}function K7({duckRadio:e,pauseRadio:t}={}){return e==null||e(),(t==null?void 0:t())||!1}const Y7=8;class X7{constructor({runner:t,ui:n,radioLayer:i=null,dataManager:o=null,backend:r=B7(),signal:s,debugSink:a=tY,actionExecutor:c,onSessionEvent:l}){var u,h,d,f;this.actionExecutor=c,this.onSessionEvent=l,this.backend=r,this.lifetimeSignal=s,this.connectionAbort=null,this.debugSink=a,this.lifetimeAbort=()=>this.stop({removeUi:!0}),s==null||s.addEventListener("abort",this.lifetimeAbort,{once:!0}),this.runner=t,this.ui=n,this.radioLayer=i,this.dataManager=o,this.radioVoiceDucked=!1,this.pc=null,this.dc=null,this.stream=null,this.audioEl=null,this.visualizerAudioContext=null,this.visualizerAnalyser=null,this.visualizerSource=null,this.visualizerFrame=null,this.visualizerData=null,this.visualizerOutputSource=null,this.visualizerOutputAnalyser=null,this.visualizerOutputData=null,this.visualizerSpeaker="idle",this.processedCalls=new Map,this.responseActive=!1,this.responseCreatePending=!1,this.userTurnPending=!1,this.pendingResponseInstructions=null,this.pendingUserTextResponse=!1,this.activeResponseId=null,this.supersededResponseIds=new Set,this.pendingRadioPlaybackResult=null,this.radioHandoffEpoch=0,this.radioHandoffCancellation=null,this.activeToolAbortControllers=new Set,this.activeRadioToolControllers=new Map,this.radioHandoffInFlight=!1,this.radioHandoffAttemptId=null,this.radioHandoffInFlightResult=null,this.radioVisibilityOffReservation=0,this.radioVisibilityOffPending=!1,this.radioToolHandoffReservations=new Map,this.radioHandoffDeferredByReservation=!1,this.buttonHandler=null,this.tierHandler=null,this.annotationEventUnsubscribe=null,this.voiceTier=LC(),this.voiceLimits=PC(),this.costTracker=fs({tier:this.voiceTier,limits:this.voiceLimits}),this.costCapStopped=!1,this.radioControlUnsubscribe=((h=(u=this.radioLayer)==null?void 0:u.subscribePlaybackControls)==null?void 0:h.call(u,p=>{const g=typeof p=="string"?{action:p,origin:"user"}:p||{};g.origin==="user"&&(g.action==="pause"||g.action==="stop")?this.cancelRadioHandoff():g.origin==="user"&&g.action==="play"&&this.isActive()&&this.stop({preserveRadioPlayback:!0})}))||null,this.radioVisibilityRequestUnsubscribe=((f=(d=this.dataManager)==null?void 0:d.subscribeVisibilityRequests)==null?void 0:f.call(d,p=>{(p==null?void 0:p.layerId)==="radio"&&p.enabled===!1&&p.origin==="user"&&this.reserveRadioVisibilityOff()}))||null,this.radioVisibilityUnsubscribe=null,this.pushToTalkMode=!1,this.pushToTalkKeyHeld=!1,this.spaceKeyHeld=!1,this.pushToTalkHoldTimer=null,this.pushToTalkHoldGeneration=0,this.pushToTalkHoldFocusOwner=null,this.pushToTalkHoldControl=null,this.pushToTalkHoldPreservesNative=!1,this.shortcutKeyDownHandler=null,this.shortcutKeyUpHandler=null,this.shortcutBlurHandler=null,this.shortcutVisibilityHandler=null,this.status="idle",this.startEpoch=0,this.disconnectGraceTimer=null,this._tearingDown=!1,this.pendingViewportDeletes=new Set,this.errors=mY(),this.sessionId=eY(),this.debugLog("controller.created",{status:this.status})}isActive(){return this.status!=="idle"&&this.status!=="error"}async start({pushToTalk:t=!1}={}){var c,l,u,h,d;if(this.isActive()||(c=this.lifetimeSignal)!=null&&c.aborted)return;this.pauseRadioForVoice();const n=t&&this.pushToTalkKeyHeld,i=this.spaceKeyHeld;if(this.stop({preserveStatus:!0}),this.pushToTalkMode=t,this.pushToTalkKeyHeld=n,this.spaceKeyHeld=i,!window.RTCPeerConnection||!((l=navigator.mediaDevices)!=null&&l.getUserMedia)){this.setStatus("error","WebRTC microphone support unavailable");return}if((u=this.lifetimeSignal)!=null&&u.aborted)return;const o=++this.startEpoch;(h=this.connectionAbort)==null||h.abort(),this.connectionAbort=new AbortController;const r=AbortSignal.any([this.connectionAbort.signal,this.lifetimeSignal].filter(Boolean));this.voiceTier=LC(),this.voiceLimits=PC(),this.costCapStopped=!1,this.costTracker=fs({tier:this.voiceTier,limits:this.voiceLimits}),this.syncCostUi(),this.setStatus("connecting","Requesting microphone"),this.debugLog("session.starting",{epoch:o,tier:this.voiceTier,connection:this.connectionDiagnostics()});let s=null,a=null;try{const f=await this.backend.requestToken({tier:this.voiceTier,signal:r}),p=f.token;if(this.abandonStart(o,{localStream:s,localPc:a}))return;this.costTracker=fs({modelId:f.model||Mi(this.voiceTier).id,limits:this.voiceLimits});const g=this.costTracker.state();if(g.ratesRecognized||console.warn(`[GEV voice] unrecognised Realtime model "${g.modelId}" — billing this session at the most expensive known rates. Update the rate table in src/voice/voiceCost.js.`),this.syncCostUi(),this.debugLog("session.token.ready",{hasToken:!!p,servedModel:f.model||null,servedTier:f.tier||null,ratesRecognized:g.ratesRecognized}),s=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1}}),this.abandonStart(o,{localStream:s,localPc:a}))return;this.stream=s,this.setMicrophoneEnabled(!this.pushToTalkMode||this.pushToTalkKeyHeld),this.startVoiceVisualizer(s),document.querySelectorAll('audio[data-gev-realtime-audio="true"]').forEach(C=>C.remove()),this.audioEl=document.createElement("audio"),this.audioEl.autoplay=!0,this.audioEl.dataset.gevRealtimeAudio="true",this.audioEl.style.display="none",document.body.appendChild(this.audioEl),a=new RTCPeerConnection,this.pc=a,this.pc.ontrack=C=>{const y=C.streams[0];this.audioEl.srcObject=y,this.startAssistantVoiceVisualizer(y)},this.pc.onconnectionstatechange=()=>this.handleConnectionStateChange(),this.pc.oniceconnectionstatechange=()=>{var C;((C=this.pc)==null?void 0:C.iceConnectionState)==="failed"&&this.fatalError("ICE connection",null,this.connectionDiagnostics())},this.pc.onicecandidateerror=C=>{this.reportError("ICE candidate",C,{errorCode:C.errorCode,errorText:C.errorText,address:C.address,port:C.port,url:C.url,...this.connectionDiagnostics()})},this.stream.getTracks().forEach(C=>this.pc.addTrack(C,this.stream));const _=this.pc.createDataChannel("oai-events");this.dc=_,_.addEventListener("open",()=>{const C=this.pushToTalkMode?this.pushToTalkKeyHeld?"Release Space to send":"Hold Space to talk":"Ask or command";this.setStatus("listening",C),this.debugLog("data_channel.open",{connection:this.connectionDiagnostics(_)})}),_.addEventListener("message",C=>this.handleRealtimeEvent(C)),_.addEventListener("error",C=>{this._tearingDown||this.dc!==_||this.fatalError("Realtime data channel",C,this.connectionDiagnostics(_))}),_.addEventListener("close",()=>{this._tearingDown||this.dc===_&&this.status!=="idle"&&this.status!=="error"&&this.fatalError("Realtime data channel closed",null,this.connectionDiagnostics(_))});const m=await this.pc.createOffer();if(await this.pc.setLocalDescription(m),this.abandonStart(o,{localStream:s,localPc:a}))return;this.debugLog("webrtc.offer.created",{sdpLength:((d=m.sdp)==null?void 0:d.length)||0,connection:this.connectionDiagnostics()});const b=await this.backend.negotiate({offerSdp:m.sdp,credential:f,signal:r});if(this.abandonStart(o,{localStream:s,localPc:a})||(await this.pc.setRemoteDescription({type:"answer",sdp:b}),this.abandonStart(o,{localStream:s,localPc:a})))return;this.debugLog("webrtc.answer.applied",{connection:this.connectionDiagnostics()})}catch(f){if(o!==this.startEpoch){FC({localStream:s,localPc:a});return}const p=this.connectionDiagnostics();this.stop({preserveStatus:!0}),this.reportError("Realtime connection",f,p)}}abandonStart(t,n){return t===this.startEpoch?!1:(n.localStream&&this.stream===n.localStream&&(this.stream=null),n.localPc&&this.pc===n.localPc&&(this.pc=null,this.dc=null),FC(n),this.debugLog("session.start.abandoned",{epoch:t,currentEpoch:this.startEpoch}),!0)}handleConnectionStateChange(){var n;const t=(n=this.pc)==null?void 0:n.connectionState;if(t==="failed"){this.fatalError("WebRTC connection",null,this.connectionDiagnostics());return}if(t==="disconnected"){if(this.disconnectGraceTimer)return;this.debugLog("webrtc.disconnected.grace",{graceMs:IC,connection:this.connectionDiagnostics()}),this.disconnectGraceTimer=setTimeout(()=>{var i;this.disconnectGraceTimer=null,((i=this.pc)==null?void 0:i.connectionState)==="disconnected"&&this.fatalError("WebRTC connection lost",null,this.connectionDiagnostics())},IC);return}(t==="connected"||t==="completed")&&this.clearDisconnectGrace()}clearDisconnectGrace(){this.disconnectGraceTimer&&(clearTimeout(this.disconnectGraceTimer),this.disconnectGraceTimer=null)}bindPushToTalkShortcut(){this.shortcutKeyDownHandler||(this.shortcutKeyDownHandler=t=>{var i,o;if(!bY(t))return;if(t.repeat){this.spaceKeyHeld&&!this.pushToTalkHoldPreservesNative&&t.preventDefault(),this.pushToTalkKeyHeld&&t.preventDefault();return}if(this.spaceKeyHeld=!0,this.pushToTalkHoldFocusOwner=document.activeElement,this.pushToTalkHoldControl=DC(document.activeElement)?document.activeElement:DC(t.target)?((o=(i=t.target).closest)==null?void 0:o.call(i,sk))||t.target:null,this.pushToTalkHoldPreservesNative=!!this.pushToTalkHoldControl,this.pushToTalkHoldPreservesNative||t.preventDefault(),this.isActive()&&!this.pushToTalkMode)return;this.cancelPushToTalkHold();const n=++this.pushToTalkHoldGeneration;this.pushToTalkHoldTimer=setTimeout(()=>{this.pushToTalkHoldTimer=null,n===this.pushToTalkHoldGeneration&&(!this.spaceKeyHeld||this.pushToTalkKeyHeld||document.activeElement===this.pushToTalkHoldFocusOwner&&(document.visibilityState==="hidden"||typeof document.hasFocus=="function"&&!document.hasFocus()||this.isActive()&&!this.pushToTalkMode||(this.pushToTalkHoldControl&&document.activeElement===this.pushToTalkHoldControl&&typeof this.pushToTalkHoldControl.blur=="function"&&this.pushToTalkHoldControl.blur(),this.pauseRadioForVoice(),this.pushToTalkKeyHeld=!0,this.isActive()?(this.ui.root.dataset.pushToTalk="held",this.setMicrophoneEnabled(!0),this.status==="listening"&&this.setStatus("listening","Release Space to send")):(this.start({pushToTalk:!0}),this.pushToTalkKeyHeld&&(this.ui.root.dataset.pushToTalk="held")))))},H7)},this.shortcutKeyUpHandler=t=>{if(!rk(t))return;const n=this.spaceKeyHeld,i=this.pushToTalkHoldPreservesNative;if(this.spaceKeyHeld=!1,this.cancelPushToTalkHold(),!this.pushToTalkKeyHeld){n&&!i&&t.preventDefault(),this.resetPushToTalkGesture();return}t.preventDefault(),this.releasePushToTalkKey(),this.resetPushToTalkGesture()},this.shortcutBlurHandler=()=>{this.spaceKeyHeld=!1,this.cancelPushToTalkHold(),this.releasePushToTalkKey(),this.resetPushToTalkGesture()},this.shortcutVisibilityHandler=()=>{document.visibilityState==="hidden"&&this.shortcutBlurHandler()},document.addEventListener("keydown",this.shortcutKeyDownHandler,!0),document.addEventListener("keyup",this.shortcutKeyUpHandler,!0),window.addEventListener("blur",this.shortcutBlurHandler),document.addEventListener("visibilitychange",this.shortcutVisibilityHandler))}cancelPushToTalkHold(){this.pushToTalkHoldGeneration++,this.pushToTalkHoldTimer!==null&&(clearTimeout(this.pushToTalkHoldTimer),this.pushToTalkHoldTimer=null)}resetPushToTalkGesture(){this.pushToTalkHoldFocusOwner=null,this.pushToTalkHoldControl=null,this.pushToTalkHoldPreservesNative=!1}releasePushToTalkKey(){this.cancelPushToTalkHold(),this.pushToTalkKeyHeld&&(this.pushToTalkKeyHeld=!1,delete this.ui.root.dataset.pushToTalk,this.pushToTalkMode&&(this.setMicrophoneEnabled(!1),this.status==="listening"?this.setStatus("listening","Hold Space to talk"):this.updateVoiceButtonLabel()))}setMicrophoneEnabled(t){var n,i,o;(n=this.ui)!=null&&n.root&&(this.ui.root.dataset.microphone=t?"active":"muted"),(o=(i=this.stream)==null?void 0:i.getAudioTracks)==null||o.call(i).forEach(r=>{r.enabled=!!t})}startVoiceVisualizer(t){this.stopVoiceVisualizer();const n=window.AudioContext||window.webkitAudioContext,i=Array.from(this.ui.root.querySelectorAll(".gev-voice-visualizer span"));if(!(!n||!t||!i.length))try{const o=new n;o.resume().catch(()=>{});const r=o.createAnalyser();r.fftSize=64,r.smoothingTimeConstant=.72;const s=o.createMediaStreamSource(t);s.connect(r),this.visualizerAudioContext=o,this.visualizerAnalyser=r,this.visualizerSource=s,this.visualizerData=new Uint8Array(r.frequencyBinCount);const a=()=>{const c=CY(this.visualizerSpeaker,{analyser:this.visualizerAnalyser,data:this.visualizerData},{analyser:this.visualizerOutputAnalyser,data:this.visualizerOutputData});if(!c){OC(i),this.visualizerFrame=requestAnimationFrame(a);return}c.analyser.getByteFrequencyData(c.data);const l=c.data.length;i.forEach((u,h)=>{const d=Math.floor(h/i.length*l),f=Math.max(d+1,Math.floor((h+1)/i.length*l));let p=0;for(let b=d;b{}),this.visualizerAudioContext=null),OC((o=(i=this.ui)==null?void 0:i.root)==null?void 0:o.querySelectorAll(".gev-voice-visualizer span"))}fatalError(t,n=null,i={}){return this.stop({preserveStatus:!0}),this.reportError(t,n,i)}stop(t={}){var s,a,c,l,u,h,d,f;const{removeUi:n=!1,preserveStatus:i=!1,preserveRadioPlayback:o=!1}=t;this.startEpoch++,(s=this.connectionAbort)==null||s.abort(),this.connectionAbort=null,n&&((a=this.lifetimeSignal)==null||a.removeEventListener("abort",this.lifetimeAbort)),this.cancelPushToTalkHold(),this.radioHandoffEpoch++;for(const p of this.activeToolAbortControllers)p.abort();this.activeToolAbortControllers.clear(),this.activeRadioToolControllers.clear();const r=this.radioHandoffAttemptId;if(this.radioHandoffInFlight&&!o&&((l=(c=this.radioLayer)==null?void 0:c.stopPlayback)==null||l.call(c,{origin:"voice-cleanup",attemptId:r})),this.radioHandoffInFlight=!1,this.radioHandoffAttemptId=null,this.radioHandoffInFlightResult=null,this.radioVisibilityOffReservation++,this.radioVisibilityOffPending=!1,this.radioToolHandoffReservations.clear(),this.radioHandoffDeferredByReservation=!1,this.clearDisconnectGrace(),this._tearingDown=!0,this.debugLog("session.stop",{removeUi:n,preserveStatus:i,status:this.status,connection:this.connectionDiagnostics()}),this.dc){this.responseActive&&this.costTracker.markIncomplete();try{this.dc.close()}catch{}this.dc=null}if(this.pc){try{this.pc.close()}catch{}this.pc=null}this._tearingDown=!1,this.stream?(this.stopVoiceVisualizer(),this.stream.getTracks().forEach(p=>p.stop()),this.stream=null):this.stopVoiceVisualizer(),this.audioEl&&(this.audioEl.remove(),this.audioEl=null),this.processedCalls.clear(),this.responseActive=!1,this.responseCreatePending=!1,this.userTurnPending=!1,this.pendingResponseInstructions=null,this.pendingUserTextResponse=!1,this.activeResponseId=null,this.supersededResponseIds.clear(),this.pendingRadioPlaybackResult=null,this.lastViewportItemId=null,this.pendingViewportDeletes.clear(),this.pushToTalkMode=!1,this.pushToTalkKeyHeld=!1,this.spaceKeyHeld=!1,this.resetPushToTalkGesture(),(u=this.ui)!=null&&u.root&&(delete this.ui.root.dataset.pushToTalk,delete this.ui.root.dataset.microphone),n&&((h=this.ui)!=null&&h.button)&&this.buttonHandler&&(this.ui.button.removeEventListener("click",this.buttonHandler),this.buttonHandler=null),n&&((d=this.ui)!=null&&d.tierButton)&&this.tierHandler&&(this.ui.tierButton.removeEventListener("click",this.tierHandler),this.tierHandler=null),n&&(this.shortcutKeyDownHandler&&document.removeEventListener("keydown",this.shortcutKeyDownHandler,!0),this.shortcutKeyUpHandler&&document.removeEventListener("keyup",this.shortcutKeyUpHandler,!0),this.shortcutBlurHandler&&window.removeEventListener("blur",this.shortcutBlurHandler),this.shortcutVisibilityHandler&&document.removeEventListener("visibilitychange",this.shortcutVisibilityHandler),this.shortcutKeyDownHandler=null,this.shortcutKeyUpHandler=null,this.shortcutBlurHandler=null,this.shortcutVisibilityHandler=null),n&&this.annotationEventUnsubscribe&&(this.annotationEventUnsubscribe(),this.annotationEventUnsubscribe=null),n&&this.radioControlUnsubscribe&&(this.radioControlUnsubscribe(),this.radioControlUnsubscribe=null),n&&this.radioVisibilityRequestUnsubscribe&&(this.radioVisibilityRequestUnsubscribe(),this.radioVisibilityRequestUnsubscribe=null),n&&this.radioVisibilityUnsubscribe&&(this.radioVisibilityUnsubscribe(),this.radioVisibilityUnsubscribe=null),n&&((f=this.ui)!=null&&f.root)&&this.ui.root.remove(),!i&&!n&&this.setStatus("idle","Voice off"),this.setRadioVoiceDucking(!1),n&&this.emitSessionEvent({type:"disposed"})}notifyMapEvent(t){return!this.dc||this.dc.readyState!=="open"?!1:this.sendRealtimeEvent({type:"conversation.item.create",item:{type:"message",role:"system",content:[{type:"input_text",text:JSON.stringify(t)}]}},"client.map_event")}sendTextCommand(t){if(!this.dc||this.dc.readyState!=="open")throw new Error("GEV voice is not connected");const n=String(t||"").trim();if(!n)return;this.cancelRadioHandoff({abortTools:!0}),this.supersedeActiveResponseForUserTurn();const i={type:"conversation.item.create",item:{type:"message",role:"user",content:[{type:"input_text",text:n}]}};this.sendRealtimeEvent(i,"client.user_text"),this.requestUserTextResponse()}supersedeActiveResponseForUserTurn(){if(this.activeResponseId)for(this.supersededResponseIds.add(this.activeResponseId);this.supersededResponseIds.size>Y7;)this.supersededResponseIds.delete(this.supersededResponseIds.values().next().value);this.pendingResponseInstructions=null}isSupersededResponse(t){return!!t&&this.supersededResponseIds.has(t)}requestUserTextResponse(){if(this.responseActive||this.responseCreatePending){this.pendingUserTextResponse=!0,this.debugLog("response.create.deferred_user_text",{responseActive:this.responseActive,responseCreatePending:this.responseCreatePending});return}if(!this.dc||this.dc.readyState!=="open")return;this.pendingUserTextResponse=!1,this.responseCreatePending=!0,this.sendRealtimeEvent({type:"response.create"},"client.response_create.user_text")||(this.responseCreatePending=!1)}async handleRealtimeEvent(t){var l,u,h,d,f,p,g,_,m,b,C,y,v,M,w,E,k,T,I;let n=null;try{n=JSON.parse(t.data)}catch{return}const i=x7(n);if(i&&this.emitSessionEvent(i),this.debugLog("server.event",{type:n.type,eventId:n.event_id||null,responseId:n.response_id||((l=n.response)==null?void 0:l.id)||null,payload:n}),n.type==="error"){if(((u=n.error)==null?void 0:u.code)==="conversation_already_has_active_response"){this.cancelRadioHandoff({abortTools:!0}),this.responseActive=!0,this.responseCreatePending=!1,this.pendingResponseInstructions=null,this.pendingUserTextResponse=!1,console.warn("[GEV Realtime] Skipped overlapping response.create"),this.debugLog("response.create.skipped_active",{eventId:n.event_id,activeResponseMessage:((h=n.error)==null?void 0:h.message)||null}),this.setStatus("listening","Ask or command");return}if(cY(n,this.pendingViewportDeletes)){n.event_id&&this.pendingViewportDeletes.delete(n.event_id),console.warn("[GEV Realtime] Ignored stale viewport item_not_found",((d=n.error)==null?void 0:d.code)||null),this.debugLog("viewport_delete.item_not_found",{eventId:n.event_id||null,code:((f=n.error)==null?void 0:f.code)||null});return}this.responseActive=!1,this.responseCreatePending=!1,this.pendingResponseInstructions=null,this.pendingUserTextResponse=!1,this.cancelRadioHandoff({abortTools:!0}),this.reportError("Realtime API",n.error,{eventId:n.event_id,type:(p=n.error)==null?void 0:p.type,code:(g=n.error)==null?void 0:g.code,param:(_=n.error)==null?void 0:_.param,...this.connectionDiagnostics()});return}if(n.type==="input_audio_buffer.speech_started"&&(this.userTurnPending=!0,this.pendingResponseInstructions=null,this.cancelRadioHandoff({abortTools:!0}),this.setVoiceSpeaker("user")),this.updateResponseState(n),this.isSessionEnding())return;if(n.type==="response.done"&&this.pendingRadioPlaybackResult){if(((m=n.response)==null?void 0:m.status)!=="completed"||this.userTurnPending){this.pendingRadioPlaybackResult=null;return}if(this.pendingResponseInstructions){this.flushPendingResponse();return}if(this.isRadioHandoffReserved()){this.radioHandoffDeferredByReservation=!0;return}await this.startPendingRadioHandoff();return}const o=lY(n);if(!o.length)return;if(this.isSessionEnding()){this.debugLog("voice.cost.cap.tools_skipped",{skipped:o.length});return}const r=n.response_id||((b=n.response)==null?void 0:b.id)||null;if(this.isSupersededResponse(r)){this.pruneProcessedCalls();for(const R of o){const S=NC(R);S.some(A=>this.processedCalls.has(A))||(S.forEach(A=>this.processedCalls.set(A,performance.now())),this.sendToolOutput(R.call_id||R.id,{ok:!1,action:R.name,superseded:!0,error:"Superseded by a newer command from the operator — this call was not run."}))}this.debugLog("tool.call.skipped_superseded",{responseId:r,skipped:o.map(R=>R.name)});return}this.setStatus("executing","Running command"),this.pruneProcessedCalls();let s=!1,a=null,c=!1;for(const R of o){const S=NC(R);if(S.some(x=>this.processedCalls.has(x)))continue;S.forEach(x=>this.processedCalls.set(x,performance.now()));let A;const L=this.dc;let F=this.radioHandoffEpoch,P=null,O=!1,D=null,$=R.name==="control_radio";try{const x=uY(R.arguments),N=R.name==="control_radio",G=R.name==="set_layer_visibility"&&x.layerId==="radio";$=N||G;const W=N?String(x.action||"").toLowerCase():null,V=G||["enable","disable"].includes(W)?"visibility":W==="status"?"query":N?"playback":null;if(O=N&&["disable","pause","stop"].includes(W)||G&&x.enabled===!1,O&&(D=this.reserveRadioToolHandoff({abortScope:W==="disable"||G&&x.enabled===!1?"all":"playback"})),F=this.radioHandoffEpoch,this.debugLog("tool.call",{name:R.name,callId:R.call_id||R.id||null,arguments:x}),P=new AbortController,this.activeToolAbortControllers.add(P),$&&this.activeRadioToolControllers.set(P,{responseId:r,authorityDomain:V}),A=await(this.actionExecutor||this.runner)(R.name,x,{signal:P.signal,isCurrent:()=>this.activeToolAbortControllers.has(P)&&!this.userTurnPending&&this.dc===L&&(L==null?void 0:L.readyState)==="open"&&(V!=="playback"||F===this.radioHandoffEpoch)}),A!=null&&A.ok&&A.radioPlaybackRequested){const H=this.activeToolAbortControllers.has(P)&&!this.userTurnPending&&this.dc===L&&(L==null?void 0:L.readyState)==="open",B=H&&F===this.radioHandoffEpoch,q=!!(H&&!B&&r&&((C=this.radioHandoffCancellation)==null?void 0:C.epoch)===this.radioHandoffEpoch&&((y=this.radioHandoffCancellation)==null?void 0:y.responseId)===r);if(B)this.pendingRadioPlaybackResult=A;else if(q){const z=((M=(v=this.radioLayer)==null?void 0:v.getUIState)==null?void 0:M.call(v))||{},j=Lr(this.dataManager,"radio",{fallbackEnabled:z.enabled??A.enabled});A={...A,radioPlaybackRequested:!1,radioPlaybackSuppressed:!0,...j,audioState:z.audioState||A.audioState||"stopped"}}else A={...A,ok:!1,radioPlaybackRequested:!1,cancelled:!0,error:"Radio request was superseded by a newer Radio control or voice turn"}}else A!=null&&A.ok&&A.action==="control_radio"&&["disable","pause","stop"].includes(A.radioAction)&&(O||this.cancelRadioHandoff({abortRadioSiblings:A.radioAction==="stop",responseId:r}))}catch(x){const N=$?((E=(w=this.radioLayer)==null?void 0:w.getUIState)==null?void 0:E.call(w))||{}:null;A={ok:!1,error:(x==null?void 0:x.message)||"GEV command failed",tool:R.name,...$?Lr(this.dataManager,"radio",{fallbackEnabled:N==null?void 0:N.enabled}):{}}}finally{P&&(this.activeToolAbortControllers.delete(P),this.activeRadioToolControllers.delete(P))}if(D&&(A!=null&&A.ok)){this.settleRadioToolHandoffReservation(D,{commit:!0,responseId:r}),D=null;const x=((T=(k=this.radioLayer)==null?void 0:k.getUIState)==null?void 0:T.call(k))||{},N=Lr(this.dataManager,"radio",{fallbackEnabled:x.enabled??A.enabled});A={...A,...N,audioState:x.audioState||A.audioState,...A.radioAction==="pause"&&N.enabled===!1?{changed:!1}:{}}}this.debugLog("tool.result",{name:R.name,callId:R.call_id||R.id||null,result:A}),a=A,c=c||q7(A)&&!A.radioPlaybackRequested&&!A.radioPlaybackSuppressed,s=this.sendToolOutput(R.call_id||R.id,A)||s,D&&this.settleRadioToolHandoffReservation(D,{commit:!1,responseId:r})}if(c){this.stop();return}if(s&&((I=this.dc)==null?void 0:I.readyState)==="open"){try{await this.sendVisualContextIfUseful(a)}catch(R){this.debugLog("viewport_context.failed",{error:(R==null?void 0:R.message)||String(R)})}this.queueResponseCreate(J7(this.pendingRadioPlaybackResult||a))}this.setStatus("listening","Ask or command")}sendToolOutput(t,n){return!t||!this.dc||this.dc.readyState!=="open"?!1:(this.sendRealtimeEvent({type:"conversation.item.create",item:{type:"function_call_output",call_id:t,output:JSON.stringify(n)}},"client.function_call_output"),!0)}async sendVisualContextIfUseful(t){var a,c;if((t==null?void 0:t.action)!=="get_entity_context"||!this.dc||this.dc.readyState!=="open")return!1;const n=(c=(a=t.scene)==null?void 0:a.basemap)==null?void 0:c.viewScale;if(!Q7(n)||Z7(t))return!1;const i=await oY();if(!i)return!1;if(this.lastViewportItemId){const l=`evt_del_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`;this.pendingViewportDeletes.add(l),this.pendingViewportDeletes.size>8&&this.pendingViewportDeletes.delete(this.pendingViewportDeletes.values().next().value),this.sendRealtimeEvent({event_id:l,type:"conversation.item.delete",item_id:this.lastViewportItemId},"client.conversation.item.delete.old_viewport")}const o=`msg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,r={type:"conversation.item.create",item:{id:o,type:"message",role:"user",content:[{type:"input_text",text:"Current God's Eye View viewport screenshot. Read any clearly visible street, building, and place labels in the image and combine them with the structured nearbyPlaces, streetLabels, and scene context. Do not invent labels that are not legible."},{type:"input_image",image_url:i,detail:"high"}]}},s=this.sendRealtimeEvent(r,"client.viewport_context");return this.lastViewportItemId=s?o:null,s}emitSessionEvent(t){var n;try{(n=this.onSessionEvent)==null||n.call(this,t)}catch{}}setStatus(t,n){this.status=t,this.emitSessionEvent({type:"state",state:t,detail:n}),this.ui.root.dataset.status=t,t==="error"&&this.ui.root.classList.remove("error-dismissed"),this.updateVoiceButtonLabel(),this.ui.status.textContent=AC[t]||AC.idle;const i=t==="listening"&&this.pushToTalkMode?this.pushToTalkKeyHeld?"Release Space to send":"Hold Space to talk":n,o=t==="error"?"VOICE UNAVAILABLE":i||(t==="idle"?"VOICE STANDBY":"VOICE ACTIVE");this.ui.detail.textContent=o,this.ui.detail.title=o,this.ui.errorDetail&&(this.ui.errorDetail.textContent=t==="error"?i||"Voice session could not be started.":""),(t==="idle"||t==="connecting"||t==="error")&&this.setVoiceSpeaker("idle"),xC({status:t,pushToTalkKeyHeld:this.pushToTalkKeyHeld})&&this.pauseRadioForVoice()}updateVoiceButtonLabel(){this.ui.buttonLabel&&(this.ui.buttonLabel.textContent="MIC",this.ui.helpDetail&&(this.ui.helpDetail.textContent=vY(this.pushToTalkMode,this.pushToTalkKeyHeld)))}setVoiceSpeaker(t,{keepVisualizerSpeaker:n=!1}={}){const i=t==="user"||t==="ai"?t:"idle";this.visualizerSpeaker=yY(this.visualizerSpeaker,i,n),this.ui.root.dataset.speaker=i,xC({speaker:i})&&this.pauseRadioForVoice()}pauseRadioForVoice(){return K7({duckRadio:()=>this.setRadioVoiceDucking(!0),pauseRadio:()=>{var t,n;return(n=(t=this.radioLayer)==null?void 0:t.pause)==null?void 0:n.call(t,{origin:"voice-duck"})}})}setRadioVoiceDucking(t){var i,o;const n=!!t;n!==this.radioVoiceDucked&&(this.radioVoiceDucked=n,(o=(i=this.radioLayer)==null?void 0:i.setVoiceDucked)==null||o.call(i,n))}reserveRadioVisibilityOff(){const t=++this.radioVisibilityOffReservation;this.radioVisibilityOffPending=!0,this.freezeRadioHandoffForReservation({abortActiveTools:!0}),Promise.resolve().then(()=>{var n,i;return(i=(n=this.dataManager)==null?void 0:n.waitForLayerSettled)==null?void 0:i.call(n,"radio")}).then(()=>{var n,i;if(t===this.radioVisibilityOffReservation){if(this.radioVisibilityOffPending=!1,((i=(n=this.dataManager)==null?void 0:n.isEnabled)==null?void 0:i.call(n,"radio"))===!1){this.radioHandoffDeferredByReservation=!1,this.cancelRadioHandoff({abortRadioSiblings:!0});return}this.resumeDeferredRadioHandoffIfUnreserved()}})}isRadioHandoffReserved(){return this.radioVisibilityOffPending||this.radioToolHandoffReservations.size>0}freezeRadioHandoffForReservation({abortScope:t="all",abortActiveTools:n=!1}={}){var i,o;if(n&&this.abortRadioSiblingTools({scope:t}),this.radioHandoffInFlight){this.radioHandoffInFlightResult&&!this.pendingRadioPlaybackResult&&(this.pendingRadioPlaybackResult=this.radioHandoffInFlightResult),this.radioHandoffDeferredByReservation=!!this.pendingRadioPlaybackResult;const r=this.radioHandoffAttemptId;this.radioHandoffInFlight=!1,this.radioHandoffAttemptId=null,(o=(i=this.radioLayer)==null?void 0:i.stopPlayback)==null||o.call(i,{origin:"voice-cleanup",attemptId:r})}}reserveRadioToolHandoff({abortScope:t="all"}={}){const n=Symbol("radio-tool-handoff-reservation");return this.radioToolHandoffReservations.set(n,{abortScope:t}),this.freezeRadioHandoffForReservation({abortScope:t}),n}settleRadioToolHandoffReservation(t,{commit:n=!1,responseId:i=null}={}){const o=this.radioToolHandoffReservations.get(t);if(o){if(this.radioToolHandoffReservations.delete(t),n){this.radioHandoffDeferredByReservation=!1,this.abortRadioSiblingTools({scope:o.abortScope}),this.cancelRadioHandoff({responseId:i});return}this.resumeDeferredRadioHandoffIfUnreserved()}}resumeDeferredRadioHandoffIfUnreserved(){this.isRadioHandoffReserved()||!this.radioHandoffDeferredByReservation||(this.radioHandoffDeferredByReservation=!1,this.startPendingRadioHandoff())}async startPendingRadioHandoff(){var a,c,l,u;if(!this.pendingRadioPlaybackResult||this.isRadioHandoffReserved()||this.radioHandoffInFlight)return;const t=this.pendingRadioPlaybackResult;this.pendingRadioPlaybackResult=null;const n=++this.radioHandoffEpoch,i=`voice-radio-${this.sessionId}-${n}`,o=this.dc;this.radioHandoffInFlight=!0,this.radioHandoffAttemptId=i,this.radioHandoffInFlightResult=t,(c=(a=this.radioLayer)==null?void 0:a.setVoiceDucked)==null||c.call(a,!0);const r=await W7(t,{prepareRadio:()=>{var h,d;return(d=(h=this.radioLayer)==null?void 0:h.playForVoice)==null?void 0:d.call(h,{attemptId:i})},stopVoice:()=>this.stop({preserveRadioPlayback:!0}),cancelRadio:()=>{var h,d;return(d=(h=this.radioLayer)==null?void 0:h.stopPlayback)==null?void 0:d.call(h,{origin:"voice-cleanup",attemptId:i})},isCurrent:()=>this.radioHandoffInFlight&&!this.isRadioHandoffReserved()&&n===this.radioHandoffEpoch&&!this.userTurnPending&&this.dc===o&&(o==null?void 0:o.readyState)==="open"}),s=n===this.radioHandoffEpoch;this.radioHandoffAttemptId===i&&(this.radioHandoffInFlight=!1,this.radioHandoffAttemptId=null,this.radioHandoffInFlightResult===t&&(this.radioHandoffInFlightResult=null)),this.debugLog("tool.radio_handoff",{result:r.result}),!((l=r.result)!=null&&l.ok||r.cancelled||!s)&&((u=this.dc)==null?void 0:u.readyState)==="open"&&!this.userTurnPending&&(this.setStatus("listening","Radio did not start"),this.queueResponseCreate("Say exactly one short correction: “The Radio station could not start. Voice is still on.”"))}abortRadioSiblingTools({responseId:t=null,scope:n="all"}={}){for(const[i,o]of this.activeRadioToolControllers)t&&o.responseId!==t||n==="playback"&&o.authorityDomain!=="playback"||(i.abort(),this.activeRadioToolControllers.delete(i))}cancelRadioHandoff({abortTools:t=!1,responseId:n=null,abortRadioSiblings:i=!1}={}){var s,a;if(this.radioHandoffEpoch++,this.radioHandoffCancellation={epoch:this.radioHandoffEpoch,responseId:n||null},t){for(const c of this.activeToolAbortControllers)c.abort();this.activeToolAbortControllers.clear(),this.activeRadioToolControllers.clear()}else i&&this.abortRadioSiblingTools();this.pendingRadioPlaybackResult=null,this.radioHandoffInFlightResult=null,this.radioToolHandoffReservations.clear(),this.radioHandoffDeferredByReservation=!1;const o=this.radioHandoffInFlight,r=this.radioHandoffAttemptId;this.radioHandoffInFlight=!1,this.radioHandoffAttemptId=null,o&&((a=(s=this.radioLayer)==null?void 0:s.stopPlayback)==null||a.call(s,{origin:"voice-cleanup",attemptId:r}))}sendRealtimeEvent(t,n="client.event"){if(!this.dc||this.dc.readyState!=="open")return!1;this.debugLog(n,{type:(t==null?void 0:t.type)||null,message:t});try{return this.dc.send(JSON.stringify(t)),!0}catch(i){return this.debugLog("client.send.failed",{logEventName:n,type:(t==null?void 0:t.type)||null,error:(i==null?void 0:i.message)||String(i)}),!1}}reportError(t,n=null,i={}){const o=dY(t,n,i);return this.errors.unshift(o),this.errors.length=Math.min(this.errors.length,cp),pY(this.errors),console.error("[GEV Realtime]",o),this.debugLog("error",o),this.setStatus("error",hY(o)),o}connectionDiagnostics(t=this.dc){var n,i,o,r,s,a,c;return{dataChannelState:(t==null?void 0:t.readyState)||null,connectionState:((n=this.pc)==null?void 0:n.connectionState)||null,iceConnectionState:((i=this.pc)==null?void 0:i.iceConnectionState)||null,iceGatheringState:((o=this.pc)==null?void 0:o.iceGatheringState)||null,signalingState:((r=this.pc)==null?void 0:r.signalingState)||null,sctpState:((c=(a=(s=this.pc)==null?void 0:s.sctp)==null?void 0:a.transport)==null?void 0:c.state)||null}}getDiagnostics(){return{status:this.status,connection:this.connectionDiagnostics(),recentErrors:this.errors.slice(),debugLog:this.debugSink?{endpoint:bf,file:".gev-logs/realtime-conversations.jsonl",sessionId:this.sessionId}:null,cost:this.costTracker.state()}}pruneProcessedCalls(){const t=performance.now()-V7;for(const[n,i]of this.processedCalls)in.stop())}catch{}if(t)try{t.close()}catch{}}function tY(e){try{const t=JSON.stringify(e);if(navigator.sendBeacon){const n=new Blob([t],{type:"application/json"});if(navigator.sendBeacon(bf,n))return}fetch(bf,{method:"POST",headers:{"Content-Type":"application/json"},body:t,keepalive:t.length<6e4}).catch(()=>{})}catch{}}function Cf(e,t=0){if(t>10)return"[MaxDepth]";if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string")return nY(e);if(Array.isArray(e))return e.map(i=>Cf(i,t+1));if(typeof e!="object")return String(e);const n={};for(const[i,o]of Object.entries(e)){if(iY(i)){n[i]="[Redacted]";continue}n[i]=Cf(o,t+1)}return n}function nY(e){if(e.startsWith("data:image/"))return`[Redacted image data URL, ${e.length} chars]`;const t=e.replace(/sk-(?:proj-)?[A-Za-z0-9_-]{20,}/g,"[Redacted OpenAI API key]").replace(/Bearer\s+[A-Za-z0-9._~+/-]+=*/gi,"Bearer [Redacted]").replace(/"client_secret"\s*:\s*"[^"]+"/gi,'"client_secret":"[Redacted]"').replace(/"value"\s*:\s*"ek_[^"]+"/gi,'"value":"[Redacted ephemeral key]"'),n=5e4;return t.length>n?`${t.slice(0,n)}...[Truncated ${t.length-n} chars]`:t}function iY(e){return/(?:api[_-]?key|authorization|bearer|client[_-]?secret|token|secret|password)/i.test(e)}async function oY(){var a,c;const e=(a=window.__godsEyeView)==null?void 0:a.viewer,t=((c=e==null?void 0:e.scene)==null?void 0:c.canvas)||document.querySelector("#cesiumContainer .cesium-widget canvas");if(!t||!t.width||!t.height||!await sY(e))return null;const{width:i,height:o}=rY(t.width,t.height,$7),r=document.createElement("canvas");r.width=i,r.height=o;const s=r.getContext("2d");if(!s)return null;try{if(s.drawImage(t,0,0,i,o),aY(s,i,o))return console.warn("[GEV Voice] Skipped black Cesium viewport capture"),null;const l=r.toDataURL("image/jpeg",.74);return SC(l)>RC?(console.warn("[GEV Voice] Skipped oversized viewport capture",{bytes:SC(l),limit:RC}),null):l}catch{return null}}function rY(e,t,n){const i=Math.max(1,Math.floor(e)||0),o=Math.max(1,Math.floor(t)||0),r=Math.max(1,n);if(i*o<=r)return{width:i,height:o};const s=Math.sqrt(r/(i*o));return{width:Math.max(1,Math.floor(i*s)),height:Math.max(1,Math.floor(o*s))}}function SC(e){if(typeof e!="string")return 0;const t=e.indexOf(","),n=t>=0?e.slice(t+1):e,i=n.endsWith("==")?2:n.endsWith("=")?1:0;return Math.max(0,Math.floor(n.length*3/4)-i)}async function sY(e){var n;const t=e==null?void 0:e.scene;if(!t||typeof document<"u"&&document.hidden)return!1;try{const i=new Promise(r=>{const s=t.postRender.addEventListener(()=>{s(),r(!0)});setTimeout(()=>{s(),r(!1)},400)});(n=t.requestRender)==null||n.call(t);const o=await i;return typeof document<"u"&&document.hidden?!1:o}catch{return!1}}function aY(e,t,n){const i=Math.min(48,t),o=Math.min(32,n);if(!i||!o)return!0;const r=document.createElement("canvas");r.width=i,r.height=o;const s=r.getContext("2d",{willReadFrequently:!0});if(!s)return!1;s.drawImage(e.canvas,0,0,i,o);const a=s.getImageData(0,0,i,o).data;let c=0,l=0;for(let u=0;ui==null?void 0:i.name)}function cY(e,t=null){var o;if(!e||e.type!=="error")return!1;const n=e.event_id;return n&&t&&t.has(n)?!0:((o=e.error)==null?void 0:o.code)==="item_not_found"}function NC(e){return[e.call_id?`call:${e.call_id}`:"",e.id?`item:${e.id}`:""].filter(Boolean)}function uY(e){if(!e)return{};if(typeof e=="object")return e;try{return JSON.parse(e)}catch{return{}}}function dY(e,t,n={}){const i=(t==null?void 0:t.error)||t;return{timestamp:new Date().toISOString(),source:e,name:(i==null?void 0:i.name)||null,message:(i==null?void 0:i.message)||n.errorText||String((t==null?void 0:t.message)||"").trim()||"No browser error message supplied",errorDetail:(i==null?void 0:i.errorDetail)||null,sctpCauseCode:(i==null?void 0:i.sctpCauseCode)??null,receivedAlert:(i==null?void 0:i.receivedAlert)??null,sentAlert:(i==null?void 0:i.sentAlert)??null,...fY(n)}}function hY(e){const t=[e.source,e.message].filter(Boolean).join(": "),n=[e.errorDetail&&`detail=${e.errorDetail}`,e.code&&`code=${e.code}`,e.sctpCauseCode!=null&&`sctp=${e.sctpCauseCode}`,e.connectionState&&`pc=${e.connectionState}`,e.iceConnectionState&&`ice=${e.iceConnectionState}`,e.dataChannelState&&`dc=${e.dataChannelState}`].filter(Boolean).join(" | ");return n?`${t} +${n}`:t}function fY(e){return Object.fromEntries(Object.entries(e||{}).filter(([,t])=>t!=null&&t!==""))}function mY(){try{const e=JSON.parse(localStorage.getItem(nk)||"[]");return Array.isArray(e)?e.slice(0,cp):[]}catch{return[]}}function pY(e){try{localStorage.setItem(nk,JSON.stringify(e.slice(0,cp)))}catch{}}function rk(e){return(e==null?void 0:e.code)==="Space"||(e==null?void 0:e.key)===" "}const sk=["button","input","textarea","select","option","a[href]","summary","audio[controls]","video[controls]","[contenteditable]","[tabindex]",'[role="button"]','[role="checkbox"]','[role="combobox"]','[role="link"]','[role="listbox"]','[role="menuitem"]','[role="menuitemcheckbox"]','[role="menuitemradio"]','[role="option"]','[role="radio"]','[role="searchbox"]','[role="slider"]','[role="spinbutton"]','[role="switch"]','[role="tab"]','[role="textbox"]','[role="treeitem"]'].join(", ");function gY(e){var t,n,i;return((n=(t=e==null?void 0:e.tagName)==null?void 0:t.toUpperCase)==null?void 0:n.call(t))!=="CANVAS"?!1:e.id==="world-overlay-canvas"?!0:!!((i=e.closest)!=null&&i.call(e,"#cesiumContainer"))}function DC(e){var t;return!e||gY(e)?!1:e.isContentEditable?!0:!!((t=e.closest)!=null&&t.call(e,sk))}function _Y(e){var i,o,r;if(!e)return!1;if(e.isContentEditable||(i=e.closest)!=null&&i.call(e,"[contenteditable]")||(o=e.closest)!=null&&o.call(e,'textarea, [role="textbox"], [role="searchbox"], [role="spinbutton"]'))return!0;const t=(r=e.closest)==null?void 0:r.call(e,"input");if(!t)return!1;const n=String(t.type||"text").toLowerCase();return["text","search","email","url","tel","password","number","date","datetime-local","month","week","time"].includes(n)}function bY(e){return!rk(e)||e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey?!1:!_Y(e.target)}function CY(e,t,n){const i=e==="ai"?n:t;return i!=null&&i.analyser&&(i!=null&&i.data)?i:null}function yY(e,t,n=!1){return n&&e==="ai"?"ai":t==="user"||t==="ai"?t:"idle"}function vY(e,t){return e&&t?"Release Space to send":"Hold Space to speak · tap Space to activate focused controls"}function MY(e,t){const n=Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,i=Number.isFinite(t)?Math.min(.95,Math.max(0,t)):0;return n<=i?0:(n-i)/(1-i)}function OC(e){if(e)for(const t of e)t.style.removeProperty("--audio-level"),t.style.removeProperty("--audio-opacity")}function wY({emit:e,runAction:t,createController:n=o=>new X7(o),...i}){const o=n({...i,actionExecutor:t,onSessionEvent:e});return{controller:o,capabilities:{costControls:!0,pushToTalk:!0},start:r=>o.start(r),stop:r=>o.stop(r),sendText:r=>o.sendTextCommand(r),sendMapEvent:r=>o.notifyMapEvent(r),ignoreButtonClick:()=>!!o.spaceKeyHeld,bindControls(){o.ui.tierButton&&(o.tierHandler=()=>o.toggleVoiceTier(),o.ui.tierButton.addEventListener("click",o.tierHandler)),o.syncCostUi(),o.bindPushToTalkShortcut()}}}function EY(e){return P7({createSession:wY,...e})}function TY(e){return EY({...e,runner:kq(e)})}function kY({scene:e,controls:t,data:n,loadingScreen:i,placeSearch:o,voice:r={},startChrome:s,onSceneDirector:a,signal:c,defer:l}){const{viewer:u,tileset:h,mapStackController:d,operations:f}=e,{styleManager:p,weatherEffects:g,cockpitCloudEffects:_}=t,{dataManager:m}=n,b=new S9(u,p,m);l(()=>b.destroy()),a==null||a(b);const C=E7({viewer:u,tileset:h,placeSearch:o,resolver:f.annotationResolver});l(()=>{window.__gevAnnotations===C&&delete window.__gevAnnotations,C.destroy()});const y=A7({viewer:u,annotations:C});l(()=>y==null?void 0:y.destroy()),s&&l(s({loadingScreen:i,styleManager:p,dataManager:m,signal:c})),Wy(u),GW(u),l(()=>YW());const v=u.trackedEntityChanged.addEventListener(()=>{u.trackedEntity?ii("tracked-entity"):Vi("tracked-entity")}),M=()=>{var T;const k=document.hidden;u.useDefaultRenderLoop=!k,(T=_==null?void 0:_.setSuspended)==null||T.call(_,k),k||(n.presentation.flushVisible(),qt("visibility-restore"))};document.addEventListener("visibilitychange",M),l(()=>document.removeEventListener("visibilitychange",M)),l(()=>{v(),Vi("tracked-entity")}),M(),window.__godsEyeView={viewer:u,styleManager:p,tileset:h,dataManager:m,sceneDirector:b,mapStackController:d,annotations:C,weatherEffects:g,cockpitCloudEffects:_,getRenderGovernorDiagnostics:Ky,surfaceServices:f.surface,requestRender:qt};const w=window.__godsEyeView;l(()=>{window.__godsEyeView===w&&delete window.__godsEyeView});const E=TY({...r,floorServices:f.surface.groundFloor,annotationResolver:f.annotationResolver,searchNavigation:f.searchAndFlyTo,signal:c,placeSearch:o,viewer:u,styleManager:p,dataManager:m,sceneDirector:b,annotations:C});return l(()=>{E.stop({removeUi:!0}),window.__gevVoiceCommands===E&&delete window.__gevVoiceCommands}),w.voiceCommands=E,{sceneDirector:b,annotations:C,voiceCommands:E}}function ak({root:e,documentRef:t=e.ownerDocument,isActive:n,onEscape:i,fallbackFocus:o}){let r=!1,s=!1,a=null;const c=d=>{if(!r||s||!n()||d.defaultPrevented)return;if(d.key==="Escape"){d.preventDefault(),d.stopPropagation(),i();return}if(d.key!=="Tab")return;const f=[...e.querySelectorAll('button, input, [href], [tabindex]:not([tabindex="-1"])')].filter(m=>!m.hasAttribute("disabled")&&m.getClientRects().length>0);if(!f.length)return;const p=f[0],g=f[f.length-1],_=t.activeElement;e.contains(_)?d.shiftKey&&_===p?(d.preventDefault(),g.focus()):!d.shiftKey&&_===g&&(d.preventDefault(),p.focus()):(d.preventDefault(),(d.shiftKey?g:p).focus())},l=()=>{s||r||(r=!0,a=t.activeElement,t.addEventListener("keydown",c,!0))},u=({restoreFocus:d=!1}={})=>{var p,g;if(!r)return;r=!1,t.removeEventListener("keydown",c,!0);const f=a;a=null,d&&(typeof(f==null?void 0:f.focus)=="function"&&f.isConnected?f.focus({preventScroll:!0}):(g=(p=o==null?void 0:o())==null?void 0:p.focus)==null||g.call(p,{preventScroll:!0}))};return{activate:l,deactivate:u,destroy:()=>{s||(s=!0,u())}}}const yf="gev:first-run-mission:v1",lk="gev:first-run-mission-session:v1",AY="ENVIRONMENTAL",BC=Object.freeze({ENVIRONMENTAL:Object.freeze({title:"ENVIRONMENTAL"}),EARTH_WATCH:Object.freeze({title:"EARTH WATCH"}),ACTIVE_EVENTS:Object.freeze({title:"ACTIVE EVENTS"})});function IY(e=AY){return BC[e]||BC.ENVIRONMENTAL}const vf=Object.freeze({contacts:Object.freeze({kind:"context",contextMode:"contacts",busyText:"Starting live contacts…"}),"space-missions":Object.freeze({kind:"context",contextMode:"space-missions",busyText:"Opening space missions…"}),environmental:Object.freeze({kind:"globe",layerIds:Object.freeze(["earthquakes","local-firms"]),busyText:"Scanning active events…"}),explore:Object.freeze({kind:"none"})});function up(e,t){if(t!==void 0)return t;try{return e==="session"?globalThis.sessionStorage:globalThis.localStorage}catch{return null}}function VC(e,t,n){var i,o;try{return((o=(i=up(e,t))==null?void 0:i.getItem)==null?void 0:o.call(i,n))??null}catch{return null}}function ck(e,t,n,i){try{const o=up(e,t);return typeof(o==null?void 0:o.setItem)!="function"?!1:(o.setItem(n,i),!0)}catch{return!1}}function RY(e,t,n){try{const i=up(e,t);return typeof(i==null?void 0:i.removeItem)!="function"?!1:(i.removeItem(n),!0)}catch{return!1}}function LY({hasShareState:e=!1,storage:t,sessionStorageRef:n,location:i=globalThis.location}={}){if(e)return!1;const o=new URLSearchParams((i==null?void 0:i.search)||"");return o.get("welcome")==="0"?!1:o.get("welcome")==="1"?!0:!(VC("local",t,yf)==="suppressed"||VC("session",n,lk)==="dismissed")}function PY(e,t){return e?ck("local",t,yf,"suppressed"):RY("local",t,yf)}function xY(e){ck("session",e,lk,"dismissed")}async function FY(e,{setContextMode:t,setLayerEnabled:n,flyToGlobe:i}){const o=vf[e];if(!o)return{ok:!1,choice:e};if(o.kind==="none")return{ok:!0,choice:e};if(o.kind==="context"){const c=await t(o.contextMode);return{ok:!!(c!=null&&c.ok),choice:e,result:c}}const r=Promise.resolve().then(()=>i()).catch(()=>null),s=await Promise.all(o.layerIds.map(async c=>{try{return{layerId:c,ok:await n(c)!==!1}}catch{return{layerId:c,ok:!1}}}));await r;const a=s.filter(c=>!c.ok).map(c=>c.layerId);return{ok:a.length===0,choice:e,failedLayerIds:a}}const SY=Object.freeze(["cockpit-mode","scene-playback-mode","recording-mode","ui-clean-view"]);function NY(e=globalThis.document){var n;const t=(n=e==null?void 0:e.body)==null?void 0:n.classList;return t?SY.some(i=>t.contains(i)):!1}function DY({styleManager:e,dataManager:t=e==null?void 0:e._dataManager,documentRef:n=globalThis.document,storage:i,sessionStorageRef:o,location:r=globalThis.location}={}){var A,L;const s=(A=n==null?void 0:n.getElementById)==null?void 0:A.call(n,"first-run-launcher");if(!s||s.dataset.initialized==="true")return null;if(s.dataset.initialized="true",!LY({hasShareState:e==null?void 0:e.hasShareState,storage:i,sessionStorageRef:o,location:r}))return s.remove(),null;const a=s.querySelector("[data-first-run-environmental-title]");a&&(a.textContent=IY().title);const c=s.querySelector("[data-first-run-status]"),l=s.querySelector("[data-first-run-suppress]"),u=[...s.querySelectorAll("[data-first-run-choice]")],h=(c==null?void 0:c.textContent)||"";let d=!1,f=!1;const p=()=>{if(typeof n.elementFromPoint!="function")return!1;const F=s.getBoundingClientRect();if(!(F.width>0&&F.height>0))return!1;try{const P=n.elementFromPoint(F.left+F.width/2,F.top+F.height/2);return!!P&&!s.contains(P)}catch{return!1}},g=()=>s.isConnected&&s.classList.contains("visible")&&s.getClientRects().length>0&&!p(),_=({restoreFocus:F=!0}={})=>{var O,D;if(f)return;f=!0,xY(o),s.classList.remove("visible"),s.setAttribute("aria-hidden","true"),(O=globalThis.removeEventListener)==null||O.call(globalThis,"resize",I),R==null||R.disconnect();const P=()=>s.remove();s.addEventListener("transitionend",P,{once:!0}),(D=globalThis.setTimeout)==null||D.call(globalThis,P,400),y.deactivate({restoreFocus:F})},m=(F,P="")=>{var O;d=F,s.dataset.state=F?"loading":"ready",s.setAttribute("aria-busy",String(F));for(const D of u)D.setAttribute("aria-disabled",String(F));c&&(F?c.textContent=((O=vf[P])==null?void 0:O.busyText)||"Working…":c.dataset.sticky!=="true"&&(c.textContent=h))},b=async F=>{var x,N,G,W;if(d||f)return;const P=(N=(x=F.currentTarget)==null?void 0:x.dataset)==null?void 0:N.firstRunChoice;if(!vf[P])return;c&&delete c.dataset.sticky,m(!0,P);let O=null;try{O=await FY(P,{setContextMode:async V=>{var B;const H=await e.setContextMode(V);return H!=null&&H.ok&&((B=e.setPanelCollapsed)==null||B.call(e,"global-context-panel",!1,{explicit:!0})),H},setLayerEnabled:V=>t.setEnabled(V,!0,{origin:"user"}),flyToGlobe:()=>e.resetToGlobeView()})}catch(V){console.warn("[First run] Mission launch failed:",V)}if(f)return;if(O!=null&&O.ok){_();return}const D=(G=O==null?void 0:O.failedLayerIds)!=null&&G.length?O.failedLayerIds:(W=O==null?void 0:O.result)==null?void 0:W.failedLayerIds,$=Array.isArray(D)&&D.length?` (${D.join(", ")})`:"";c&&(c.dataset.sticky="true",c.textContent=`Could not open that mission${$}. Retry or explore manually.`),m(!1)},C=F=>{const P=F.currentTarget,O=!!(P!=null&&P.checked);PY(O,i)||(P&&(P.checked=!O),c&&(c.dataset.sticky="true",c.textContent="This browser is blocking storage, so that could not be saved."))},y=ak({root:s,documentRef:n,isActive:()=>!f&&g(),onEscape:()=>_(),fallbackFocus:()=>n.body});for(const F of u)F.addEventListener("click",b);l==null||l.addEventListener("change",C),y.activate();const v=s.querySelector(".first-run-choices"),M=()=>{if(!v)return;const F=v.scrollHeight>v.clientHeight+1;v.dataset.scrollable=String(F)};let w=!1;const E=()=>{var F;w||f||(w=!0,s.hidden=!1,(F=globalThis.requestAnimationFrame)==null||F.call(globalThis,()=>{var P,O;f||(s.classList.add("visible"),M(),(O=(P=u[0])==null?void 0:P.focus)==null||O.call(P,{preventScroll:!0}))}))},k=()=>{f||_({restoreFocus:!1})},T=()=>{if(f)return;const F=NY(n);w&&F?k():!w&&!F&&E()},I=()=>M();(L=globalThis.addEventListener)==null||L.call(globalThis,"resize",I);const R=typeof globalThis.MutationObserver=="function"?new globalThis.MutationObserver(T):null;return n.body&&(R==null||R.observe(n.body,{attributes:!0,attributeFilter:["class"]})),T(),{dismiss:_,isTopmost:g,destroy:()=>{var F;f=!0,y.destroy(),(F=globalThis.removeEventListener)==null||F.call(globalThis,"resize",I),R==null||R.disconnect(),s.remove()}}}function OY({loadingScreen:e,styleManager:t,dataManager:n,signal:i,initializeWelcome:o=DY,initializeSettings:r}){let s=!1,a,c,l;const u=new Promise(p=>{l=p}),h=setTimeout(l,1e3),d=()=>{s||i.aborted||a||(a=o==null?void 0:o({styleManager:t,dataManager:n}),clearTimeout(c),e.removeEventListener("transitionend",d))};Promise.all([t.initialRestorePromise,u]).catch(()=>{}).then(()=>{s||i.aborted||(e.classList.add("hidden"),e.addEventListener("transitionend",d,{once:!0}),c=setTimeout(d,900))});const f=Promise.resolve(i.aborted?null:r==null?void 0:r({signal:i}));return f.catch(()=>console.error("Provider settings initialization failed")),async()=>{var p;s=!0,clearTimeout(h),clearTimeout(c),l(),e.removeEventListener("transitionend",d),a==null||a.destroy(),(p=await f.catch(()=>null))==null||p.destroy()}}function BY(e){const t=Math.max(0,((e==null?void 0:e.total)||0)-((e==null?void 0:e.setCount)||0));return t>0?`POWER UP · ${t} ${t===1?"KEY":"KEYS"} WAITING`:"POWERED UP"}function VY(e){const t={};for(const n of e||[]){const i=String((n==null?void 0:n.value)??"").trim();i&&(n!=null&&n.envVar)&&(t[n.envVar]=i)}return t}function HY(e){if(!e)return null;try{const t=new URLSearchParams(e);return["osm","esri-imagery"].includes(t.get("map"))?(t.delete("map"),t.toString()):null}catch{return null}}const $Y=Object.freeze({metered:"🔴",free:"🟡"});function GY(e,t){const n=e.createElement("section");n.className="key-setup-row",n.dataset.keyId=t.id,n.dataset.set=String(!!t.set),t.managed&&(n.dataset.managed=t.managed);const i=t.managed==="external",o=e.createElement("div");o.className="key-setup-row-head";const r=e.createElement("span");r.className="key-setup-led",r.setAttribute("aria-hidden","true");const s=e.createElement("strong");s.textContent=t.title;const a=e.createElement("span");if(a.className="key-setup-tier",a.textContent=$Y[t.tier]||"",a.title=t.tier==="metered"?"Metered — a billing-enabled account":"Free key — register, paste, done",o.append(r,s,a),t.clientExposed){const u=e.createElement("span");u.className="key-setup-exposed",u.textContent="browser-side",u.title="This key runs in the browser by design — restrict it at the provider (see SECURITY.md)",o.append(u)}if(i){const u=e.createElement("span");u.className="key-setup-external",u.textContent="configured externally",u.title="Supplied by your environment, Keychain, or launcher — change it where it was set",o.append(u)}const c=e.createElement("a");c.className="key-setup-get",c.href=t.getUrl,c.target="_blank",c.rel="noopener noreferrer",c.textContent=t.set?"MANAGE ↗":"GET KEY ↗",o.append(c);const l=e.createElement("p");if(l.className="key-setup-unlocks",l.textContent=t.unlocks,n.append(o,l),!i){const u=e.createElement("div");u.className="key-setup-fields";for(const h of t.envVars){const d=e.createElement("input");d.type="password",d.autocomplete="off",d.spellcheck=!1,d.dataset.envVar=h,d.setAttribute("aria-label",h),d.placeholder=t.set?`${h} saved — paste to replace`:`paste ${h}`,u.append(d)}if(t.managed==="file"){const h=e.createElement("button");h.type="button",h.className="key-setup-remove",h.dataset.keySetupRemove=JSON.stringify(t.envVars),h.textContent="REMOVE",h.title=`Remove ${t.title} from this app's saved keys`,u.append(h)}n.append(u)}return n}async function UY({documentRef:e=globalThis.document,fetchImpl:t,signal:n}={}){var R,S,A,L;const i=(R=e==null?void 0:e.getElementById)==null?void 0:R.call(e,"key-setup-chip"),o=(S=e==null?void 0:e.getElementById)==null?void 0:S.call(e,"key-setup");if(!i||!o||o.dataset.initialized==="true")return null;o.dataset.initialized="true";const r=new AbortController;let s=!1,a=()=>{};const c=()=>{s||(s=!0,r.abort(),n==null||n.removeEventListener("abort",c),a(),i.remove(),o.remove())};if(n!=null&&n.aborted)return c(),null;n==null||n.addEventListener("abort",c,{once:!0});const l=t||((A=globalThis.fetch)==null?void 0:A.bind(globalThis));let u=null;try{const F=await l("/api/setup/status",{cache:"no-store",signal:r.signal});if(!F.ok)throw new Error(String(F.status));if(u=await F.json(),s)return null}catch{return c(),null}const h=o.querySelector("[data-key-setup-rows]"),d=o.querySelector("[data-key-setup-apply]"),f=o.querySelector("[data-key-setup-close]"),p=i.querySelector("[data-key-setup-chip-label]")||i,g=o.querySelector("[data-key-setup-status]"),_=(g==null?void 0:g.textContent)||"";let m=!1,b=!1;const C=F=>{if(!s&&(u=F,p.textContent=BY(u),i.hidden=u.setCount>=u.total,!!h)){h.textContent="";for(const P of u.keys||[])h.append(GY(e,P))}},y=()=>o.isConnected&&o.classList.contains("visible")&&o.getClientRects().length>0,v=ak({root:o,documentRef:e,isActive:()=>b&&y(),onEscape:()=>w()}),M=()=>{var F;s||b||(b=!0,v.activate(),o.hidden=!1,(F=globalThis.requestAnimationFrame)==null||F.call(globalThis,()=>{var P,O;b&&(o.classList.add("visible"),(O=(P=o.querySelector("input"))==null?void 0:P.focus)==null||O.call(P,{preventScroll:!0}))}))},w=()=>{var P;if(!b)return;b=!1,o.classList.remove("visible");const F=()=>{b||(o.hidden=!0)};o.addEventListener("transitionend",F,{once:!0}),(P=globalThis.setTimeout)==null||P.call(globalThis,F,400),g&&(g.textContent=_),v.deactivate({restoreFocus:!0})},E=F=>{g&&(g.textContent=F)},k=()=>(u==null?void 0:u.store)==="pinokio-environment"?"your app configuration":"your local .env",T=async(F,P)=>{var D,$,x,N;if(s||m)return;const O=!(($=(D=u==null?void 0:u.keys)==null?void 0:D.find(G=>G.id==="google-maps"))!=null&&$.set);m=!0,d==null||d.setAttribute("aria-disabled","true"),E("Saving…");try{const G=await l("/api/setup/keys",{method:"POST",signal:r.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify(F)}),W=await G.json().catch(()=>({}));if(s)return;if(!G.ok||!W.ok){E(W.error||`Save failed (${G.status}).`);return}for(const V of o.querySelectorAll("input[data-env-var]"))V.value="";if(C(W.status),O&&((x=W.saved)!=null&&x.includes("GOOGLE_MAPS_API_KEY"))){const V=()=>{var H,B,q,z;try{const j=HY(((B=(H=globalThis.location)==null?void 0:H.hash)==null?void 0:B.slice(1))||"");j!==null&&((z=(q=globalThis.history)==null?void 0:q.replaceState)==null||z.call(q,null,"",`#${j}`))}catch{}};V(),(N=globalThis.addEventListener)==null||N.call(globalThis,"pagehide",V,{once:!0,signal:r.signal})}E(`${P} ${k()}. Restarting — this page reloads itself.`)}catch(G){E(`Save failed: ${(G==null?void 0:G.message)||G}`)}finally{m=!1,d==null||d.setAttribute("aria-disabled","false")}},I=async()=>{if(s||m)return;const F=[...o.querySelectorAll("input[data-env-var]")],P=VY(F.map(O=>({envVar:O.dataset.envVar,value:O.value})));if(!Object.keys(P).length){E("Paste at least one key first.");return}await T(P,"Saved to")};i.addEventListener("click",M),f==null||f.addEventListener("click",w),d==null||d.addEventListener("click",I),h==null||h.addEventListener("click",F=>{var $,x;const P=(x=($=F.target)==null?void 0:$.closest)==null?void 0:x.call($,"[data-key-setup-remove]");if(s||!P||m)return;let O=[];try{O=JSON.parse(P.dataset.keySetupRemove||"[]")}catch{return}!Array.isArray(O)||!O.length||!(typeof globalThis.confirm!="function"||globalThis.confirm("Remove this key from your saved configuration?"))||T(Object.fromEntries(O.map(N=>[N,null])),"Removed from")}),C(u);try{new URLSearchParams(((L=globalThis.location)==null?void 0:L.search)||"").get("setup")==="1"&&M()}catch{}return a=()=>{b=!1,v.destroy(),i.removeEventListener("click",M),f==null||f.removeEventListener("click",w),d==null||d.removeEventListener("click",I)},{open:M,close:w,render:C,destroy:c}}function zY(e){return OY({initializeSettings:UY,...e})}function jY(e){return kY({startChrome:zY,...e})}let HC=!1;function qY({googleApiKey:e,cesiumToken:t,geospatial:n={},voice:i={},allowQaRegistration:o=!1}){if(HC)throw new Error("The standalone application already owns this page");HC=!0;const r=document.getElementById("loading-screen"),s=r.querySelector(".loader-status");let a,c;return zU({createScene:async l=>{a=PM({presets:Ot,...n,resolveApiKey:()=>e,signal:l.signal});const u=await gz({...l,googleApiKey:e,cesiumToken:t,loaderStatus:s});return c=GE({signal:l.signal,surface:u.operations.surface}),u},createControls:l=>h9({...l,loaderStatus:s,placeSearch:a,catalog:c}),createData:l=>C9({...l,allowQaRegistration:o,catalog:c}),createTools:l=>jY({...l,loadingScreen:r,placeSearch:a,voice:i})})}const WY=qY({googleApiKey:void 0,cesiumToken:void 0,allowQaRegistration:!1});WY.start().catch(e=>{console.error("God's Eye View initialization failed:",e);const t=document.querySelector("#loading-screen .loader-status");t.textContent=`Error: ${zE(e)}`,t.style.color="#ff4444"});