@rr0/ufoathome 0.60.1 → 0.60.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7542,4 +7542,4 @@ void main() {
7542
7542
  gl_FragColor = vec4(color, tex.a * uOpacity * (1.0 - blur * 0.5));
7543
7543
  }
7544
7544
  `;let Rl;function PT(){if(Rl)return Rl;const r=128,e=document.createElement("canvas");e.width=r,e.height=r;const t=e.getContext("2d"),n=t.createRadialGradient(r/2,r/2,0,r/2,r/2,r/2);return n.addColorStop(0,"rgba(255,255,255,1)"),n.addColorStop(.4,"rgba(255,255,255,0.35)"),n.addColorStop(1,"rgba(255,255,255,0)"),t.fillStyle=n,t.fillRect(0,0,r,r),Rl=new Ui(e),Rl}function Em(r){const t=document.createElement("canvas");t.width=128,t.height=128;const n=t.getContext("2d"),i=128/2-2,s=128/2,a=128/2,o="#2e2b26",l="#f4f1e2";n.fillStyle=o,n.beginPath(),n.arc(s,a,i,0,Math.PI*2),n.fill();const c=ro(r.illuminatedFraction,0,1),h=r.phaseFraction<.5,d=i*Math.abs(1-2*c),u=c<.5;return n.save(),n.beginPath(),n.arc(s,a,i,0,Math.PI*2),n.clip(),n.fillStyle=l,n.beginPath(),h?(n.arc(s,a,i,-Math.PI/2,Math.PI/2,!1),n.ellipse(s,a,d,i,0,Math.PI/2,-Math.PI/2,u)):(n.arc(s,a,i,Math.PI/2,-Math.PI/2,!1),n.ellipse(s,a,d,i,0,-Math.PI/2,Math.PI/2,u)),n.fill(),n.restore(),new Ui(t)}function LT(r){const e=document.createElement("canvas");e.width=128,e.height=128;const t=e.getContext("2d");return t.fillStyle="rgba(0, 0, 0, 0.55)",t.beginPath(),t.arc(64,64,60,0,Math.PI*2),t.fill(),t.fillStyle="#ffffff",t.font="bold 52px sans-serif",t.textAlign="center",t.textBaseline="middle",t.fillText(r,64,68),new Ui(e)}function Vh(r){let e=r;return function(){e|=0,e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}const Xh=7.5,ao=9;class xi{static cache=new Map;static load(e){let t=xi.cache.get(e);return t||(t=fetch(e).then(n=>n.arrayBuffer()).then(n=>xi.parse(n)),xi.cache.set(e,t)),t}static upTo(e,t){const n=e.filter((a,o)=>o===0||e[o-1].magnitudeLimit<t);if(n.length<=1)return xi.load(e[0].url);const i=n.map(a=>a.url).join(`
7545
- `);let s=xi.cache.get(i);return s||(s=Promise.all(n.map(a=>xi.load(a.url))).then(a=>a.reduce((o,l)=>xi.concat(o,l))),xi.cache.set(i,s)),s}static parse(e){const t=e.byteLength/(4*Float32Array.BYTES_PER_ELEMENT),n=t*Float32Array.BYTES_PER_ELEMENT;return{count:t,ra:new Float32Array(e,0*n,t),dec:new Float32Array(e,1*n,t),mag:new Float32Array(e,2*n,t),ci:new Float32Array(e,3*n,t)}}static concat(e,t){const n=(i,s)=>{const a=new Float32Array(i.length+s.length);return a.set(i,0),a.set(s,i.length),a};return{count:e.count+t.count,ra:n(e.ra,t.ra),dec:n(e.dec,t.dec),mag:n(e.mag,t.mag),ci:n(e.ci,t.ci)}}}const kT=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,NT=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,OT=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,FT=20,UT=1;class BT{context;buffers=new Map;ambientSource;ambientGain;ambientKey="none";ambientToken=0;ambientVolume=0;windSource;windGain;windActive=!1;windToken=0;windVolume=0;paused=!0;requested={type:"none",intensity:0,windSpeed:0};resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("WeatherAudio: Web Audio unavailable, weather sounds disabled:",e);return}}this.context.state==="suspended"&&this.context.resume()}setAmbient(e,t,n){if(this.requested={type:e,intensity:t,windSpeed:n},!this.context)return;this.paused&&(e="none",t=0,n=0);const i=e==="rain"||e==="hail"?e:"none";if(this.ambientVolume=i==="hail"?Math.min(1,t*1.3+.2):i==="rain"?t:0,i!==this.ambientKey){this.ambientKey=i;const a=++this.ambientToken;this.stopSource(this.ambientSource,this.ambientGain),this.ambientSource=void 0,this.ambientGain=void 0,i!=="none"&&this.startLoop(kT,this.ambientVolume).then(o=>this.applyIfCurrent(o,a,()=>this.ambientToken,l=>{this.ambientSource=l?.source,this.ambientGain=l?.gain,l&&(l.gain.gain.value=this.ambientVolume)}))}else this.ambientGain&&(this.ambientGain.gain.value=this.ambientVolume);this.windVolume=Math.min(n/FT,1);const s=n>UT;if(s!==this.windActive){this.windActive=s;const a=++this.windToken;this.stopSource(this.windSource,this.windGain),this.windSource=void 0,this.windGain=void 0,s&&this.startLoop(NT,this.windVolume).then(o=>this.applyIfCurrent(o,a,()=>this.windToken,l=>{this.windSource=l?.source,this.windGain=l?.gain,l&&(l.gain.gain.value=this.windVolume)}))}else this.windGain&&(this.windGain.gain.value=this.windVolume)}setPaused(e){if(e===this.paused)return;this.paused=e;const{type:t,intensity:n,windSpeed:i}=this.requested;this.setAmbient(t,n,i)}playThunder(){!this.context||this.paused||this.playOneShot(OT,.9)}dispose(){this.ambientToken++,this.windToken++,this.stopSource(this.ambientSource,this.ambientGain),this.stopSource(this.windSource,this.windGain),this.ambientSource=void 0,this.ambientGain=void 0,this.windSource=void 0,this.windGain=void 0,this.context?.close(),this.context=void 0,this.buffers.clear()}applyIfCurrent(e,t,n,i){if(t!==n()){e?.source.stop();return}i(e)}async startLoop(e,t){const n=this.context;if(n)try{const i=await this.getBuffer(e),s=n.createBufferSource();s.buffer=i,s.loop=!0;const a=n.createGain();return a.gain.value=t,s.connect(a).connect(n.destination),s.start(),{source:s,gain:a}}catch(i){console.warn("Weather ambient sound failed to load, staying silent:",i);return}}async playOneShot(e,t){const n=this.context;if(n)try{const i=await this.getBuffer(e),s=n.createBufferSource();s.buffer=i;const a=n.createGain();a.gain.value=t,s.connect(a).connect(n.destination),s.start()}catch(i){console.warn("Thunder sound failed to load:",i)}}async getBuffer(e){const t=this.context;if(!t)throw new Error("WeatherAudio: AudioContext not ready — resume() must be called first");let n=this.buffers.get(e);return n||(n=fetch(e).then(i=>{if(!i.ok)throw new Error(`Audio fetch failed (${i.status}): ${e}`);return i.arrayBuffer()}).then(i=>t.decodeAudioData(i)),this.buffers.set(e,n)),n}stopSource(e,t){try{e?.stop()}catch{}e?.disconnect(),t?.disconnect()}}class Ki{constructor(e){this.elements=e;const{eccentricity:t,perihelionAu:n}=e,[i,s]=this.perifocalAxes(),a=Math.sqrt(Ki.SUN_GM_AU3_PER_DAY2*(1+t)/n);this.perihelionPosition=this.scale(i,n),this.perihelionVelocity=this.scale(s,a),this.inverseSemiMajorAxis=(1-t)/n}static SUN_GM_AU3_PER_DAY2=.0002959122082855911;static MAX_ITERATIONS=200;perihelionPosition;perihelionVelocity;inverseSemiMajorAxis;positionAt(e){const t=e-this.elements.perihelionJd,n=this.universalAnomaly(t),i=this.inverseSemiMajorAxis*n*n,s=this.elements.perihelionAu,a=1-n*n/s*Ki.stumpffC(i),o=t-n*n*n/Math.sqrt(Ki.SUN_GM_AU3_PER_DAY2)*Ki.stumpffS(i);return{x:a*this.perihelionPosition.x+o*this.perihelionVelocity.x,y:a*this.perihelionPosition.y+o*this.perihelionVelocity.y,z:a*this.perihelionPosition.z+o*this.perihelionVelocity.z}}heliocentricDistanceAt(e){const t=this.positionAt(e);return Math.hypot(t.x,t.y,t.z)}universalAnomaly(e){if(e===0)return 0;const t=Math.sign(e),n=Math.sqrt(Ki.SUN_GM_AU3_PER_DAY2)*Math.abs(e),i=o=>{const l=this.inverseSemiMajorAxis*o*o,c=this.elements.perihelionAu;return(1-this.inverseSemiMajorAxis*c)*o*o*o*Ki.stumpffS(l)+c*o};let s=Math.max(1,n/this.elements.perihelionAu);for(;i(s)<n;)s*=2;let a=0;for(let o=0;o<Ki.MAX_ITERATIONS&&s-a>1e-13*Math.max(1,s);o++){const l=(a+s)/2;i(l)<n?a=l:s=l}return t*(a+s)/2}perifocalAxes(){const e=this.elements.ascendingNodeDeg*Math.PI/180,t=this.elements.argumentOfPerihelionDeg*Math.PI/180,n=this.elements.inclinationDeg*Math.PI/180,i=Math.cos(e),s=Math.sin(e),a=Math.cos(t),o=Math.sin(t),l=Math.cos(n),c=Math.sin(n);return[{x:i*a-s*o*l,y:s*a+i*o*l,z:o*c},{x:-i*o-s*a*l,y:-s*o+i*a*l,z:a*c}]}scale(e,t){return{x:e.x*t,y:e.y*t,z:e.z*t}}static stumpffC(e){if(Math.abs(e)<1e-6)return 1/2-e/24+e*e/720;if(e>0)return(1-Math.cos(Math.sqrt(e)))/e;const t=Math.sqrt(-e);return(Math.cosh(t)-1)/-e}static stumpffS(e){if(Math.abs(e)<1e-6)return 1/6-e/120+e*e/5040;if(e>0){const n=Math.sqrt(e);return(n-Math.sin(n))/(n*n*n)}const t=Math.sqrt(-e);return(Math.sinh(t)-t)/(t*t*t)}}const Rv=[{id:"halley-1910",designation:"1P/Halley",name:{en:"Halley's Comet",fr:"comète de Halley"},orbit:{eccentricity:.9672960498922706,perihelionAu:.5872100477652511,inclinationDeg:162.218798367122,ascendingNodeDeg:58.56208298700436,argumentOfPerihelionDeg:111.7366940639061,perihelionJd:2.4187816784171113e6},peakMagnitude:0,peakOn:"1910-05-20",absoluteMagnitude:4.72,activityExponent:4,tailLengthDeg:100,tailLengthAu:.1638,note:"Passed 0.15 au from Earth on 20 May 1910, and the Earth crossed the outer tail the day before — the apparition that produced a genuine public panic."},{id:"brooks-1911",designation:"C/1911 O1",name:{en:"Comet Brooks",fr:"comète Brooks"},orbit:{eccentricity:.9876404970138669,perihelionAu:.4898172916113738,inclinationDeg:33.34043866978714,ascendingNodeDeg:293.7022074981857,argumentOfPerihelionDeg:153.5578007321686,perihelionJd:2.4193378856140426e6},peakMagnitude:2,peakOn:"1911-10-25",absoluteMagnitude:5.59,activityExponent:4},{id:"skjellerup-maristany-1927",designation:"C/1927 X1",name:{en:"Comet Skjellerup-Maristany",fr:"comète Skjellerup-Maristany"},orbit:{eccentricity:.999839726885059,perihelionAu:.1761569619628186,inclinationDeg:85.1125991950808,ascendingNodeDeg:78.24360172472711,argumentOfPerihelionDeg:47.15877857390136,perihelionJd:2.4252326808989984e6},peakMagnitude:-6,peakOn:"1927-12-15",absoluteMagnitude:1.19,activityExponent:4,note:"One of the few comets of the century seen in full daylight."},{id:"de-kock-paraskevopoulos-1941",designation:"C/1941 B2",name:{en:"Comet de Kock-Paraskevopoulos",fr:"comète de Kock-Paraskevopoulos"},orbit:{eccentricity:.9991026715181549,perihelionAu:.7900329662827822,inclinationDeg:168.2039226531089,ascendingNodeDeg:43.10609347214336,argumentOfPerihelionDeg:268.6990344196369,perihelionJd:2430022157765061e-9},peakMagnitude:2,peakOn:"1941-02-05",absoluteMagnitude:5.01,activityExponent:4},{id:"southern-1947",designation:"C/1947 X1",name:{en:"the Southern Comet",fr:"comète australe"},orbit:{eccentricity:.9998424430916737,perihelionAu:.1100045955093761,inclinationDeg:138.5113919632757,ascendingNodeDeg:337.3114969669252,argumentOfPerihelionDeg:196.1820121395961,perihelionJd:2.4325220864727003e6},peakMagnitude:-3,peakOn:"1947-12-08",absoluteMagnitude:3.01,activityExponent:4,note:"A bright southern-hemisphere comet of December 1947, the month the American sighting wave of that year was still being argued over."},{id:"eclipse-1948",designation:"C/1948 V1",name:{en:"the Eclipse Comet",fr:"comète de l'éclipse"},orbit:{eccentricity:.9999130678247334,perihelionAu:.1354437057263306,inclinationDeg:23.11668597152911,ascendingNodeDeg:211.0454985994762,argumentOfPerihelionDeg:107.2474157073104,perihelionJd:2.4328519265329437e6},peakMagnitude:-2,peakOn:"1948-11-01",absoluteMagnitude:4.79,activityExponent:4,note:"Found during the total solar eclipse of 1 November 1948, which is how a comet that bright had gone unnoticed: it had been hidden in the Sun's glare."},{id:"arend-roland-1957",designation:"C/1956 R1",name:{en:"Comet Arend-Roland",fr:"comète Arend-Roland"},orbit:{eccentricity:1.0002570255357,perihelionAu:.3160532361485914,inclinationDeg:119.9440863251822,ascendingNodeDeg:215.8548157717755,argumentOfPerihelionDeg:308.775920364167,perihelionJd:2.4359365327396123e6},peakMagnitude:.5,peakOn:"1957-04-25",absoluteMagnitude:3.96,activityExponent:4,note:"Showed a spike pointing back TOWARD the Sun in late April 1957 — a real anti-tail, and much reported at the time."},{id:"mrkos-1957",designation:"C/1957 P1",name:{en:"Comet Mrkos",fr:"comète Mrkos"},orbit:{eccentricity:.9993521583504134,perihelionAu:.3549238508212375,inclinationDeg:93.9433042053929,ascendingNodeDeg:68.32441518619923,argumentOfPerihelionDeg:40.31823675802871,perihelionJd:243605193752228e-8},peakMagnitude:1,peakOn:"1957-08-05",absoluteMagnitude:5.07,activityExponent:4,note:"The second bright naked-eye comet of 1957, four months after Arend-Roland."},{id:"seki-lines-1962",designation:"C/1962 C1",name:{en:"Comet Seki-Lines",fr:"comète Seki-Lines"},orbit:{eccentricity:1.000003791331562,perihelionAu:.03139689112215131,inclinationDeg:65.01487186102287,ascendingNodeDeg:304.6776602796538,argumentOfPerihelionDeg:11.47295326312573,perihelionJd:2437756163010178e-9},peakMagnitude:-2.5,peakOn:"1962-04-01",absoluteMagnitude:9.3,activityExponent:4},{id:"ikeya-seki-1965",designation:"C/1965 S1",name:{en:"Comet Ikeya-Seki",fr:"comète Ikeya-Seki"},orbit:{eccentricity:.9999141178248997,perihelionAu:.007785966366889336,inclinationDeg:141.8642315267051,ascendingNodeDeg:346.9951764632611,argumentOfPerihelionDeg:69.04909813996062,perihelionJd:2.4390546837018197e6},peakMagnitude:-10,peakOn:"1965-10-21",alsoRecordedMagnitude:2,alsoRecordedOn:"1965-10-30",absoluteMagnitude:5.26,activityExponent:4.002,tailLengthDeg:25,tailLengthAu:.5048,note:"A sungrazer that passed 450 000 km above the Sun's surface and was seen beside it in broad daylight — the brightest comet of the twentieth century. It then stood in the dawn sky for a fortnight with a tail some 25 degrees long, which is the second magnitude recorded here."},{id:"bennett-1970",designation:"C/1969 Y1",name:{en:"Comet Bennett",fr:"comète Bennett"},orbit:{eccentricity:.9962979048768408,perihelionAu:.5376209981502136,inclinationDeg:90.03975717147327,ascendingNodeDeg:224.6576652531314,argumentOfPerihelionDeg:354.1494209173161,perihelionJd:2.4406655455270996e6},peakMagnitude:0,peakOn:"1970-03-26",absoluteMagnitude:3.36,activityExponent:4},{id:"white-ortiz-bolelli-1970",designation:"C/1970 K1",name:{en:"Comet White-Ortiz-Bolelli",fr:"comète White-Ortiz-Bolelli"},orbit:{eccentricity:.9999488875801225,perihelionAu:.00884411465256722,inclinationDeg:138.9520738221631,ascendingNodeDeg:336.8194095816687,argumentOfPerihelionDeg:61.10224765396615,perihelionJd:2.4407209807728203e6},peakMagnitude:1,peakOn:"1970-05-22",absoluteMagnitude:4.35,activityExponent:4},{id:"kohoutek-1973",designation:"C/1973 E1",name:{en:"Comet Kohoutek",fr:"comète Kohoutek"},orbit:{eccentricity:1.000007152175185,perihelionAu:.1424250377812859,inclinationDeg:14.30414984159355,ascendingNodeDeg:258.4893339663974,argumentOfPerihelionDeg:37.79772760699667,perihelionJd:2442044930687027e-9},peakMagnitude:0,peakOn:"1974-01-05",absoluteMagnitude:4.89,activityExponent:4,note:"Announced in advance as the comet of the century and remembered for disappointing: it was an ordinary naked-eye object, not the spectacle the press had promised."},{id:"west-1976",designation:"C/1975 V1",name:{en:"Comet West",fr:"comète West"},orbit:{eccentricity:1.000017859625611,perihelionAu:.1966006188461085,inclinationDeg:43.07319920579427,ascendingNodeDeg:118.9189245655447,argumentOfPerihelionDeg:358.4315101259072,perihelionJd:2442833721841768e-9},peakMagnitude:-3,peakOn:"1976-02-25",absoluteMagnitude:4.41,activityExponent:4,tailLengthDeg:30,tailLengthAu:.4325,note:"Broke into four pieces at perihelion. Barely reported at the time — the press had been burned by Kohoutek two years earlier."},{id:"iras-araki-alcock-1983",designation:"C/1983 H1",name:{en:"Comet IRAS-Araki-Alcock",fr:"comète IRAS-Araki-Alcock"},orbit:{eccentricity:.9898409731606003,perihelionAu:.9913412593828502,inclinationDeg:73.25000846947029,ascendingNodeDeg:49.10235754476374,argumentOfPerihelionDeg:192.8506176754439,perihelionJd:2.4454757545235856e6},peakMagnitude:1.7,peakOn:"1983-05-11",absoluteMagnitude:9.04,activityExponent:4,note:"Passed 0.031 au from Earth on 11 May 1983, one of the closest cometary approaches on record: it crossed a quarter of the sky in a night, which no other comet in this list did."},{id:"halley-1986",designation:"1P/Halley",name:{en:"Halley's Comet",fr:"comète de Halley"},orbit:{eccentricity:.9672792271749998,perihelionAu:.5871034488173393,inclinationDeg:162.2422242700916,ascendingNodeDeg:58.85993640671803,argumentOfPerihelionDeg:111.8655480539208,perihelionJd:2.4464709589610207e6},peakMagnitude:2.1,peakOn:"1986-03-10",absoluteMagnitude:2.71,activityExponent:4,note:"The worst-placed return in two thousand years — famous, expected, and for most observers a faint smudge."},{id:"hyakutake-1996",designation:"C/1996 B2",name:{en:"Comet Hyakutake",fr:"comète Hyakutake"},orbit:{eccentricity:.9997295133739305,perihelionAu:.2302272039470452,inclinationDeg:124.923592343765,ascendingNodeDeg:188.0454295899424,argumentOfPerihelionDeg:130.1724036582639,perihelionJd:2.4502048946148166e6},peakMagnitude:0,peakOn:"1996-03-25",absoluteMagnitude:4.75,activityExponent:4,tailLengthDeg:80,tailLengthAu:1,note:"Passed 0.10 au from Earth in March 1996, five weeks BEFORE perihelion, with a tail measured at some 80 degrees — the longest of the modern era."},{id:"hale-bopp-1997",designation:"C/1995 O1",name:{en:"Comet Hale-Bopp",fr:"comète Hale-Bopp"},orbit:{eccentricity:.9951314746156615,perihelionAu:.9141695067003724,inclinationDeg:89.43017155012492,ascendingNodeDeg:282.470602866853,argumentOfPerihelionDeg:130.5872524854533,perihelionJd:2450539633099368e-9},peakMagnitude:-.8,peakOn:"1997-04-01",absoluteMagnitude:-1.06,activityExponent:4,tailLengthDeg:20,tailLengthAu:.9938,note:"Visible to the naked eye for about eighteen months, longer than any comet on record."},{id:"mcnaught-2007",designation:"C/2006 P1",name:{en:"Comet McNaught",fr:"comète McNaught"},orbit:{eccentricity:1.00001811603225,perihelionAu:.1707325614080681,inclinationDeg:77.83726446452654,ascendingNodeDeg:267.4149080498975,argumentOfPerihelionDeg:155.9756130642756,perihelionJd:2454113298753579e-9},peakMagnitude:-5.5,peakOn:"2007-01-13",absoluteMagnitude:2.53,activityExponent:4,tailLengthDeg:35,tailLengthAu:.5009,note:"The brightest comet since Ikeya-Seki, seen in daylight beside the Sun in January 2007."},{id:"lovejoy-2011",designation:"C/2011 W3",name:{en:"Comet Lovejoy",fr:"comète Lovejoy"},orbit:{eccentricity:.999915056276912,perihelionAu:.005553783989325053,inclinationDeg:134.3558712062691,ascendingNodeDeg:326.3693517957772,argumentOfPerihelionDeg:53.50991655176601,perihelionJd:2455911511809431e-9},peakMagnitude:-3,peakOn:"2011-12-16",alsoRecordedMagnitude:1.5,alsoRecordedOn:"2011-12-22",absoluteMagnitude:3.51,activityExponent:1.194,note:"A sungrazer that was expected to be destroyed at perihelion and came out the other side, to stand in the southern dawn sky for the rest of December — which is the second magnitude recorded here."},{id:"panstarrs-2013",designation:"C/2011 L4",name:{en:"Comet PANSTARRS",fr:"comète PANSTARRS"},orbit:{eccentricity:1.000032542889696,perihelionAu:.301544229714915,inclinationDeg:84.2081978367921,ascendingNodeDeg:65.66588626213694,argumentOfPerihelionDeg:333.6516444379993,perihelionJd:2456361669960698e-9},peakMagnitude:1,peakOn:"2013-03-10",absoluteMagnitude:5.98,activityExponent:4},{id:"neowise-2020",designation:"C/2020 F3",name:{en:"Comet NEOWISE",fr:"comète NEOWISE"},orbit:{eccentricity:.9991782081129224,perihelionAu:.2946512466331692,inclinationDeg:128.9375043020912,ascendingNodeDeg:61.01042991771634,argumentOfPerihelionDeg:37.2786526292898,perihelionJd:2.4590341788972816e6},peakMagnitude:.9,peakOn:"2020-07-08",absoluteMagnitude:5.79,activityExponent:4,tailLengthDeg:10,tailLengthAu:.1808,note:"The first comet since Hale-Bopp that ordinary observers in the northern hemisphere saw without being told where to look."},{id:"tsuchinshan-atlas-2024",designation:"C/2023 A3",name:{en:"Comet Tsuchinshan-ATLAS",fr:"comète Tsuchinshan-ATLAS"},orbit:{eccentricity:1.000020192843226,perihelionAu:.3914228969475176,inclinationDeg:139.1105462619479,ascendingNodeDeg:21.55945689078845,argumentOfPerihelionDeg:308.4913086299446,perihelionJd:2460581242087108e-9},peakMagnitude:0,peakOn:"2024-10-14",absoluteMagnitude:3.97,activityExponent:4,tailLengthDeg:20,tailLengthAu:.1902,note:"Briefly reported far brighter around 9 October 2024, when it stood almost between the observer and the Sun and forward-scattered the light through its own dust — a geometry this catalog's brightness model does not attempt, so what is stored is the ordinary evening-sky peak a few days later."}];class ql{static WINDOW_DAYS=200;static TWILIGHT_ELONGATION_DEG=15;static LIGHT_SPEED_AU_PER_DAY=173.144632674;static orbits=new Map;static aroundDate(e){const t=this.julianDayOf(e);return Rv.filter(n=>Math.abs(t-n.orbit.perihelionJd)<=this.WINDOW_DAYS)}static brightestAt(e,t){return this.aroundDate(e).map(n=>this.appearanceOf(n,e,t)).sort((n,i)=>n.magnitude-i.magnitude)[0]}static appearanceOf(e,t,n){const i=Xt(t),s=this.earthPositionAt(i),a=this.apparentPositionOf(e,2451545+i.tt,s),o=this.subtract(a,s),l=this.length(a),c=this.length(o),h=this.tailEndAt(e,a,s,l,i,t,n),d=this.horizontalOf(o,i,t,n);return{apparition:e,position:d,...h,heliocentricDistanceAu:l,earthDistanceAu:c,elongationDeg:this.angleBetween(o,this.subtract({x:0,y:0,z:0},s)),magnitude:this.magnitudeAt(e,l,c)}}static magnitudeAt(e,t,n){const i=e.absoluteMagnitude+5*Math.log10(n)+2.5*e.activityExponent*Math.log10(t);return Math.max(i,e.peakMagnitude)}static tailEndAt(e,t,n,i,s,a,o){if(e.tailLengthAu===void 0)return{};const l=1+e.tailLengthAu/i,c=this.subtract({x:t.x*l,y:t.y*l,z:t.z*l},n),h=this.subtract(t,n);return{tailEnd:this.horizontalOf(c,s,a,o),tailLengthDeg:this.angleBetween(h,c)}}static apparentPositionOf(e,t,n){const i=this.orbitOf(e);let s=i.positionAt(t);for(let a=0;a<2;a++){const o=this.length(this.subtract(s,n))/this.LIGHT_SPEED_AU_PER_DAY;s=i.positionAt(t-o)}return s}static horizontalOf(e,t,n,i){const s=Vl(XE(),new Mt(e.x,e.y,e.z,t)),a=Vl(qE(t),s),o=SE(t,new uf(i.lat,i.lng,i.elevationM)),l=new Mt(a.x-o.x,a.y-o.y,a.z-o.z,t),c=mv(l);return Rc(c.ra,c.dec,n,i)}static earthPositionAt(e){return Vl(VE(),Rs(Me.Earth,e))}static julianDayOf(e){return 2451545+Xt(e).tt}static orbitOf(e){const t=this.orbits.get(e.id);if(t)return t;const n=new Ki(e.orbit);return this.orbits.set(e.id,n),n}static subtract(e,t){return{x:e.x-t.x,y:e.y-t.y,z:e.z-t.z}}static length(e){return Math.hypot(e.x,e.y,e.z)}static angleBetween(e,t){const n=(e.x*t.x+e.y*t.y+e.z*t.z)/(this.length(e)*this.length(t)||1);return Math.acos(Math.min(1,Math.max(-1,n)))*180/Math.PI}}const zT=[{id:"quadrantids",code:"QUA",name:{en:"Quadrantids",fr:"Quadrantides"},radiantRaHours:15.33,radiantDecDeg:49.7,start:{month:12,day:28},peak:{month:1,day:3},end:{month:1,day:12},peakZhr:110,velocityKmS:41,populationIndex:2.1},{id:"lyrids",code:"LYR",name:{en:"April Lyrids",fr:"Lyrides d'avril"},radiantRaHours:18.13,radiantDecDeg:33.3,start:{month:4,day:16},peak:{month:4,day:22},end:{month:4,day:25},peakZhr:18,velocityKmS:49,populationIndex:2.1},{id:"eta-aquariids",code:"ETA",name:{en:"eta Aquariids",fr:"Êta Aquarides"},radiantRaHours:22.53,radiantDecDeg:-1,start:{month:4,day:19},peak:{month:5,day:6},end:{month:5,day:28},peakZhr:50,velocityKmS:66,populationIndex:2.4},{id:"alpha-capricornids",code:"CAP",name:{en:"alpha Capricornids",fr:"Alpha Capricornides"},radiantRaHours:20.47,radiantDecDeg:-9.2,start:{month:7,day:3},peak:{month:7,day:30},end:{month:8,day:15},peakZhr:5,velocityKmS:23,populationIndex:2.5},{id:"southern-delta-aquariids",code:"SDA",name:{en:"Southern delta Aquariids",fr:"Delta Aquarides du Sud"},radiantRaHours:22.67,radiantDecDeg:-16.4,start:{month:7,day:12},peak:{month:7,day:30},end:{month:8,day:23},peakZhr:25,velocityKmS:41,populationIndex:3.2},{id:"perseids",code:"PER",name:{en:"Perseids",fr:"Perséides"},radiantRaHours:3.22,radiantDecDeg:58,start:{month:7,day:17},peak:{month:8,day:12},end:{month:8,day:24},peakZhr:100,velocityKmS:59,populationIndex:2.2},{id:"southern-taurids",code:"STA",name:{en:"Southern Taurids",fr:"Taurides du Sud"},radiantRaHours:3.47,radiantDecDeg:13,start:{month:9,day:10},peak:{month:10,day:10},end:{month:11,day:20},peakZhr:5,velocityKmS:27,populationIndex:2.3},{id:"draconids",code:"DRA",name:{en:"October Draconids",fr:"Draconides d'octobre"},radiantRaHours:17.47,radiantDecDeg:54,start:{month:10,day:6},peak:{month:10,day:8},end:{month:10,day:10},peakZhr:10,velocityKmS:20,populationIndex:2.6},{id:"orionids",code:"ORI",name:{en:"Orionids",fr:"Orionides"},radiantRaHours:6.35,radiantDecDeg:15.6,start:{month:10,day:2},peak:{month:10,day:21},end:{month:11,day:7},peakZhr:20,velocityKmS:66,populationIndex:2.5},{id:"northern-taurids",code:"NTA",name:{en:"Northern Taurids",fr:"Taurides du Nord"},radiantRaHours:3.87,radiantDecDeg:22,start:{month:10,day:20},peak:{month:11,day:12},end:{month:12,day:10},peakZhr:5,velocityKmS:29,populationIndex:2.3},{id:"leonids",code:"LEO",name:{en:"Leonids",fr:"Léonides"},radiantRaHours:10.13,radiantDecDeg:21.6,start:{month:11,day:6},peak:{month:11,day:17},end:{month:11,day:30},peakZhr:15,velocityKmS:71,populationIndex:2.5},{id:"geminids",code:"GEM",name:{en:"Geminids",fr:"Géminides"},radiantRaHours:7.47,radiantDecDeg:32.3,start:{month:12,day:4},peak:{month:12,day:14},end:{month:12,day:17},peakZhr:150,velocityKmS:35,populationIndex:2.6},{id:"ursids",code:"URS",name:{en:"Ursids",fr:"Ursides"},radiantRaHours:14.47,radiantDecDeg:75.3,start:{month:12,day:17},peak:{month:12,day:22},end:{month:12,day:26},peakZhr:10,velocityKmS:33,populationIndex:3}],xo=6.5;class da{static activeAt(e){return zT.flatMap(t=>{const n=this.nearness(t,e);return n<=0?[]:[{shower:t,zhr:t.peakZhr*n,nearness:n}]})}static nearness(e,t){const n=this.dayOfYear(t),i=this.dayOfYear(this.asDate(e.start)),s=this.dayOfYear(this.asDate(e.peak)),a=this.dayOfYear(this.asDate(e.end)),o=this.wrappedDelta(n,s),l=this.wrappedDelta(s,i),c=this.wrappedDelta(a,s);return o<0?o<-l?0:1+o/l:o>0?o>c?0:1-o/c:1}static observedRatePerHour(e,t,n,i=xo){if(t<=0)return 0;const s=xo-i;return e*Math.sin(t*Math.PI/180)/Math.pow(n,s)}static radiantPosition(e,t,n){return Rc(e.radiantRaHours,e.radiantDecDeg,t,n)}static dayOfYear(e){const t=Date.UTC(e.getUTCFullYear(),0,1);return Math.floor((Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())-t)/864e5)+1}static asDate(e){return new Date(Date.UTC(2001,e.month-1,e.day))}static wrappedDelta(e,t){const n=e-t;return n>182?n-365:n<-182?n+365:n}}class Dt{static QUIET_RATE_PER_HOUR=2;static APEX_RATE_PER_HOUR=8;static POPULATION_INDEX=3;static apexPosition(e,t){const n=Xt(e),i=new hf(0,xE(e).elon-90,1),s=Vl(YE(n),pv(i,n)),a=mv(s);return Rc(a.ra,a.dec,e,t)}static observedRatePerHour(e,t=xo){const n=Dt.APEX_RATE_PER_HOUR*Math.max(0,Math.sin(e*Math.PI/180)),i=xo-t;return(Dt.QUIET_RATE_PER_HOUR+n)/Math.pow(Dt.POPULATION_INDEX,i)}static schedule(e){const t=new yv(e.seed^1542469173);return rr.schedule(e).map(n=>{const i=Dt.toCartesian({altitudeDeg:Math.asin(t.next())*180/Math.PI,azimuthDeg:t.between(0,360)}),s=n.fromRadiantDeg*Math.PI/180,a=Dt.turnAround(i,t.between(0,360)),o={x:i.x*Math.cos(s)+a.x*Math.sin(s),y:i.y*Math.cos(s)+a.y*Math.sin(s),z:i.z*Math.cos(s)+a.z*Math.sin(s)};return{...n,radiant:Dt.toHorizontal(o),bearingDeg:Dt.bearingFrom(o,i)}})}static turnAround(e,t){const[n,i]=Dt.basisAround(e),s=t*Math.PI/180;return{x:n.x*Math.cos(s)+i.x*Math.sin(s),y:n.y*Math.cos(s)+i.y*Math.sin(s),z:n.z*Math.cos(s)+i.z*Math.sin(s)}}static bearingFrom(e,t){const[n,i]=Dt.basisAround(e),s=e.x*t.x+e.y*t.y+e.z*t.z,a=Dt.normalise({x:t.x-e.x*s,y:t.y-e.y*s,z:t.z-e.z*s});return(Math.atan2(a.x*i.x+a.y*i.y+a.z*i.z,a.x*n.x+a.y*n.y+a.z*n.z)*180/Math.PI%360+360)%360}static basisAround(e){const t=Math.abs(e.y)<.9?{x:0,y:1,z:0}:{x:1,y:0,z:0},n=Dt.normalise(Dt.cross(e,t));return[n,Dt.normalise(Dt.cross(e,n))]}static toHorizontal(e){const t=Math.hypot(e.x,e.y,e.z)||1;return{altitudeDeg:Math.asin(Math.min(1,Math.max(-1,e.y/t)))*180/Math.PI,azimuthDeg:(Math.atan2(e.x,-e.z)*180/Math.PI%360+360)%360}}static appearanceOf(e){const t=Dt.toCartesian(e.radiant??{altitudeDeg:90,azimuthDeg:0}),n=Dt.turnAround(t,e.bearingDeg),i=e.fromRadiantDeg*Math.PI/180;return Dt.toHorizontal({x:t.x*Math.cos(i)+n.x*Math.sin(i),y:t.y*Math.cos(i)+n.y*Math.sin(i),z:t.z*Math.cos(i)+n.z*Math.sin(i)})}static toCartesian(e){const t=e.altitudeDeg*Math.PI/180,n=e.azimuthDeg*Math.PI/180,i=Math.cos(t);return{x:i*Math.sin(n),y:Math.sin(t),z:-i*Math.cos(n)}}static cross(e,t){return{x:e.y*t.z-e.z*t.y,y:e.z*t.x-e.x*t.z,z:e.x*t.y-e.y*t.x}}static normalise(e){const t=Math.hypot(e.x,e.y,e.z)||1;return{x:e.x/t,y:e.y/t,z:e.z/t}}static TYPICAL_VELOCITY_KM_S=40}const Tm="https://ufoathome.org/tle/index.json";class pn{static MAX_ELEMENT_AGE_DAYS=7;static DAY_MS=864e5;fetchImpl;indexUrls;index;files=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??pn.defaultIndexUrls()}static defaultIndexUrls(){const e=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&e.push(new URL("/tle/index.json",location.href).href),e.includes(Tm)||e.push(Tm),e}static FIRST_SNAPSHOT="2021-02-22";async covers(e){const t=Date.parse(`${pn.FIRST_SNAPSHOT}T00:00:00Z`)-pn.MAX_ELEMENT_AGE_DAYS*pn.DAY_MS;if(e.getTime()<t)return!1;const n=await this.loadIndex();return n?Object.values(n.index.kinds).some(i=>e.getTime()>=Date.parse(i.from)-pn.MAX_ELEMENT_AGE_DAYS*pn.DAY_MS&&e.getTime()<=Date.parse(i.to)+pn.MAX_ELEMENT_AGE_DAYS*pn.DAY_MS):!1}async at(e){const t=await this.loadIndex();if(!t)return;const{index:n,base:i}=t,s=[],a=[];for(const o of Object.keys(n.kinds)){const l=await this.kindAt(o,e,n,i);s.push(...l),a.push(this.coverageOf(o,e,n,l.length>0))}return{objects:s,coverage:a,credit:n.credit,creditUrl:n.source}}async kindAt(e,t,n,i){const s=t.getTime(),a=n.binDays*pn.DAY_MS,o=Math.floor(s/a),l=s-o*a<a/2?o-1:o+1,c=new Set(n.kinds[e].bins),h=[o,l].map(v=>new Date(v*a).toISOString().slice(0,10)).filter(v=>c.has(v));if(h.length===0)return[];const[d,...u]=await Promise.all([this.json(new URL(`objects-${e}.json`,i).href),...h.map(v=>this.binary(new URL(`${e}/${v}.bin`,i).href))]),f=new Map;for(const v of u)for(const m of pn.decode(v,n.recordBytes)){const g=f.get(m.norad);(!g||Math.abs(m.epochMs-s)<Math.abs(g.epochMs-s))&&f.set(m.norad,m)}const p=[];for(const v of f.values()){const m=Math.abs(v.epochMs-s)/pn.DAY_MS;if(m>pn.MAX_ELEMENT_AGE_DAYS)continue;const g=d[v.norad]??{name:String(v.norad)};g.launch&&Date.parse(`${g.launch}T00:00:00Z`)>s||p.push({norad:v.norad,name:g.name,kind:e,launch:g.launch,stdMag:g.stdMag,elements:v,ageDays:m})}return p}coverageOf(e,t,n,i){const{from:s,to:a}=n.kinds[e],o=t.getTime(),l=pn.MAX_ELEMENT_AGE_DAYS*pn.DAY_MS,c=i?"covered":o<Date.parse(s)-l?"before":o>Date.parse(a)+l?"after":"gap";return{kind:e,status:c,from:s,to:a}}static decode(e,t){const n=new DataView(e),i=[];for(let s=0;s+t<=e.byteLength;s+=t)i.push({norad:n.getUint32(s,!0),epochMs:n.getFloat64(s+4,!0),bstar:n.getFloat32(s+12,!0),inclinationDeg:n.getFloat32(s+16,!0),raanDeg:n.getFloat32(s+20,!0),eccentricity:n.getFloat32(s+24,!0),argOfPerigeeDeg:n.getFloat32(s+28,!0),meanAnomalyDeg:n.getFloat32(s+32,!0),meanMotion:n.getFloat64(s+36,!0)});return i}loadIndex(){return this.index??=(async()=>{for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;return{index:await t.json(),base:e}}catch{}})(),this.index}json(e){return this.cached(e,async t=>t.json())}binary(e){return this.cached(e,async t=>t.arrayBuffer())}cached(e,t){let n=this.files.get(e);return n||(n=this.fetchImpl(e).then(i=>{if(!i.ok)throw new Error(`${e}: ${i.status}`);return t(i)}),n.catch(()=>this.files.delete(e)),this.files.set(e,n)),n}}class HT{lowerM;upperM;add(e,t){if(!(e<=0)){if(t.behindM!==void 0){const n=et.sizeMAt(t.behindM,e);this.lowerM=this.lowerM===void 0?n:Math.max(this.lowerM,n)}if(t.inFrontM!==void 0){const n=et.sizeMAt(t.inFrontM,e);this.upperM=this.upperM===void 0?n:Math.min(this.upperM,n)}}}get sizeRange(){return{minM:this.lowerM,maxM:this.upperM}}get empty(){return this.lowerM===void 0&&this.upperM===void 0}get contradictory(){return this.lowerM!==void 0&&this.upperM!==void 0&&this.lowerM>this.upperM}distanceRangeAt(e){return e<=0?{}:{minM:this.lowerM===void 0?void 0:et.distanceMAt(this.lowerM,e),maxM:this.upperM===void 0?void 0:et.distanceMAt(this.upperM,e)}}clear(){this.lowerM=void 0,this.upperM=void 0}}class ar{static DEG_PER_SECOND=360/86164.0905;static degOver(e){return Math.max(0,e)*ar.DEG_PER_SECOND}static instants(e,t){if(!(t>0))return 1;const n=ar.degOver(e)/t;return n<1?1:Math.min(ar.MAX_INSTANTS,Math.max(2,Math.ceil(n)))}static MAX_INSTANTS=64}class mn{static EYE={apertureMm:7,exposureSeconds:.1,resolutionArcsec:60};static WAVELENGTH_M=55e-8;static ARCSEC_PER_RADIAN=180*3600/Math.PI;static UNKNOWN_CAMERA_FOCAL_MM=50;static UNKNOWN_CAMERA_DETAIL_UM=20;static get skyDriftArcsecPerSecond(){return ar.DEG_PER_SECOND*3600}static graspOf(e,t={}){const n=t.exposureSeconds??e.exposureSeconds,i=t.fNumber??e.fNumber;if(n===void 0||i===void 0||!(n>0)||!(i>0))return mn.EYE;const s=t.focalLengthMm??e.frame?.focalLengthMm??mn.UNKNOWN_CAMERA_FOCAL_MM,a=s/i,o=mn.resolutionArcsec(e,s,a);return{apertureMm:a,exposureSeconds:Math.min(n,mn.trailLimitedSeconds(o)),resolutionArcsec:o}}static resolutionArcsec(e,t,n){const s=(e.detailUm??mn.UNKNOWN_CAMERA_DETAIL_UM)/1e3/t*mn.ARCSEC_PER_RADIAN,a=1.22*mn.WAVELENGTH_M/(n/1e3)*mn.ARCSEC_PER_RADIAN;return Math.max(s,a)}static trailLimitedSeconds(e){return e/mn.skyDriftArcsecPerSecond}static gainOverEye(e,t={}){const n=mn.graspOf(e,t),i=mn.EYE,s=(n.apertureMm/i.apertureMm)**2,a=n.exposureSeconds/i.exposureSeconds,o=(i.resolutionArcsec/n.resolutionArcsec)**2;return 1.25*Math.log10(s*a*o)}static gainFor(e,t){const n=t.fieldOfViewDeg===void 0?void 0:rt.focalLengthMmFor(e,t.fieldOfViewDeg);return mn.gainOverEye(e,{fNumber:t.fNumber,focalLengthMm:n,exposureSeconds:t.exposureSeconds})}}const Am=111320,Wa=Math.PI/180,GT=1.02,WT=1;class oo{static of(e,t){const n=oo.sightings(e,t);if(n.length<2)return;const i=oo.baseline(n);if(!i)return;const{near:s,far:a,closedM:o}=i,l=Math.tan(a.widthDeg/2*Wa)===0?0:Math.tan(s.widthDeg/2*Wa)/Math.tan(a.widthDeg/2*Wa);if(l<GT)return;const c=o/(l-1),h=et.sizeMAt(c,s.widthDeg),d=n.map(u=>({t:u.t,m:et.distanceMAt(h,u.widthDeg)}));return{widthM:h,distanceM:d,nearestM:Math.min(...d.map(u=>u.m)),fromT:a.t,toT:s.t,closedM:o}}static sightings(e,t){return e.timeline.allKeyframes.flatMap(n=>{const i=n.shapes.find(o=>o.sourceId===t)?.shape,s=i?.angular?.widthDeg,a=tt(e,n.t);return s===void 0||s<=0||a?.lat===void 0||a.lng===void 0?[]:[{t:n.t,widthDeg:s,lat:a.lat,lng:a.lng,sightAzimuthDeg:i?.aim?.azimuthDeg??a.headingDeg}]}).sort((n,i)=>n.t-i.t)}static baseline(e){let t;for(const n of e)for(const i of e){if(n.t>=i.t)continue;const s=oo.closedAlongSight(n,i),[a,o,l]=s>=0?[i,n,s]:[n,i,-s];l<WT||a.widthDeg<=o.widthDeg||(!t||l>t.closedM)&&(t={near:a,far:o,closedM:l})}return t}static closedAlongSight(e,t){const n=(t.lat-e.lat)*Am,i=(t.lng-e.lng)*Am*Math.cos(e.lat*Wa),s=(e.sightAzimuthDeg??0)*Wa;return n*Math.cos(s)+i*Math.sin(s)}}class xn{static CONVENTIONAL_M=5;static NEAREST_M=.2;static MARGIN=1.1;static resolve(e){if(e.statedM!==void 0&&e.statedM>0)return{distanceM:xn.atLeastNearest(e.statedM),basis:"stated"};if(e.hypothesisM!==void 0&&e.hypothesisM>0)return{distanceM:xn.atLeastNearest(e.hypothesisM),basis:"hypothesis"};if(e.derivedM!==void 0&&e.derivedM>0)return{distanceM:xn.atLeastNearest(e.derivedM),basis:"derived"};const t=xn.largest(e.range?.minM,e.crossing?.behindM),n=xn.smallest(e.range?.maxM,e.crossing?.inFrontM),i=t===void 0?void 0:t*xn.MARGIN,s=n===void 0?void 0:n/xn.MARGIN;return i!==void 0&&s!==void 0?{distanceM:xn.atLeastNearest(i<=s?Math.sqrt(i*s):i),basis:"bounded"}:i!==void 0?{distanceM:xn.atLeastNearest(i),basis:"bounded"}:s!==void 0&&s<xn.CONVENTIONAL_M?{distanceM:xn.atLeastNearest(s),basis:"bounded"}:{distanceM:xn.CONVENTIONAL_M,basis:"conventional"}}static atLeastNearest(e){return Math.max(xn.NEAREST_M,e)}static largest(...e){const t=e.filter(n=>n!==void 0&&n>0);return t.length===0?void 0:Math.max(...t)}static smallest(...e){const t=e.filter(n=>n!==void 0&&n>0);return t.length===0?void 0:Math.min(...t)}}xc();const VT={sun:{en:"Sun",fr:"Soleil"},moon:{en:"Moon",fr:"Lune"},Venus:{en:"Venus",fr:"Vénus"},Mars:{en:"Mars",fr:"Mars"},Jupiter:{en:"Jupiter",fr:"Jupiter"},Saturn:{en:"Saturn",fr:"Saturne"}},XT=["en","fr"],qT={en:"{name} — mag {mag}, {alt}° above the horizon",fr:"{name} — mag {mag}, {alt}° au-dessus de l'horizon"},YT={en:"{name} — satellite, mag {mag}, {height} km up",fr:"{name} — satellite, mag {mag}, à {height} km d'altitude"},Pv="satellites-change",$T={en:"{name} — mag {mag}, {alt}° below the horizontal",fr:"{name} — mag {mag}, {alt}° sous l'horizontale"},Im="comet:",KT={building:{en:"Building",fr:"Bâtiment"},tree:{en:"Tree",fr:"Arbre"},crop:{en:"Crop row",fr:"Rang de culture"},mound:{en:"Stone heap",fr:"Tas de pierres"},streetlight:{en:"Streetlight",fr:"Lampadaire"},vehicle:{en:"Vehicle",fr:"Véhicule"},witness:{en:"Witness",fr:"Témoin"},aircraft:{en:"Aircraft",fr:"Aéronef"},entity:{en:"Being",fr:"Être"}},ZT=new URL(""+new URL("stars-mag7.5-B43R6Wvg.bin",import.meta.url).href,import.meta.url).href,jT=new URL(""+new URL("stars-mag7.5-9-BLV2tFmZ.bin",import.meta.url).href,import.meta.url).href,JT=-18,QT={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},qh={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class ff extends HTMLElement{static get observedAttributes(){return["src","star-catalog-src","deep-star-catalog-src","show-compass","max-pixel-ratio",sr,ia]}shadow;stageElement;frameElement;sceneCanvas;ufoElement;sceneRenderer;hoverTooltip;resizeObserver;sizeEstimates=new Map;sizeEstimatesFor;distanceHypotheses=new Map;depths=new Map;directionScratch=new P;meteorScheduleFor;lastTimeMs=0;lastSkyKey;starCatalog;starCatalogRequest=0;static tleArchive=new pn;satellitesFor;satelliteRequest=0;satelliteStatus="none";satellites;satellitePassesMemo;starCatalogDepth=0;weatherAudio=new BT;animateWhilePausedValue=!1;set animateWhilePaused(e){e!==this.animateWhilePausedValue&&(this.animateWhilePausedValue=e,this.syncAnimationsToPlayback())}get animateWhilePaused(){return this.animateWhilePausedValue}thunderTimeoutId;handleFullscreenChange=()=>this.resizeToStage();handlePointerMove=e=>{this.sceneRenderer.setCompassHovered(!0);const t=this.ufoElement.canvasElement,n=t.getBoundingClientRect();if(n.width===0||n.height===0)return;const i=(e.clientX-n.left)/n.width*t.width,s=(e.clientY-n.top)/n.height*t.height;if(this.ufoElement.hasVisibleShapeAt(i,s)){this.hoverTooltip.hidden=!0;return}const a=(e.clientX-n.left)/n.width*2-1,o=-((e.clientY-n.top)/n.height*2-1),l=na(Ts.preferencesFor(this),XT),c=this.sceneRenderer.pickBodyAt(a,o);if(c){this.showHoverTooltip(e,this.bodyName(c,l));return}const h=this.sceneRenderer.pickDecorAt(a,o),d=h?this.ufoElement.sighting.decor.find(p=>p.id===h):void 0;if(d){this.showHoverTooltip(e,this.said.read(d.title)||KT[d.kind][l]);return}const u=this.sceneRenderer.pickSatelliteAt(a,o);if(u){this.showHoverTooltip(e,YT[l].replace("{name}",u.name).replace("{mag}",u.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(u.heightKm).toLocaleString()));return}const f=this.sceneRenderer.pickStarAt(a,o);if(f){const p=f.star.mag,v=f.altitudeDeg,m=(v<0?$T:qT)[l];this.showHoverTooltip(e,m.replace("{name}",f.star.name[l]).replace("{mag}",p.toLocaleString(void 0,{maximumFractionDigits:Math.abs(p)<1?2:1})).replace("{alt}",String(Math.round(Math.abs(v)))));return}this.hoverTooltip.hidden=!0};bodyName(e,t){const n=e.startsWith(Im)?e.slice(Im.length):void 0;return(n?Rv.find(s=>s.id===n):void 0)?.name[t]??VT[e]?.[t]??e}showHoverTooltip(e,t){this.hoverTooltip.textContent=t,this.hoverTooltip.hidden=!1;const n=this.stageElement.getBoundingClientRect();this.hoverTooltip.style.left=`${e.clientX-n.left+12}px`,this.hoverTooltip.style.top=`${e.clientY-n.top+12}px`}handlePointerLeave=()=>{this.hoverTooltip.hidden=!0,this.sceneRenderer.setCompassHovered(!1)};handleLightningFlash=()=>{clearTimeout(this.thunderTimeoutId);const e=(.5+Math.random()*3.5)*1e3;this.thunderTimeoutId=window.setTimeout(()=>this.weatherAudio.playThunder(),e)};handleFirstInteraction=()=>{this.weatherAudio.resume(),this.setWeather(Ut(this.ufoElement.sighting,this.lastTimeMs))};handleTimeUpdate=e=>{this.lastTimeMs=e.detail.time,this.syncAnimationsToPlayback(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.playbackState==="playing"&&this.sceneRenderer.frame(performance.now())};syncAnimationsToPlayback(){const e=this.ufoElement.playbackState==="playing",t=e||this.animateWhilePaused;this.sceneRenderer.setAnimationsRunning(t,e),this.weatherAudio.setPaused(!t),t||clearTimeout(this.thunderTimeoutId)}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${ry}</style>${sy}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.frameElement=this.shadow.getElementById("frame"),this.sceneCanvas=this.shadow.getElementById("scene-canvas"),this.sceneRenderer=new $n(this.sceneCanvas,void 0,this.handleLightningFlash),this.hoverTooltip=this.shadow.getElementById("hover-tooltip"),this.ufoElement=document.createElement(ld),this.ufoElement.classList.add("ufo-overlay"),this.ufoElement.paintsShapes=!1,this.forwardPlayerAttributes(),this.ufoElement.addEventListener("lookat",t=>this.lookToward(t.detail)),this.ufoElement.style.setProperty("--ufo-canvas-background","transparent"),this.ufoElement.style.setProperty("--ufo-canvas-border","none"),this.ufoElement.fullscreenTarget=this.stageElement,this.shadow.getElementById("ufo-slot").replaceWith(this.ufoElement),this.sceneRenderer.onMapSubjectBounds=t=>this.ufoElement.setMapSubjectBounds(t),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),this.ufoElement.addEventListener("referenceview",t=>this.applyReferenceView(t.detail)),this.ufoElement.canvasElement.addEventListener("pointermove",this.handlePointerMove),this.ufoElement.canvasElement.addEventListener("pointerleave",this.handlePointerLeave),this.ufoElement.canvasElement.addEventListener("pointerdown",this.handleFirstInteraction,{once:!0})}get said(){return this.saidTexts??=new Zi(Ts.preferencesFor(this))}saidTexts;connectedCallback(){this.saidTexts=void 0,this.sceneRenderer.restoreContext(),this.resizeToStage(),this.updateAstronomy(this.lastTimeMs),this.loadStars(),this.resizeObserver=new ResizeObserver(()=>this.resizeToStage()),this.resizeObserver.observe(this.frameElement),document.addEventListener("fullscreenchange",this.handleFullscreenChange);const e=this.getAttribute("src");e&&this.loadFromSrc(e)}disconnectedCallback(){this.resizeObserver?.disconnect(),document.removeEventListener("fullscreenchange",this.handleFullscreenChange),this.sceneRenderer.stopTwinkle(),clearTimeout(this.thunderTimeoutId),this.weatherAudio.dispose(),queueMicrotask(()=>{this.isConnected||this.sceneRenderer.releaseContext()})}attributeChangedCallback(e,t,n){if(e==="src"&&n&&n!==t&&this.isConnected&&this.loadFromSrc(n),(e==="star-catalog-src"||e==="deep-star-catalog-src")&&n!==t&&this.isConnected&&this.loadStars(),e==="show-compass"&&n!==t&&this.sceneRenderer.setShowCompass(this.hasAttribute("show-compass")),e==="max-pixel-ratio"&&n!==t){const i=Number(n);this.sceneRenderer.setMaxPixelRatio(Number.isFinite(i)&&i>0?i:Math.min(window.devicePixelRatio||1,2))}(e===sr||e===ia)&&n!==t&&this.forwardPlayerAttributes()}forwardPlayerAttributes(){for(const e of[sr,ia])this.ufoElement.toggleAttribute(e,this.hasAttribute(e))}setCompassForced(e){this.sceneRenderer.setCompassForced(e)}lookToward(e){const t=tt(this.ufoElement.sighting,this.lastTimeMs);if(e.kind==="witness"||t?.lat===void 0||t.lng===void 0||t.headingDeg===void 0){this.setLookOffset(0,0);return}const{x:n,z:i}=on(e.lat,e.lng,t.lat,t.lng);if(Math.hypot(n,i)<1)return this.setLookOffset(0,0);const s=(Math.atan2(n,-i)*180/Math.PI+360)%360;this.setLookOffset(((s-t.headingDeg)%360+540)%360-180,-t.pitchDeg)}setLookOffset(e,t){this.sceneRenderer.setLookOffset(e,t),this.ufoElement.setLookOffset(e,t),this.updateAstronomy(this.lastTimeMs)}setIndoorLook(e,t){this.sceneRenderer.setIndoorLook(e,t)}setCloudRendering(e){this.sceneRenderer.setCloudRendering(e)}setWeather(e){this.sceneRenderer.setWeather(e),this.weatherAudio.setAmbient(e.precipitationType,e.precipitationIntensity,e.windSpeed)}pickCloudAt(e,t){return this.sceneRenderer.pickCloudAt(e,t)}cloudDirectionAt(e,t){return this.sceneRenderer.cloudDirectionAt(e,t)}pickDecorAt(e,t){return this.sceneRenderer.pickDecorAt(e,t)}resumeWeatherAudio(){this.weatherAudio.resume()}async loadFromSrc(e){this.sightingData=await Lu.json(e)}get sightingData(){return this.ufoElement.sightingData}set sightingData(e){this.ufoElement.sightingData=e,this.applyFrameFormat(),this.lastTimeMs=0,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(0)}referenceAspect(e){return this.sceneRenderer.referenceAspect(e)}screenPointOf(e){return this.sceneRenderer.screenPointOf(e)}directionAt(e,t){return this.sceneRenderer.directionAt(e,t)}referenceFailedToLoad(e){return this.sceneRenderer.referenceFailedToLoad(e)}applyReferenceView(e){this.sceneRenderer.setReferencesShown(e.shown);for(const t of this.ufoElement.sighting.references)this.sceneRenderer.setReferenceView(t.id,{opacity:e.opacity})}get currentTerrainAttribution(){return this.sceneRenderer.currentTerrainAttribution}setTerrainProviders(e){this.sceneRenderer.setTerrainProviders(e)}setDecorModelProvider(e){this.sceneRenderer.setDecorModelProvider(e)}get decorModelCredits(){return this.sceneRenderer.currentDecorModelCredits}applyFrameFormat(){const e=this.ufoElement.sighting.instrument,t=et.CANVAS_HEIGHT_PX,n=rt.frameWidthPx(e,t);this.frameElement.style.setProperty("--frame-aspect",`${n} / ${t}`)}resizeToStage(){const e=this.frameElement.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height));this.sceneCanvas.width=t,this.sceneCanvas.height=n,this.sceneRenderer.resize(t,n)}async loadStars(){const e=[{magnitudeLimit:Xh,url:this.getAttribute("star-catalog-src")??ZT},{magnitudeLimit:ao,url:this.getAttribute("deep-star-catalog-src")??jT}],t=this.instrumentReach(),n=++this.starCatalogRequest;this.starCatalogDepth=t>Xh?ao:Xh;const i=await xi.upTo(e,t);n===this.starCatalogRequest&&(this.starCatalog=i,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(this.lastTimeMs))}ensureStarsDeepEnough(){!this.starCatalog||this.starCatalogDepth>=ao||this.instrumentReach()<=this.starCatalogDepth||this.loadStars()}instrumentReach(){const e=this.ufoElement.sighting,t=mn.gainFor(e.instrument,{fNumber:tt(e,0)?.fNumber,fieldOfViewDeg:ln.fovOf(e,0),exposureSeconds:e.exposure});return nr(JT,t)}updateAstronomy(e){this.ensureStarsDeepEnough(),this.applySceneAt(e);const t=ii.windowEndingAt(e,this.exposureSeconds()),n=t.seconds,i=this.degreesPerPixelAt(e),s=ar.instants(n,i),a=Math.max(s,this.ufoElement.exposureTimes(e).length,ii.instants(this.ufoElement.sighting.decor,tt(this.ufoElement.sighting,e)?.elevationM??0,t.fromMs,n,i));if(a<=1){this.sceneRenderer.setExposure(1);return}this.sceneRenderer.setExposure(a,o=>this.applySceneAt(t.fromMs+t.ms*o/(a-1),{sky:Math.floor(o*s/a)!==Math.floor((o-1)*s/a),stepMs:t.ms/a}))}exposureSeconds(){return this.ufoElement.sighting.exposure??0}degreesPerPixelAt(e){const t=this.sceneCanvas.height;return t<=0?0:ln.fovOf(this.ufoElement.sighting,e)/t}applySceneAt(e,t){const n=this.ufoElement.sighting;this.setWeather(Ut(n,e)),this.sceneRenderer.setInstrument(n.instrument),this.updateMeteorShower(n,e),this.sceneRenderer.setDecor(n.decor),this.sceneRenderer.setReferences(n.references);const i=tt(n,e),s=tt(n,0),a=Ut(n,0),o=Object.fromEntries(Di(Ut(n,e)).map(x=>[x.id,$l(e,n.weatherTrack,a,s,i,x.id)]));this.sceneRenderer.setCloudOffset($l(e,n.weatherTrack,a,s,i),o),this.sceneRenderer.setObserverPose(i??qh),this.sceneRenderer.setLensOptics(this.lensOpticsAt(e)),this.sceneRenderer.setInstrumentGain(mn.gainFor(n.instrument,{fNumber:i?.fNumber,fieldOfViewDeg:ln.fovOf(n,e),exposureSeconds:n.exposure})),this.sceneRenderer.setGait($t.of(n)?.offsetAt(e)??$t.STILL),this.sceneRenderer.updateDecorAnchoring(tt(n,0),i,e),this.sceneRenderer.updateDecorLitState(e,t?.stepMs??0),this.sceneRenderer.setTerrainOrigin(i?.lat,i?.lng),this.pushPhenomenaAt(e);const l=i?.lat??qh.lat,c=i?.lng??qh.lng,h=Ds(n.event.time??{},c,n.event.utcOffsetHours),d={lat:l,lng:c,elevationM:i?.elevationM??0};if(this.pushSatellitesAt(h,e,d),t&&!t.sky)return;if(!h){this.sceneRenderer.setAstronomy(QT);return}const u=new Date(h.getTime()+e),f=Math.max(1,Math.round(.25*this.degreesPerPixelAt(e)/ar.DEG_PER_SECOND*1e3)),p=Math.max(1e-8,this.degreesPerPixelAt(e)*.1),v=`${Math.floor(u.getTime()/f)}|${Math.round(l/p)}|${Math.round(c/p)}|${Math.round(d.elevationM)}|${this.starCatalog?this.starCatalogDepth:0}`;if(v===this.lastSkyKey){this.sceneRenderer.render();return}this.lastSkyKey=v;const m={...Cn("Sun",u,d),magnitude:Ah("Sun",u)},g={...Cn("Moon",u,d),phase:vc(u),magnitude:Ah("Moon",u)},M=$E.map(x=>({body:x,position:Cn(x,u,d),magnitude:Ah(x,u)}));this.sceneRenderer.setAstronomy({sun:m,moon:g,planets:M,comet:this.cometAt(u,d),stars:this.starCatalog?{catalog:this.starCatalog,date:u,observer:d}:void 0,frame:{date:u,observer:d}}),this.ufoElement.setSunAltitude(m.altitudeDeg)}pushSatellitesAt(e,t,n){if(this.ensureSatellites(e),!e||!this.satellites){this.sceneRenderer.setSatellites([]);return}const i=new Date(e.getTime()+t),s=[];for(const a of this.satellites.passes.positionsAt(i,n,-1))a.magnitude!==void 0&&s.push({norad:a.object.norad,name:a.object.name,position:{altitudeDeg:a.altitudeDeg,azimuthDeg:a.azimuthDeg},magnitude:a.magnitude,heightKm:a.heightKm});this.sceneRenderer.setSatellites(s)}ensureSatellites(e){const t=e?String(e.getTime()):"";if(t===this.satellitesFor)return;this.satellitesFor=t,this.satellites=void 0,this.satellitePassesMemo=void 0;const n=++this.satelliteRequest;if(!e){this.satelliteStatus="none";return}this.satelliteStatus="loading";const i=a=>{n===this.satelliteRequest&&(this.satelliteStatus=a,this.dispatchEvent(new CustomEvent(Pv)))},s=ff.tleArchive;(async()=>{if(!await s.covers(e))return i("outside");const[a,o]=await Promise.all([s.at(e),jn(()=>import("./SatellitePasses-Pfro2-0Z.js"),[],import.meta.url)]);if(n===this.satelliteRequest){if(!a)return i("unavailable");this.satellites={snapshot:a,passes:new o.SatellitePasses(a.objects)},i("ready"),this.updateAstronomy(this.lastTimeMs)}})().catch(()=>i("unavailable"))}get satelliteState(){const e=this.satellites?.snapshot;return{status:this.satelliteStatus,coverage:e?.coverage,credit:e?.credit,creditUrl:e?.creditUrl}}satellitePassesDuring(e){const t=this.satellites,n=this.ufoElement.sighting,i=tt(n,0),s=n.event.place?.[0],a=i?.lat??s?.lat,o=i?.lng??s?.lng;if(!t||a===void 0||o===void 0)return[];const l=Ds(n.event.time??{},o,n.event.utcOffsetHours);if(!l)return[];const c=Math.min(Math.max(e,0),4*36e5),h={lat:a,lng:o,elevationM:i?.elevationM??0},d=JSON.stringify([this.satellitesFor,l.getTime(),a,o,h.elevationM,c]);if(this.satellitePassesMemo?.key===d)return this.satellitePassesMemo.passes;const u=Math.max(10,Math.ceil(c/1e3/600)),f=t.passes.passesDuring(l,new Date(l.getTime()+c),h,u);return this.satellitePassesMemo={key:d,passes:f},f}cometAt(e,t){const n=ql.brightestAt(e,t);if(n)return{id:n.apparition.id,position:n.position,tailEnd:n.tailEnd,magnitude:n.magnitude}}pushPhenomenaAt(e){const t=this.ufoElement.sighting;t!==this.sizeEstimatesFor&&(this.sizeEstimates.clear(),this.distanceHypotheses.clear(),this.sizeEstimatesFor=t);const n=t.timeline,i=this.ufoElement.canvasElement,s=this.ufoElement.frameShiftPx,a=this.projectionAt(e),o=new Map,l=new Map,c=new Set;for(const p of n.sourceIds){const v=n.getInterpolatedShapeAt(e,p);if(!v)continue;const m={...v,bounds:{...v.bounds,x:v.bounds.x+s.x,y:v.bounds.y+s.y}};o.set(p,m);const g=v.aim?this.sceneRenderer.screenPointOf(ni.directionOf(v.aim,this.directionScratch)):{ndcX:(m.bounds.x+m.bounds.width/2)/i.width*2-1,ndcY:-((m.bounds.y+m.bounds.height/2)/i.height*2-1)},M=g!==void 0&&Math.abs(g.ndcX)<=1&&Math.abs(g.ndcY)<=1,x=M?this.sceneRenderer.decorDistancesAt(g.ndcX,g.ndcY,p):{};c.add(p),(M||v.aim)&&c.delete(p);const w=v.angular?.widthDeg??a.pxToDeg(v.bounds.width),S=this.sizeEstimateOf(p);S.add(w,x);const E=oo.of(t,p);l.set(p,xn.resolve({hypothesisM:this.distanceHypotheses.get(p),derivedM:E&&w>0?et.distanceMAt(E.widthM,w):void 0,range:S.distanceRangeAt(w),crossing:x}))}for(const[p,v]of o)for(const[m,g]of o){if(m===p||g.transparency>=1||g.bounds.width*g.bounds.height<=v.bounds.width*v.bounds.height||!(v.bounds.x>=g.bounds.x&&v.bounds.y>=g.bounds.y&&v.bounds.x+v.bounds.width<=g.bounds.x+g.bounds.width&&v.bounds.y+v.bounds.height<=g.bounds.y+g.bounds.height))continue;const x=l.get(m);x&&l.set(p,{distanceM:x.distanceM*.999,basis:x.basis});break}this.depths=l;const h=n.sourceIds,d=[];for(const[p,v]of o)d.push({sourceId:p,shape:v,distanceM:l.get(p).distanceM,renderOrder:h.indexOf(p),aim:v.aim,hidden:c.has(p)});const f=(tt(t,e)?.rollDeg??0)+($t.of(t)?.offsetAt(e)??$t.STILL).rollDeg;this.sceneRenderer.setPhenomena(d,{projection:a,canvasWidthPx:i.width,canvasHeightPx:i.height,scale:Math.max(1,this.sceneCanvas.height/Math.max(1,i.height)),starPoints:rt.starPointsOf(t.instrument),rollRad:f*Math.PI/180})}setDistanceHypothesis(e,t){t===void 0||!(t>0)?this.distanceHypotheses.delete(e):this.distanceHypotheses.set(e,t),this.updateAstronomy(this.lastTimeMs)}depthOf(e){return this.depths.get(e)}sizeRangeOf(e){return this.sizeEstimateOf(e).sizeRange}distanceRangeAt(e,t){const n=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,e);if(!n)return{};const i=n.angular?.widthDeg??this.projectionAt(t).pxToDeg(n.bounds.width);return this.sizeEstimateOf(e).distanceRangeAt(i)}sizeContradictory(e){return this.sizeEstimateOf(e).contradictory}updateMeteorShower(e,t){this.ensureMeteorSchedule(e),this.sceneRenderer.updateMeteors(t)}ensureMeteorSchedule(e){const t=this.meteorInputsOf(e);t!==this.meteorScheduleFor&&(this.meteorScheduleFor=t,this.scheduleMeteors(e))}meteorInputsOf(e){const t=e.event.place?.[0],n=e.event.time;return JSON.stringify([t?.lat,t?.lng,n?.year,n?.month,n?.day,n?.hour,n?.minute,e.event.utcOffsetHours,e.event.durationSeconds,e.timeline.duration])}scheduleMeteors(e){const t=e.event.place?.[0],n=e.event.time,i=t?.lat!==void 0&&t.lng!==void 0&&n?.year!==void 0?Ds(n,t.lng,e.event.utcOffsetHours):void 0;if(!i||t?.lat===void 0||t.lng===void 0){this.sceneRenderer.setMeteorShower([],0,0);return}const s={lat:t.lat,lng:t.lng,elevationM:0},a=(e.event.durationSeconds??0)*1e3||e.timeline.duration||2e4,o=Math.round(i.getTime()/1e3)+Math.round(t.lat*1e3),l=Dt.schedule({ratePerHour:Dt.observedRatePerHour(Dt.apexPosition(i,s).altitudeDeg),durationMs:a,velocityKmS:Dt.TYPICAL_VELOCITY_KM_S,seed:o}),c=da.activeAt(i).map(d=>{const u=da.radiantPosition(d.shower,i,s);return{entry:d,position:u,rate:da.observedRatePerHour(d.zhr,u.altitudeDeg,d.shower.populationIndex)}}).sort((d,u)=>u.rate-d.rate)[0];if(!c||c.rate<=0){this.sceneRenderer.setMeteorShower(l,0,0);return}const h=rr.schedule({ratePerHour:c.rate,durationMs:a,velocityKmS:c.entry.shower.velocityKmS,seed:o+1});this.sceneRenderer.setMeteorShower([...h,...l],c.position.altitudeDeg,c.position.azimuthDeg)}meteorByRank(e){this.ensureMeteorSchedule(this.ufoElement.sighting);const t=[...this.sceneRenderer.meteorSchedule].filter(s=>s.t+s.durationMs<=this.ufoElement.seekableDuration).sort((s,a)=>a.brightness-s.brightness);if(t.length===0)return;const n=t[e%t.length],i=this.sceneRenderer.meteorMidpoint(n);if(i)return{t:Math.round(n.t+n.durationMs*.45),...i}}lensOpticsAt(e){const t=this.ufoElement.sighting,n=t.instrument,i=n.frame,s=tt(t,e),a=s?.fNumber??n.fNumber;if(!i||a===void 0)return;const o=rt.focalLengthMmFor(n,ln.fovOf(t,e));if(o!==void 0)return{focalLengthMm:o,fNumber:a,focusDistance:s?.focusDistanceM??0,frameHeightMm:i.heightMm}}projectionAt(e){const t=this.ufoElement.sighting;return oi.of(t.instrument,et.CANVAS_HEIGHT_PX,ln.fovOf(t,e))}sizeEstimateOf(e){let t=this.sizeEstimates.get(e);return t||(t=new HT,this.sizeEstimates.set(e,t)),t}}const Cu="rr0-scene";function eA(){xc(),customElements.get(Cu)||customElements.define(Cu,ff)}class tA{constructor(e,t){this.timeline=e,this.clock=t}currentPointer=null;shapePrototype=null;sourceId="";start(e,t){this.sourceId=e,this.shapePrototype=t,this.currentPointer=null,this.clock.start(n=>this.recordSample(n))}onPointerMove(e,t){this.currentPointer={x:e,y:t}}stop(){this.clock.stop()}recordSample(e){if(!this.currentPointer||!this.shapePrototype)return;const t=$m(this.shapePrototype,this.currentPointer.x,this.currentPointer.y);this.timeline.addKeyframe(e,[{sourceId:this.sourceId,shape:t}])}}class nA{constructor(e){this.intervalMs=e}rafId=null;startTime=0;lastTick=0;start(e){this.startTime=performance.now(),this.lastTick=0;const t=()=>{const n=performance.now()-this.startTime;n-this.lastTick>=this.intervalMs&&(this.lastTick=n,e(n)),this.rafId=requestAnimationFrame(t)};this.rafId=requestAnimationFrame(t)}stop(){this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}}const iA=[{id:"echo",name:{en:"the Echo balloons",fr:"les ballons Echo"},from:"1960-08-12",to:"1969-06-07",peakMagnitude:-1,note:"Echo 1 and 2 were 30- and 40-metre reflective balloons, as bright as the brightest stars and moving slowly enough to be watched — deliberately visible, widely announced in newspapers, and the first objects most people ever saw crossing the night sky. They fall squarely inside the sighting waves this project reconstructs."},{id:"iridium-flares",name:{en:"the Iridium flares",fr:"les flashes d'Iridium"},from:"1997-05-05",to:"2019-12-27",peakMagnitude:-8,note:"The original Iridium satellites carried flat, mirror-finish antennas that threw a sunbeam a few kilometres wide across the ground: a still point of sky flaring to magnitude -8 over five seconds and vanishing again. Nothing else in the sky does that."},{id:"iss",name:{en:"the International Space Station",fr:"la Station spatiale internationale"},from:"1998-11-20",peakMagnitude:-5.9,note:"Since its first module, and much brighter as it grew: at its best it outshines everything in the sky but the Sun and the Moon, crossing in a straight silent line in about four minutes."},{id:"starlink-trains",name:{en:"the Starlink trains",fr:"les trains de Starlink"},from:"2019-05-24",peakMagnitude:1,note:"In the days after a launch, satellites still bunched in their deployment string cross as an evenly spaced line of lights — the most reported 'formation of UFOs' of the era. They spread out within weeks, so a train is a fact about the days after a launch rather than about the year."}],sA=23493,Dm=[2,3,2,1,2,5,4,6,5,6,6,6,6,6,6,6,9,9,9,9,9,9,14,14,15,16,16,16,16,16,18,22,25,24,29,28,29,33,34,35,40,40,42,42,43,46,48,48,49,53,53,54,58,61,70,70,74,78,79,83,92,92,99,97,101,102,109,115,126,125,123,125,127,130,139,153,157,156,161,156,165,174,193,193,201,203,212,215,224,244,255,263,262,281,293,307,312,327,339,336,343,353,359,369,386,396,405,410,421,419,424,434,443,450,460,480,492,504,509,516,519,524,527,530,527,535,543,549,564,571,573,576,582,584,600,600,608,618,625,632,637,642,648,654,661,667,669,667,671,671,697,692,703,697,710,714,724,731,747,755,764,770,782,802,801,815,819,837,846,856,878,881,877,900,906,907,917,932,932,936,954,973,989,986,991,990,1002,1009,1021,1024,1040,1038,1058,1078,1098,1092,1094,1099,1122,1132,1140,1151,1154,1161,1176,1185,1202,1206,1227,1228,1243,1265,1281,1288,1296,1325,1328,1336,1354,1373,1375,1393,1398,1411,1432,1457,1462,1476,1487,1485,1506,1509,1521,1524,1537,1543,1563,1586,1598,1614,1621,1620,1640,1658,1660,1673,1670,1686,1708,1715,1726,1726,1745,1749,1767,1774,1790,1798,1803,1805,1815,1818,1819,1820,1833,1822,1821,1819,1838,1835,1845,1841,1851,1869,1865,1868,1871,1870,1879,1882,1886,1900,1899,1908,1921,1928,1954,1966,1976,1986,1999,2007,2015,2030,2036,2057,2067,2072,2077,2088,2101,2106,2112,2119,2127,2142,2171,2176,2203,2226,2242,2241,2244,2254,2263,2284,2300,2320,2327,2345,2364,2367,2402,2423,2425,2434,2443,2461,2476,2495,2505,2520,2531,2535,2556,2567,2599,2608,2625,2639,2660,2663,2668,2681,2695,2702,2709,2719,2720,2738,2746,2763,2778,2788,2796,2807,2822,2831,2831,2853,2863,2866,2883,2892,2895,2921,2919,2937,2941,2947,2964,2987,2992,2987,2995,3002,3021,3025,3026,3036,3052,3049,3059,3077,3075,3083,3086,3107,3123,3124,3146,3155,3168,3179,3204,3205,3211,3233,3252,3253,3276,3287,3294,3293,3297,3314,3326,3335,3338,3355,3362,3358,3365,3364,3376,3375,3382,3418,3429,3432,3455,3463,3483,3490,3502,3509,3521,3532,3542,3544,3553,3571,3580,3588,3596,3603,3633,3639,3649,3655,3660,3670,3699,3699,3707,3723,3747,3752,3754,3766,3772,3778,3781,3798,3815,3814,3824,3832,3853,3859,3879,3885,3899,3912,3910,3924,3937,3951,3951,3961,3963,3961,3976,3977,3988,4004,4018,4025,4047,4074,4086,4108,4133,4136,4159,4168,4182,4192,4200,4215,4230,4239,4257,4678,4698,4694,4713,4719,4739,4750,4756,4764,4771,4788,4792,4790,4809,4821,4829,4834,4836,4843,4853,4863,4872,4881,4890,4898,4901,4897,4895,4884,4886,4886,4894,4897,4905,4905,4909,4907,4925,4918,4920,4929,4925,4928,4936,4943,4944,4951,4955,4952,4974,4976,4975,4981,4994,4997,5022,5023,5032,5043,5048,5051,5066,5062,5068,5075,5082,5082,5098,5102,5110,5113,5119,5123,5138,5138,5145,5149,5157,5165,5166,5169,5178,5183,5190,5192,5203,5204,5207,5214,5228,5234,5245,5249,5256,5262,5275,5278,5305,5303,5315,5321,5348,5358,5369,5369,5372,5385,5402,5409,5427,5429,5429,5439,5456,5464,5481,5485,5494,5509,5520,5526,5543,5555,5568,5575,5585,5596,5602,5620,5627,5644,5647,5660,5678,5680,5684,5692,5700,5711,5727,5733,5736,5756,5776,5797,5805,5804,5807,5800,5808,5814,5822,5839,5856,5869,5889,5902,5919,5921,5936,5937,5936,5957,5961,5975,5981,6002,6015,6027,6035,6042,6059,6062,6080,6081,6092,6097,6106,6127,6129,6198,6227,6231,6243,6249,6262,6255,6279,6304,6315,6326,6330,6334,6361,6358,6359,6379,6381,6389,6388,6404,6404,6443,6465,6473,6497,6500,6513,6524,6532,6538,6578,6572,6576,6584,6582,6608,6639,6656,6761,6764,6768,6772,6836,6905,6916,6925,6951,6984,7009,7072,7092,7110,7122,7140,7148,7170,7168,7180,7194,7247,7374,7391,7393,7382,7425,7485,7530,7568,7587,7602,7602,7715,7771,7900,8004,8103,8153,8162,8296,8319,8437,8566,8746,8860,8913,9128,9275,9585,9739,10014,10123,10167,10203,10288,10323,10398,10544,10721,10883,11044,11157,11442,11515,11787,12070,12269,12468,12484,12619,12883,13008,13264,13317,13549,13859,14049,14175,14360,14498,14687,14843,14984,15093,15279,15431,15623,15741,15788,15966,16025,16132,16419,16568,16791,16892,17060,17269,17598,17959,18194,18482,18804,19136,19564,19990,20249,20509,20943,21248,21539,21845,22196,22412];class Mi{static FIRST_ORBIT="1957-10-04";static EARTH_RADIUS_KM=6371;static LOW_ORBIT_KM=500;static shadowHeightKm(e){if(e>=0)return 0;const t=-e*Math.PI/180;return Mi.EARTH_RADIUS_KM*(1/Math.cos(t)-1)}static isLitOverhead(e,t){return e>Mi.shadowHeightKm(t)}static classesAt(e){const t=e.getTime();return iA.filter(n=>{const i=Date.parse(`${n.from}T00:00:00Z`),s=n.to===void 0?1/0:Date.parse(`${n.to}T23:59:59Z`);return t>=i&&t<=s})}static trackedInOrbitAt(e){const t=e.getUTCFullYear()*12+e.getUTCMonth()-sA;if(!(t<0))return Dm[Math.min(t,Dm.length-1)]}static visibilityAt(e,t){const n=Cn("Sun",e,t).altitudeDeg;return{sunAltitudeDeg:n,shadowHeightKm:Mi.shadowHeightKm(n),lowOrbitLit:Mi.isLitOverhead(Mi.LOW_ORBIT_KM,n),classes:Mi.classesAt(e),trackedObjects:Mi.trackedInOrbitAt(e),anythingInOrbit:e.getTime()>=Date.parse(`${Mi.FIRST_ORBIT}T00:00:00Z`)}}}const rA={en:["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"],fr:["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSO","SO","OSO","O","ONO","NO","NNO"]};class _s{static POINT_DEG=360/16;static point(e,t){const n=(e%360+360)%360,i=Math.round(n/_s.POINT_DEG)%16;return rA[t][i]}static towards(e,t){const n=_s.point(e,t);return t==="en"?`to the ${n}`:aA.test(n)?`à l'${n}`:`au ${n}`}}const aA=/^[EO]/;class it{static COARSE_STEP_DEG=10;static FINE_STEP_DEG=2;static FINE_SPAN_DEG=10;static LOWEST_DEG=5;static THRESHOLD_CONTRAST=.5;static CONE_SEPARATION_DEG=60;galaxy=new je;dust=new It;assess(e,t){const n=Cn("Sun",e,t),i=Cn("Moon",e,t),s={altitudeDeg:i.altitudeDeg,phaseAngleDeg:Xe.phaseAngleOf(vc(e).illuminatedFraction)},a=Gn.galactic(e,t),o=it.unit(a.centre),l=it.unit(a.rotation),c=it.unit(a.pole),h=it.unit(Gn.eclipticPole(e,t)),d=it.unit(n),u=it.unit(i),f=it.normalize(it.reject(d,h));let p,v,m=0;const g=(M,x)=>{const w=it.unit({altitudeDeg:M,azimuthDeg:x}),S=it.between(w,d),E=Xe.magPerArcsec2({altitudeDeg:n.altitudeDeg,separationDeg:S},{...s,separationDeg:it.between(w,u)},M);E>m&&(m=E);const D=ns.fromMagPerArcsec2(E),y=10**(-.4*Xe.EXTINCTION_PER_AIR_MASS*(Xe.airMass(M)-1)),T=this.galaxy.surfaceBrightnessS10(Math.atan2(it.dot(w,l),it.dot(w,o))*180/Math.PI,Math.asin(Math.max(-1,Math.min(1,it.dot(w,c))))*180/Math.PI)*y;p=it.better(p,T,D,E,M,x,S);const A=Math.max(-1,Math.min(1,it.dot(w,h))),I=it.normalize(it.reject(w,h)),R=this.dust.surfaceBrightnessS10(it.between(I,f),Math.asin(A)*180/Math.PI)*y;v=it.better(v,R,D,E,M,x,S)};for(let M=it.LOWEST_DEG;M<=90;M+=it.COARSE_STEP_DEG)for(let x=0;x<360;x+=it.COARSE_STEP_DEG)g(M,x);for(const M of[p,v]){if(!M)continue;const x=it.FINE_SPAN_DEG,w=it.FINE_STEP_DEG;for(let S=M.altitudeDeg-x;S<=M.altitudeDeg+x;S+=w)if(!(S<it.LOWEST_DEG||S>90))for(let E=M.azimuthDeg-x;E<=M.azimuthDeg+x;E+=w)g(S,(E+360)%360)}return{milkyWay:p&&p.contrast>=it.THRESHOLD_CONTRAST?p:void 0,zodiacal:v&&v.contrast>=it.THRESHOLD_CONTRAST?v:void 0,darkestSkyMagPerArcsec2:m}}static better(e,t,n,i,s,a,o){const l=t/n;return e&&e.contrast>=l?e:{contrast:l,altitudeDeg:s,azimuthDeg:a,magPerArcsec2:ns.toMagPerArcsec2(t),skyMagPerArcsec2:i,sunSeparationDeg:o}}static unit(e){const t=e.altitudeDeg*Math.PI/180,n=e.azimuthDeg*Math.PI/180,i=Math.cos(t);return[i*Math.sin(n),Math.sin(t),-i*Math.cos(n)]}static dot(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}static between(e,t){return Math.acos(Math.max(-1,Math.min(1,it.dot(e,t))))*180/Math.PI}static reject(e,t){const n=it.dot(e,t);return[e[0]-n*t[0],e[1]-n*t[1],e[2]-n*t[2]]}static normalize(e){const t=Math.hypot(...e)||1;return[e[0]/t,e[1]/t,e[2]/t]}}const oA=.5,Pl=40,lA=4e5,Ws=Math.PI/180,Gr=180/Math.PI;class Fn{static localDirection(e,t,n,i=new P){const s=Math.tan(t/2*Ws);return i.set((e.u*2-1)*s*n,(1-e.v*2)*s,-1).normalize()}static picturePoint(e,t,n){if(e.z>=0)return;const i=Math.tan(t/2*Ws),s=e.x/-e.z/(i*n),a=e.y/-e.z/i;return{u:(s+1)/2,v:(1-a)/2}}static worldDirection(e,t=new P){const n=e.azimuthDeg*Ws,i=e.altitudeDeg*Ws;return t.set(Math.sin(n)*Math.cos(i),Math.sin(i),-Math.cos(n)*Math.cos(i))}static aimOf(e){const t=Math.hypot(e.x,e.z);return{azimuthDeg:(Math.atan2(e.x,-e.z)*Gr+360)%360,altitudeDeg:Math.atan2(e.y,t)*Gr}}static rotationOf(e){const t=new xt;return t.rotation.set(e.pitchDeg*Ws,-e.headingDeg*Ws,-(e.rollDeg??0)*Ws,"YXZ"),t.quaternion.clone()}static anglesOf(e){const t=new Fi().setFromQuaternion(e,"YXZ"),n=(-t.y*Gr%360+360)%360,i=-t.z*Gr;return{headingDeg:n,pitchDeg:t.x*Gr,rollDeg:Math.abs(i)<1e-9?0:i}}static worldDirectionOf(e,t,n,i=new P){return this.localDirection(e,t.fovDeg,n,i).applyQuaternion(this.rotationOf(t))}static picturePointOf(e,t,n){const i=e.clone().applyQuaternion(this.rotationOf(t).invert()),s=this.picturePoint(i,t.fovDeg,n);if(!(!s||s.u<0||s.u>1||s.v<0||s.v>1))return s}static solve(e,t,n,i=e.length>=3){if(e.length<2)return;if(!i)return this.solveAtField(e,t,n);let s=1,a=179;const o=(Math.sqrt(5)-1)/2;let l=a-o*(a-s),c=s+o*(a-s),h=this.solveAtField(e,t,l),d=this.solveAtField(e,t,c);for(let f=0;f<60&&a-s>1e-4;f++){if(!h||!d)return;h.residualDeg<d.residualDeg?(a=c,c=l,d=h,l=a-o*(a-s),h=this.solveAtField(e,t,l)):(s=l,l=c,h=d,c=s+o*(a-s),d=this.solveAtField(e,t,c))}return h&&d?h.residualDeg<d.residualDeg?h:d:h??d}static solveAtField(e,t,n){const i=e.map(c=>this.localDirection(c.picture,n,t)),s=e.map(c=>this.worldDirection(c.scene)),a=this.triad(i,s);if(!a)return;const o=this.refine(a,i,s);return{registration:{...this.anglesOf(o),fovDeg:n},residualDeg:this.residualDeg(o,i,s)}}static triad(e,t){let n=0,i=1,s=-1;for(let h=0;h<e.length;h++)for(let d=h+1;d<e.length;d++){const u=e[h].clone().cross(e[d]).lengthSq();u>s&&(s=u,n=h,i=d)}if(s<1e-12)return;const a=(h,d)=>{const u=h.clone().normalize(),f=h.clone().cross(d).normalize(),p=f.clone().cross(u);return new Be().set(u.x,p.x,f.x,u.y,p.y,f.y,u.z,p.z,f.z)},o=a(e[n],e[i]),c=a(t[n],t[i]).multiply(o.transpose());return new Oi().setFromRotationMatrix(new Ve().setFromMatrix3(c))}static refine(e,t,n){const i=e.clone(),s=new P;for(let a=0;a<20;a++){const o=new Be().set(0,0,0,0,0,0,0,0,0),l=o.elements,c=new P;for(let f=0;f<t.length;f++){s.copy(t[f]).applyQuaternion(i);const p=s,v=[[0,p.z,-p.y],[-p.z,0,p.x],[p.y,-p.x,0]],m=[n[f].x-p.x,n[f].y-p.y,n[f].z-p.z];for(let g=0;g<3;g++){for(let M=0;M<3;M++)for(let x=0;x<3;x++)l[M*3+g]+=v[x][g]*v[x][M];c.setComponent(g,c.getComponent(g)+v[0][g]*m[0]+v[1][g]*m[1]+v[2][g]*m[2])}}for(let f=0;f<3;f++)l[f*3+f]+=1e-9;const h=c.applyMatrix3(o.invert()),d=h.length();if(d<1e-12)break;const u=new Oi().setFromAxisAngle(h.normalize(),d);if(i.premultiply(u).normalize(),d<1e-10)break}return i}static residualDeg(e,t,n){let i=0;const s=new P;for(let a=0;a<t.length;a++){s.copy(t[a]).applyQuaternion(e);const o=s.angleTo(n[a])*Gr;i+=o*o}return Math.sqrt(i/t.length)}}const Cm=6371e3,Va=Math.PI/180;class ea{constructor(e=t=>fetch(t).then(n=>{if(!n.ok)throw new Error(`${t}: HTTP ${n.status}`);return n.json()})){this.fetchJson=e}static API="https://api.panoramax.xyz/api";static CREDIT="Panoramax";static CREDIT_URL="https://panoramax.fr/";async nearby(e,t,n=300,i=50){const s=n/111320,a=n/(111320*Math.cos(e*Va)),o=[t-a,e-s,t+a,e+s].map(h=>h.toFixed(6)).join(",");return((await this.fetchJson(`${ea.API}/search?bbox=${o}&limit=${i}`)).features??[]).map(h=>this.picture(h,e,t)).filter(h=>h!==void 0&&h.distanceM<=n).sort((h,d)=>h.distanceM-d.distanceM)}picture(e,t,n){const[i,s]=e.geometry.coordinates,a=e.assets.sd?.href??e.assets.hd?.href;if(!a)return;const{distanceM:o,bearingDeg:l}=ea.offset(t,n,s,i),c=e.properties,h=c["pers:interior_orientation"]?.field_of_view,d=(c.providers??[]).map(f=>f.name).filter(f=>!!f),u=c.license??"CC-BY-SA-4.0";return{id:e.id,lat:s,lng:i,distanceM:o,bearingDeg:l,azimuthDeg:c["view:azimuth"],panorama:h!==void 0&&h>=360,takenAt:c.datetime??"",src:a,srcFull:e.assets.hd?.href,credit:`${ea.CREDIT}${d.length?` — ${d.join(", ")}`:""} (${u})`,creditUrl:`${ea.API.replace(/\/api$/,"")}/#focus=pic&pic=${e.id}`}}static offset(e,t,n,i){const s=(n-e)*Va*Cm,a=(i-t)*Va*Cm*Math.cos((e+n)/2*Va);return{distanceM:Math.hypot(a,s),bearingDeg:(Math.atan2(a,s)/Va+360)%360}}}const Ll=36e5,Rm=25;class Yh{constructor(e){this.provider=e}async infer(e){const t=this.questionOf(e);if(!t)return{status:"incomplete"};const{origin:n,start:i}=t,s=ua(e.event)??0,a=this.sampleTimings(e,i,s);let o;try{o=await this.provider.getWeather({points:a.map(l=>this.pointAt(e,l,n))})}catch{return{status:"failed",at:i}}return o?{status:"inferred",at:i,source:o.source,keyframes:o.samples.map((l,c)=>({t:a[c].t,weather:l.weather}))}:{status:"unavailable",at:i}}applyTo(e,t){if(!(t.status!=="inferred"||!t.keyframes||!t.source)){e.weatherTrack.clear();for(const n of t.keyframes)e.weatherTrack.addKeyframe(n.t,n.weather);e.weatherSource=t.source}}sampleTimes(e,t){const n=[e],i=e.getTime()+t;let s=Math.floor(e.getTime()/Ll)*Ll+Ll;for(;s<=i&&n.length<Rm;)n.push(new Date(s)),s+=Ll;return t>0&&n[n.length-1].getTime()!==i&&n.length<Rm&&n.push(new Date(i)),n}sampleTimings(e,t,n){const i=e.timeline.duration>0?e.timeline.duration:n;return n<=0||i<=0?[{time:t,t:0}]:this.sampleTimes(t,n).map(s=>{const a=(s.getTime()-t.getTime())/n;return{time:s,t:Math.round(i*Math.max(0,Math.min(1,a)))}})}canInfer(e){return this.questionOf(e)!==void 0}questionOf(e){const t=this.originOf(e);if(!t)return;const n=e.event.time;if(n?.year===void 0||n.month===void 0||n.day===void 0)return;const i=Ds(n,t.lng,e.event.utcOffsetHours);return i?{origin:t,start:i}:void 0}originOf(e){const t=tt(e,0),n=e.event.place?.[0],i=t?.lat??n?.lat,s=t?.lng??n?.lng;return i===void 0||s===void 0?void 0:{lat:i,lng:s}}pointAt(e,t,n){const i=tt(e,t.t);return{lat:i?.lat??n.lat,lng:i?.lng??n.lng,time:t.time}}}const cA=Date.UTC(1940,0,1),Pm=36e5,Lm=.25,hA=.7,dA=.45,uA=.1,fA=2,pA=.3,mA=.2,gA=8,$h=.125,vA=.05,km=125,Nm=100,Om=2500,Kh=3500,Zh=8e3,yA=95,bA=99,wA=[96,99],xA=["cloud_cover","cloud_cover_low","cloud_cover_mid","cloud_cover_high","precipitation","snowfall","weather_code","wind_speed_10m","wind_direction_10m","temperature_2m","dew_point_2m"];class Lv{fetchImpl;baseUrl;cache=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.baseUrl=e.baseUrl??"https://archive-api.open-meteo.com/v1/archive"}async getWeather(e){if(e.points.length===0)return;const t=e.points.map(f=>f.time.getTime()),n=Math.min(...t);if(n<cA)return;const i=new Map;for(const f of e.points){const p=this.cellKey(f);i.has(p)||i.set(p,{lat:f.lat,lng:f.lng,index:i.size})}const s=this.requestUrl([...i.values()],new Date(n),new Date(Math.max(...t))),a=this.cache.get(s);if(a)return a;const o=await this.fetchImpl(s);if(!o.ok)throw new Error(`Open-Meteo HTTP ${o.status}`);const l=await o.json(),c=Array.isArray(l)?l:[l];if(c.length<i.size||c.some(f=>f.error||!f.hourly))return;const h={id:"era5",name:"ERA5 (Open-Meteo)",url:s},d=e.points.map(f=>this.sampleAt(c[i.get(this.cellKey(f)).index].hourly,f.time));if(d.some(f=>f===void 0))return;const u={samples:d,source:h};return this.cache.set(s,u),u}cellKey(e){return`${Math.round(e.lat/Lm)},${Math.round(e.lng/Lm)}`}requestUrl(e,t,n){const i=new URLSearchParams({latitude:e.map(s=>s.lat).join(","),longitude:e.map(s=>s.lng).join(","),start_date:this.isoDate(t),end_date:this.isoDate(n),hourly:xA.join(","),wind_speed_unit:"ms",timezone:"UTC"});return`${this.baseUrl}?${i}`}isoDate(e){return e.toISOString().slice(0,10)}sampleAt(e,t){const n=this.recordAt(e,t);return n&&{time:t,weather:this.toWeather(n)}}recordAt(e,t){const n=e.time.map(o=>Date.parse(`${o}Z`)),i=t.getTime();if(n.length===0||i<n[0]-Pm||i>n[n.length-1]+Pm)return;if(i<=n[0])return this.recordFrom(e,0);if(i>=n[n.length-1])return this.recordFrom(e,n.length-1);let s=0;for(;s+1<n.length&&n[s+1]<=i;)s++;const a=n[s+1]-n[s];return this.blendRecords(this.recordFrom(e,s),this.recordFrom(e,s+1),a>0?(i-n[s])/a:0)}recordFrom(e,t){const n={cloudCover:e.cloud_cover[t]/100,cloudCoverLow:e.cloud_cover_low[t]/100,cloudCoverMid:e.cloud_cover_mid[t]/100,cloudCoverHigh:e.cloud_cover_high[t]/100,precipitationMm:e.precipitation[t],snowfallCm:e.snowfall[t],weatherCode:e.weather_code[t],windSpeedMs:e.wind_speed_10m[t],windFromDeg:e.wind_direction_10m[t],temperatureC:e.temperature_2m[t],dewPointC:e.dew_point_2m[t]};return Object.values(n).some(i=>i===void 0||Number.isNaN(i))?void 0:n}blendRecords(e,t,n){if(!e||!t)return e??t;const i=(a,o)=>a+(o-a)*n,s=((t.windFromDeg-e.windFromDeg)%360+540)%360-180;return{cloudCover:i(e.cloudCover,t.cloudCover),cloudCoverLow:i(e.cloudCoverLow,t.cloudCoverLow),cloudCoverMid:i(e.cloudCoverMid,t.cloudCoverMid),cloudCoverHigh:i(e.cloudCoverHigh,t.cloudCoverHigh),precipitationMm:i(e.precipitationMm,t.precipitationMm),snowfallCm:i(e.snowfallCm,t.snowfallCm),weatherCode:n<.5?e.weatherCode:t.weatherCode,windSpeedMs:i(e.windSpeedMs,t.windSpeedMs),windFromDeg:((e.windFromDeg+s*n)%360+360)%360,temperatureC:i(e.temperatureC,t.temperatureC),dewPointC:i(e.dewPointC,t.dewPointC)}}cloudLayersFrom(e){return[{id:"record-low",type:"unknown",baseM:Math.round(this.clamp(km*(e.temperatureC-e.dewPointC),Nm,Om)),thicknessM:650,coverage:this.clamp(e.cloudCoverLow,0,1),sizeM:1400,density:1},{id:"record-mid",type:"unknown",baseM:Kh,thicknessM:800,coverage:this.clamp(e.cloudCoverMid,0,1),sizeM:2500,density:1},{id:"record-high",type:"cirrus",baseM:Zh,thicknessM:400,coverage:this.clamp(e.cloudCoverHigh,0,1),sizeM:2200,density:.35}]}toWeather(e){const t=e.weatherCode>=yA&&e.weatherCode<=bA,n=this.precipitationTypeFrom(e);return{cloudLayers:this.cloudLayersFrom(e),cloudCover:this.clamp(e.cloudCover,0,1),cloudDarkness:this.cloudDarknessFrom(e,t),cloudBaseM:this.cloudBaseFrom(e),highCloudCover:e.cloudCoverHigh,lowerCloudCover:Math.max(e.cloudCoverLow,e.cloudCoverMid),precipitationType:n,precipitationIntensity:n==="none"?0:this.clamp(Math.sqrt(e.precipitationMm/gA),0,1),windDirectionDeg:(e.windFromDeg+180)%360,windSpeed:e.windSpeedMs,storm:t}}precipitationTypeFrom(e){return e.snowfallCm>0?"snow":wA.includes(e.weatherCode)?"hail":e.precipitationMm>0?"rain":"none"}cloudDarknessFrom(e,t){const n=e.cloudCoverLow+e.cloudCoverMid+e.cloudCoverHigh;if(n<=0)return 0;const i=(hA*e.cloudCoverLow+dA*e.cloudCoverMid+uA*e.cloudCoverHigh)/n,s=Math.min(1,e.precipitationMm/fA);return this.clamp(i+pA*s+(t?mA:0),0,1)}cloudBaseFrom(e){if(e.cloudCover<vA)return;const t=this.clamp(km*(e.temperatureC-e.dewPointC),Nm,Om);if(e.cloudCoverLow>=$h)return Math.round(t);if(e.cloudCoverMid>=$h)return Kh;if(e.cloudCoverHigh>=$h)return Zh;const n=Math.max(e.cloudCoverLow,e.cloudCoverMid,e.cloudCoverHigh);if(!(n<=0))return n===e.cloudCoverLow?Math.round(t):n===e.cloudCoverMid?Kh:Zh}clamp(e,t,n){return Math.max(t,Math.min(n,e))}}function MA(){return new Lv}const SA=5;class kv{attribution={text:"© OpenStreetMap",url:"https://osm.org/copyright"};fetchImpl;baseUrl;reverseUrl;cache=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.baseUrl=e.baseUrl??"https://nominatim.openstreetmap.org/search",this.reverseUrl=e.reverseUrl??"https://nominatim.openstreetmap.org/reverse"}async reverse(e,t,n={}){const i=new URLSearchParams({lat:String(e),lon:String(t),format:"jsonv2"});n.language&&i.set("accept-language",n.language);const s=`${this.reverseUrl}?${i}`,a=this.cache.get(s);if(a)return a[0];const o=await this.fetchImpl(s,{signal:n.signal});if(!o.ok)throw new Error(`Nominatim HTTP ${o.status}`);const l=await o.json(),c=l.error?void 0:this.toMatch(l);return this.cache.set(s,c?[c]:[]),c}async search(e,t={}){const n=e.trim();if(n==="")return[];const i=this.requestUrl(n,t),s=this.cache.get(i);if(s)return s;const a=await this.fetchImpl(i,{signal:t.signal});if(!a.ok)throw new Error(`Nominatim HTTP ${a.status}`);const o=await a.json(),l=(Array.isArray(o)?o:[]).map(c=>this.toMatch(c)).filter(c=>c!==void 0);return this.cache.set(i,l),l}requestUrl(e,t){const n=new URLSearchParams({q:e,format:"jsonv2",limit:String(t.limit??SA)});return t.language&&n.set("accept-language",t.language),`${this.baseUrl}?${n}`}toMatch(e){const t=e.display_name??e.name,n=this.coordinate(e.lat),i=this.coordinate(e.lon);return t&&n!==void 0&&i!==void 0?{name:t,lat:n,lng:i}:void 0}coordinate(e){if(e===void 0||e.trim()==="")return;const t=Number(e);return Number.isFinite(t)?t:void 0}}function _A(){return new kv}const EA=[{id:"nominatim",name:"Nominatim",credit:"© OpenStreetMap",creditUrl:"https://osm.org/copyright",create:()=>new kv}],TA=[{id:"era5",name:"ERA5 (Open-Meteo)",credit:"© Copernicus/ECMWF",creditUrl:"https://open-meteo.com/en/docs/historical-weather-api",create:()=>new Lv}];class AA{attribution;fetchImpl;tileUrlTemplate;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis);const t=e.year??2024;this.tileUrlTemplate=`https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-${t}_3857/default/g/{z}/{y}/{x}.jpg`,this.attribution=`EOxCloudless https://cloudless.eox.at by EOX IT Services GmbH (Contains modified Copernicus Sentinel data ${t})`}async getImageryTexture(e,t){return ag(e,t,n=>this.tileUrlTemplate.replace("{z}",String(n.z)).replace("{y}",String(n.y)).replace("{x}",String(n.x)),this.fetchImpl)}}const jh=[{id:"aws-terrarium",name:"AWS Terrain Tiles",credit:"© AWS Open Data (SRTM, ETOPO1)",creditUrl:"https://registry.opendata.aws/terrain-tiles/",create:()=>new rg}],Fm=[{id:"esri-world",name:"Esri World Imagery",credit:"Imagery © Esri, Maxar, Earthstar Geographics, and the GIS User Community",creditUrl:"https://www.arcgis.com/home/item.html?id=10df2279f9684e4a9f6a7f08febac2a9",create:()=>new og},{id:"eox-s2cloudless",name:"EOX Sentinel-2 cloudless",credit:"EOxCloudless by EOX IT Services GmbH (contains modified Copernicus Sentinel data)",creditUrl:"https://cloudless.eox.at",create:()=>new AA}];class pf{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const n=pf.SPAN_DEG;try{const s=(await this.provider.getElevationGrid({south:e-n,north:e+n,west:t-n,east:t+n},{width:2,height:2})).heights[0];return Number.isFinite(s)?s:void 0}catch{return}}}class IA{available(){const e=Intl.supportedValuesOf;return e?[...e.call(Intl,"timeZone")].sort():[]}offsetHoursAt(e,t){if(t.year===void 0)return;const n=Date.UTC(t.year,(t.month??1)-1,t.day??1,t.hour??12,t.minute??0,t.second??0),i=this.zoneOffsetHours(e,new Date(n));if(i!==void 0)return this.zoneOffsetHours(e,new Date(n-i*36e5))??i}zoneOffsetHours(e,t){let n;try{n=new Intl.DateTimeFormat("en-US",{timeZone:e,timeZoneName:"longOffset"}).formatToParts(t).find(s=>s.type==="timeZoneName")?.value??""}catch{return}const i=/^GMT(?:([+-])(\d{2}):(\d{2}))?$/.exec(n);if(i)return i[1]?(i[1]==="-"?-1:1)*(Number(i[2])+Number(i[3])/60):0}}function Wr(r,e){return r.find(t=>t.id===e)??r[0]}class DA{constructor(e="https://api.open-meteo.com/v1/forecast"){this.endpoint=e}async zoneAt(e,t){const n=new URL(this.endpoint);n.searchParams.set("latitude",String(e)),n.searchParams.set("longitude",String(t)),n.searchParams.set("timezone","auto"),n.searchParams.set("forecast_days","1");try{const i=await fetch(n.toString());if(!i.ok)return;const s=await i.json();return s.timezone&&s.timezone!=="GMT"?s.timezone:void 0}catch{return}}}const CA=[{id:"open-meteo",name:"Open-Meteo",credit:"© Open-Meteo",creditUrl:"https://open-meteo.com/en/docs",create:()=>new DA}],RA={color:"Color",transparency:"Transparency",halo:"Halo",blur:"Blur",brightness:"Brilliance",shapeTitle:"Name",utcOffset:"Time zone",cloudBase:"Cloud base",elevation:"Altitude",heightAboveGround:"Height above ground",duration:"Duration",placeName:"Place",latitude:"Latitude",longitude:"Longitude",heading:"Heading",pitch:"Tilt",roll:"Roll",observationTime:"Observation start",observationEndTime:"Observation end",assessmentGroup:"Assessment",assessmentNames:{coverage:"Witness info"},assessmentVerdicts:{"hynek.nl":"NL — nocturnal light","hynek.dd":"DD — daylight disc","hynek.rv":"RV — radar-visual","hynek.ce1":"CE1 — close encounter","hynek.ce2":"CE2 — with a physical trace","hynek.ce3":"CE3 — with entities"},witnessGroup:"Witness",witnessId:"ID",witnessTitle:"Title",witnessLastName:"Last name",witnessFirstNames:"First names",caseId:"Case ID",tags:"Tags",cloudCover:"Cloud cover",highCloudCover:"Ice cloud (cirrus)",focalLength:"Focal length",fieldOfView:"Field of view",aperture:"Aperture",exposure:"Exposure",focusDistance:"Focused at",iceCrystalAlignment:"Crystal alignment",cloudDarkness:"Cloud darkness",precipitationType:"Precipitation",precipitationNone:"None",precipitationRain:"Rain",precipitationSnow:"Snow",precipitationHail:"Hail",precipitationIntensity:"Intensity",windDirection:"Wind direction",windSpeed:"Wind speed",storm:"Storm",cloudsGroup:"Clouds",precipitationGroup:"Precipitation",windGroup:"Wind",soundKind:"Sound",soundNone:"None (silent)",soundHum:"Hum",soundWhistle:"Whistle",soundRumble:"Rumble",soundCrackle:"Crackle",soundVolume:"Loudness",soundPitch:"Pitch",soundSrc:"Recording",instrument:"Observed through",decorAircraft:"Aircraft",decorEntity:"Being",decorAltitude:"Altitude",decorLights:"Lights",decorLightsNone:"none",decor:"Environment",decorBuilding:"Building",decorTree:"Tree",decorCrop:"Crop row",decorMound:"Stone heap",decorStreetlight:"Streetlight",decorVehicle:"Vehicle",decorWitness:"Other witness",decorEast:"Distance east",decorNorth:"Distance north",decorHeading:"Heading",decorColor:"Colour",decorLit:"Lit",decorTitle:"Name",milestones:"Moments",milestoneLabel:"Label",milestoneNote:"What happens",addMilestone:"Name this moment",deleteMilestone:"Delete moment",confirmAccept:"Delete",confirmDecline:"Cancel",decorWidth:"Width",decorLength:"Length",decorHeight:"Height",decorModel:"3D model",decorModelNone:"Built-in shape",decorModelAdvanced:"Model from an address",decorModelUrl:"glTF/GLB address",decorModelTitle:"Model name",decorModelAuthor:"Author",decorModelLicense:"Licence",decorModelSource:"Where it came from",decorFloors:"Floors",decorOccupiedFloor:"Occupied floor",decorWitnessSide:"Witness location",decorWitnessSideNone:"Not present",decorWindows:"Windows",decorSideFront:"Front",decorSideBehind:"Behind",decorSideLeft:"Left",decorSideRight:"Right",decorSideFrontLeft:"Front-left",decorSideFrontRight:"Front-right",decorSideBehindLeft:"Behind-left",decorSideBehindRight:"Behind-right"},Nv={...RA,oval:"Oval",polygon:"Polygon",addVertex:"Add vertex",deleteVertex:"Delete vertex",notAPolygon:"Select a single polygon shape",tooFewVertices:"A shape needs at least 3 points",shape:"Shape",apparentWidth:"Apparent width",realWidth:"Real width",distance:"Distance",sizeLock:"Hold",lockNone:"nothing",lockApparent:"the apparent width",lockReal:"the real width",lockDistance:"the distance",apparentSize:"{moons}× the Moon",utcOffsetPlaceholder:"from longitude",realSizeBetween:"The scene bounds that width: between {min} and {max} m, from what it crosses",realSizeAtLeast:"The scene bounds that width: at least {min} m, from what it passes behind",realSizeAtMost:"The scene bounds that width: at most {max} m, from what it passes in front of",realSizeUnknown:"Nothing in the scene bounds that width: it is only what the distance implies",realSizeOutside:" — the width above is outside that",blurBound:"Blurred through this lens: nearer than {max} m",blurBoundNoInstrument:"Blur through the naked eye bounds no distance — an eye has no aperture to be out of focus with",blurBoundNotAtInfinity:"Blur bounds a distance only for a lens focused at infinity: this one is focused at {focus} m, which blurs on both sides of it",realSizeContradiction:"Contradiction: the declared crossings cannot all be true",realDistanceHere:" — i.e. between {min} and {max} m here",clearDistanceHypothesis:"Withdraw the distance hypothesis",clearDistanceHypothesisTitle:"Back to what the recording establishes",depthStated:"Drawn at {m} m, as the recording states",depthHypothesis:"Drawn at {m} m: your hypothesis — what the decor hides of it is what a thing that far would lose",depthDerived:"Drawn at {m} m, from the witness's own walk",depthBounded:"Drawn at {m} m, from what it passes behind and in front of",depthConventional:"Drawn at {m} m by convention: nothing in the recording establishes a distance",addShape:"Add shape",deleteShape:"Delete shape",play:"Play",pause:"Pause",noDuration:"No observation duration",autoReplay:"Auto-replay",group:"Group",ungroup:"Ungroup",bringToFront:"Bring to front",sendToBack:"Send to back",contextMenuDelete:"Delete",confirmDeleteShape:"Delete {name}? This can't be undone.",confirmDeleteShapes:"Delete {count} shapes? This can't be undone.",confirmDeleteMilestone:"Stop naming moment {name}? The recording itself is unchanged.",onlyOneShape:"There is only one shape",alreadyAtFront:"This shape is already at the front",alreadyAtBack:"This shape is already at the back",needTwoShapesToGroup:"Select at least two shapes to group them",notGrouped:"This shape isn't part of a group",multipleShapesSelected:"Multiple shapes selected — select just one to edit this",samplingRate:"Sampling rate",currentPosition:"Current position",switchToElapsed:"click to show elapsed time",switchToClockTime:"click to show the time of day",durationPlaceholder:"observation length",durationImprecise:"These dates don't precisely enough determine a duration — enter it manually.",export:"Export",importFile:"Load JSON file",importUrl:"Or load from URL",importUrlPlaceholder:"https://…/sighting.json",importButton:"Load",importError:"Couldn't load that recording — check the file or URL and try again.",importErrorCors:'That address answers, but the browser is not allowed to read it from this page. The file itself is fine — its server needs to send the header "Access-Control-Allow-Origin: *" with it. If it is not your server, that is what to ask its administrator for.',importErrorMixedContent:"A secure page cannot load an address starting with http://. Use https:// if that server offers it.",importErrorUnreachable:"Nothing answered at that address. Check the spelling, and that you are online.",importErrorStatus:"That server answered with an error ({status}). The address is probably wrong, or the file has moved.",importErrorMalformed:"That address answered, but what came back is not a recording.",record:"Record",stop:"Stop",according:"according to",sourceElevation:"Relief",sourceImagery:"Imagery",placeNamePlaceholder:"Valensole, France",searchPlace:"Locate",placeMatch:"Matches",placeSearching:"Looking up the place…",placeMatchFound:"place found",placeMatchesFound:"places found",placeNotFound:"No place by that name",placeSearchFailed:"Place search temporarily unavailable",utcOffsetImplausible:"This time zone doesn't match the longitude entered, whose own solar time is UTC{solar} — yet the scene and the weather record both obey what is declared here. Clear the field to derive it from the longitude.",timeZoneManual:"offset entered",altitudeAboveSeaLevel:"The witness's altitude above sea level — the ground at the location entered sets its floor: a witness in the Alps is not at 0 m.",groundAt:"ground at {m} m",headingPlaceholder:"unknown",edtfInvalid:"Not a valid EDTF date/time (e.g. 1965-07-01T05:00, 2025-06?, 2025~).",edtfPlaceholder:"YYYY-MM-DDThh:mm[?~%] or hh:mm",observationTimeHint:"EDTF — e.g. 1965-07-01T05:00, 2025-06? (uncertain), 2025~ (approximate), or just 05:00 if the date isn't known",observationEndTimeHint:"EDTF — e.g. 1965-07-01T05:10, 2025-06? (uncertain), 2025~ (approximate), or just 05:10 if the date isn't known",presetsGroupLabel:"UFO shape",witnessDirName:"Dir name",description:"Description",tagsPlaceholder:"comma-separated",weather:"Weather",shapeGroup:"Phenomenon",soundGroup:"Sound",temporalGroup:"Moment",timeQualifierExact:"Exact",timeQualifierApproximate:"Approximate",timeQualifierUncertain:"Uncertain",timeQualifierBoth:"Uncertain and approximate",edtfModeTitle:"Type an imprecise date instead: a year alone, a month, a time with no date",locationGroup:"Location",observationGroup:"Observation",weatherWhilePlaying:"Pause the recording to state the weather — while it plays, the instant these would be written at is moving",weatherInferred:"From weather records",weatherInferredTitle:"Weather isn't testimony: it's a measurable fact, on record for the observation's own date, time and place. Uncheck to state the conditions the witness reported, which then override the record.",weatherLookingUp:"Looking up the record…",weatherNeedsDateAndPlace:"A full date and a place are needed to look up the record",weatherNoRecord:"No record for this date and place",weatherLookupFailed:"Weather records temporarily unreachable",instrumentOutOfPeriod:"{name} — not of this date",unitMillimetres:"mm",unitDegrees:"°",soundSrcPlaceholder:"URL of a real recording",referenceGroup:"Pictures",reference:"Picture",referenceTitle:"Name",referenceSrc:"Address",referenceSrcPlaceholder:"https://…/photo.jpg",referenceKind:"Kind",referencePhoto:"Photo",referencePanorama:"Panorama (360°)",referenceCredit:"Credit",referenceCreditUrl:"Credit link",referenceT:"Taken at",referenceDrawing:"Drawn on",referenceOpacity:"Opacity",referenceHeading:"Heading",referencePitch:"Pitch",referenceRoll:"Roll",referenceFov:"Vertical field",referenceUsePose:"Use the witness's pose",addReferenceUrl:"Add from an address",addReferenceFile:"Add a file",deleteReference:"Delete picture",referenceEmbedded:"{kb} kB embedded in the recording — an address would keep it light",referenceUnreachable:"The picture could not be loaded: check the address, and that its site allows other sites to read it",referenceRegisterHint:"Drag to turn the picture, wheel to change its field; “Add a landmark” to point at a detail on the picture, then at the same one in the render",referenceLandmarkPicture:"Landmark {n}: click the point on the picture",referenceLandmarkScene:"Landmark {n}: click the same point in the render",referenceLandmarkOffPicture:"That click is not on the picture",referenceNotLoaded:"The picture has not arrived yet",referenceLandmarksFit:"{n} landmarks — {deg}° off on average",referenceLandmarks:"Landmarks",addReferenceLandmark:"Add a landmark",deleteReferenceLandmark:"Delete landmark",referenceLandmarkLabel:"Name",referenceLandmarkLabelPlaceholder:"Masking tree, fence…",referenceAdoptPose:"Adopt as the witness's pose",referenceAdoptRationale:"Measured on the picture “{title}”: {n} landmarks lined up, {deg}° of residual",referenceStreetSearch:"Street-level pictures nearby",referenceStreetSearching:"Looking for pictures taken nearby…",referenceStreetNone:"No street-level picture within {m} m (Panoramax)",referenceStreetFailed:"Panoramax could not be reached",referenceStreetAdd:"Add",referenceStreetItem:"{distance} m at {bearing}°, {date}{panorama}",referenceStreetPanorama:" — 360°",referenceStreetTitle:"Street-level picture {distance} m away at {bearing}°, {date}",skyLine:"Sky: {parts}",skyStarsEye:"stars down to magnitude {limit}, which is as faint as an eye went under this sky",skyStarsDeeper:"stars down to magnitude {limit} through a {device} — {gain} magnitudes past the {eye} the witness's own eyes reached",skyStarsShallower:"stars down to magnitude {limit} through a {device} — {gain} magnitudes short of the {eye} the witness's own eyes reached",skyStarsCatalogue:", drawn to {catalogue}, where this project's catalogue stops",skyStarsNone:"no star could be picked out of a sky this bright",skyDetails:"Show the records in full",skyDetailsHide:"Hide the records",skyShowerActive:"{name} — radiant {altitude}° above the horizon, {bearing} — about {rate}/h under this sky, over a sporadic background of {sporadic}/h",skyShowerBelowHorizon:"{name} is active, but its radiant is below the horizon — it can have produced nothing",skyNothingActive:"no meteor shower active on this date — a sporadic background of about {sporadic}/h",showMeteor:"Show me one",skyComet:"{name}, magnitude {magnitude}, {altitude}° above the horizon {bearing}, tail {tail}° long",skyCometNoTail:"{name}, magnitude {magnitude}, {altitude}° above the horizon {bearing}",skyCometBelowHorizon:"{name} was there at magnitude {magnitude}, but below the horizon — nobody here saw it",skyCometInDaylight:"{name}, magnitude {magnitude}, {altitude}° above the horizon {bearing} — but only {elongation}° from the Sun",showComet:"Show me the comet",skySatellitePasses:"{count} satellites crossed this sky bright enough to be seen, the brightest {name}, magnitude {magnitude}, {altitude}° above the horizon {bearing} at {time}",skySatellitePassesOne:"one satellite crossed this sky bright enough to be seen: {name}, magnitude {magnitude}, {altitude}° above the horizon {bearing} at {time}",skySatelliteTrain:"among them a train of {count} Starlinks launched on {date}",skySatellitePassesNone:"by the orbital elements archived for that date, no lit satellite crossed this sky brightly enough to be seen",skySatelliteElementsGap:"no orbital elements archived near that date",showSatellite:"Show me a satellite",skyOpticsPossible:"ice cloud enough, around the {source}, for {forms}",skyOpticsAlignment:" — everything but the rings needs crystals falling level, stated here at {alignment}% since no record holds it",skyOpticsHalo22:"a {angle}° ring",skyOpticsHalo46:"a {angle}° ring",skyOpticsParhelia:"sundogs {angle}° to either side",skyOpticsTangentArc:"an arc tangent on top of it",skyOpticsParhelicCircle:"a white circle right round the sky at its own height",skyOpticsCircumzenithal:"a circumzenithal arc {angle}° up",skyOpticsCircumhorizontal:"a circumhorizontal arc far below it",skyOpticsPillar:"a pillar standing over it",skyOpticsNoIce:"no ice cloud: no halo and no sundogs",skyOpticsHidden:"ice cloud above, but a lower deck between it and the witness",skyOpticsSun:"Sun",skyOpticsMoon:"Moon",skyBowPossible:"rain and sunlight enough for {forms}",skyBowMoon:"rain under a Moon {lit}% lit, enough for {forms} — a moonbow, which the eye sees as a white arc",skyGlowBand:"the Milky Way {contrast}× the sky behind it, {altitude}° up {bearing}",skyGlowCone:"the zodiacal light {contrast}× the sky behind it, {altitude}° up {bearing}, {elongation}° from the Sun — a leaning cone with no edge, gone within the hour",skyGlowZodiacalBand:"the zodiacal band {contrast}× the sky behind it, {altitude}° up {bearing} — the whole ecliptic faintly alight, which is not the sight people report",skyGlowMoon:"no Milky Way and no zodiacal light: a Moon {lit}% lit held the sky at {sky} magnitudes a square arcsecond, where they need 22",skyGlowTwilight:"no Milky Way and no zodiacal light: twilight still held the sky at {sky} magnitudes a square arcsecond, where they need 22",skyGlowNothingUp:"sky dark enough ({sky} magnitudes a square arcsecond) but neither the galactic plane nor the ecliptic stood high enough in it",skyBowPrimary:"a bow {radius}° across, its top {top}° up",skyBowSecondary:"a second, fainter one at {radius}° with its colours reversed",skyBowSourceTooHigh:"rain, but with the source {altitude}° up no bow could clear the horizon: they stand {radius}° from the point opposite it",skyBowHidden:"rain, but an unbroken deck between it and the light: no bow",skyBowNoSource:"rain, and nothing lit to make a bow of it",skySatellitesLit:"the Earth's shadow stood {height} km above the witness, so low orbit was still in sunlight — {count} tracked objects were in orbit that month",skySatellitesLitWith:"the Earth's shadow stood {height} km above the witness, so low orbit was still in sunlight — {count} tracked objects were in orbit that month, among them {eras}",skySatellitesShadowed:"the Earth's shadow stood {height} km above the witness: of the {count} tracked objects in orbit that month, nothing in low orbit was lit",skySatellitesNotYet:"nothing had been put in orbit yet",skySatellitesDaylight:"everything in orbit was sunlit, as it always is by day, and {eras} could outshine even this sky",skySatellitesDaylightOne:"everything in orbit was sunlit, as it always is by day, and {eras} could outshine even this sky",skyUnknown:"cannot be worked out without a date and a place",lookAtDecor:"Look at it",addDecor:"Add",deleteDecor:"Delete decor",decorSightingUrl:"Their own recording URL",viewTestimony:"View testimony",noWitnessRecording:"No recording URL set for this witness",masks:"Masks",addWitness:"Add witness",narrativePlaceholder:"What the witness reported, in their own words",narrativeKey:"{source} API key",narrativeNeedsKey:"Enter your own {source} API key to generate a reconstruction from the account",narrativeKeyUnlikely:"This does not look like a Claude API key: they begin with sk-ant-",narrativeWorkspace:"Workspace ID",narrativeWorkspacePlaceholder:"only if your key spans several",narrativeWorkspaceHint:"Only for a key whose scope is the whole organisation. Simpler: leave this empty and create a key scoped to one workspace instead.",narrativeNeedsAsk:"Nothing to send yet",narrativeRemember:"Remember on this device",narrativeDraft:"Generate reconstruction",narrativeStop:"Stop",narrativeWorking:"Reading the account…",narrativeApplied:"{count} fields written into the editor",narrativeUnchanged:"The account states nothing the recording can hold yet",narrativeStated:"What the witness said",narrativeDerived:"Worked out from the account",narrativeAssumed:"Guessed, so the reconstruction runs — check these",narrativeGaps:"What nothing could settle",narrativeErrorCredential:"No key, or one that was refused — check it at console.anthropic.com",narrativeErrorRateLimited:"Too many requests on your account: wait a moment and ask again",narrativeErrorRefused:"The account was not answered. Rephrasing may help; asking again will not",narrativeErrorMalformed:"The answer was not a usable draft — worth asking once more",narrativeErrorUnreachable:"Nothing answered: check the connection",narrativeErrorRejected:"Refused: {detail}",witnessAge:"Age then",witnessOccupation:"Occupation",testimonySource:"Account obtained",testimonySourceUnknown:"unknown",testimonySourceOnSite:"on-site investigation",testimonySourceInterview:"interview in person",testimonySourceTelephone:"by telephone",testimonySourceQuestionnaire:"questionnaire",testimonySourceLetter:"the witness wrote it",testimonySourcePress:"press or broadcast",testimonyFollowedUp:"Followed up",testimonyUnknown:"unknown",testimonyYes:"yes",testimonyNo:"no",questionUnanswered:"Nothing in this recording answers one of the questions a reconstruction needs settled",durationRequired:"The observation needs a length to be replayed at all — state one, or an end time, which may be approximate",questionsUnanswered:"{count} of the questions a full reconstruction answers are unanswered here"},PA=Object.freeze(Object.defineProperty({__proto__:null,sightingEditorMessages_en:Nv},Symbol.toStringTag,{value:"Module"})),Um=new Set;xc();eA();const Vr={width:48,height:28},LA=2500,kA=600,Bm=900,Xr=2e-4,NA=900,OA=-1.46,FA=3,zm=.2,UA=.01,BA=1.6,Jh=2e3,zA=250,Hm=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),vs=4,kl="ufo-1",Gm=["oval","polygon"],HA={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5,blur:0,brightness:0};function GA(r){return r.kind==="oval"?"oval":"polygon"}const WA=-6,VA=21;class Tt extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;presetButtons;presetsGroup;colorInput;transparencyInput;haloScaleInput;blurInput;brightnessInput;blurBoundOutput;sourceSelect;shapeTitleInput;utcOffsetInput;timeZoneSelect;timeZoneProvider=CA[0].create();timeZoneLookupTimer;timeZoneLookedUpAt;autoFilledTimeZone;timeZones=new IA;apparentWidthInput;realWidthInput;objectDistanceInput;sizeLockSelect;apparentSizeOutput;realSizeOutput;clearDistanceHypothesisButton;depthBasisOutput;addShapeButton;deleteShapeButton;contextMenu;contextGroupButton;contextUngroupButton;contextBringToFrontButton;contextSendToBackButton;contextDeleteButton;contextAddVertexButton;contextDeleteVertexButton;decorContextMenu;contextViewTestimonyButton;contextMasksSubmenu;labelContextMasks;playPauseButton;seekInput;timeStartLabel;timeEndLabel;loopButton;durationInput;exportButton;importFileInput;importUrlInput;importUrlButton;narrativeKeyInput;narrativeWorkspaceInput;narrativeRememberInput;narrativeDraftButton;narrativeStopButton;narrativeCreditLink;narrativeStatus;narrativeReport;placeNameInput;searchPlaceButton;placeMatchRow;placeMatchSelect;placeStatusText;placeProvider=_A();placeMatches=[];placeSearchToken=0;placeReverseTimer;namedCoordinates;latInput;lngInput;headingInput;pitchInput;rollInput;elevationInput;groundElevationOutput;weatherFromRecords=!0;groundElevationM;groundElevationFor;groundElevationTimer;groundElevationToken=0;obsTimeInput;obsTimeNativeInput;obsEndTimeNativeInput;obsTimeQualifier;obsEndTimeQualifier;edtfModeButton;edtfMode=!1;obsEndTimeInput;witnessIdInput;witnessDirNameInput;witnessTitleInput;witnessLastNameInput;witnessFirstNamesInput;witnessAgeInput;witnessOccupationInput;testimonySourceSelect;testimonyFollowedUpSelect;caseIdInput;descriptionInput;tagsInput;cloudEditor;cloudCoverInput;cloudDarknessInput;cloudBaseInput;precipitationTypeSelect;precipitationIntensityInput;windDirectionInput;windSpeedInput;stormInput;weatherInferredInput;weatherSourceText;skyCandidatesOutput;showMeteorButton;showCometButton;showSatelliteButton;weatherSourceLink;weatherFields;weatherInference=new Yh(MA());weatherLookupTimer;weatherLookupToken=0;weatherLookupPending=!1;weatherLookupResult;weatherTrackSpan;soundKindSelect;soundVolumeInput;soundPitchInput;soundPitchValue;soundSrcInput;soundFields;soundKindOptions=new Map;soundPreviewTimer;instrumentSelect;focalLengthInput;labelFocalLength;unitFocalLength;labelFNumber;labelExposure;labelFocusDistance;fNumberInput;exposureInput;focusDistanceInput;labelColor;labelTransparency;labelHalo;labelBlur;labelBrightness;labelShape;labelShapeTitle;labelUtcOffset;labelApparentWidth;labelRealWidth;labelObjectDistance;labelSizeLock;labelSamplingRate;labelDuration;placeSourceRow;weatherSourceRow;terrainSourceRows;chosenSourceId=new Map;labelPlaceName;labelPlaceMatch;labelLatitude;labelLongitude;labelHeading;labelPitch;labelRoll;labelElevation;labelObservationTime;labelObservationEndTime;labelWitnessId;labelWitnessDirName;labelWitnessTitle;labelWitnessLastName;labelWitnessFirstNames;labelWitnessAge;labelWitnessOccupation;labelTestimonySource;labelTestimonyFollowedUp;labelCaseId;labelDescription;labelTags;labelImportFile;labelImportUrl;labelNarrativeKey;labelNarrativeWorkspace;labelNarrativeRemember;groupTabs;groupPanels;paramSummary;paramSummaryBuilder;paramSummarySignature="";labelShapeGroup;labelTemporalGroup;labelLocationGroup;labelObservationGroup;labelWitnessGroup;skyDetailsButton;clampedLines;labelWeatherGroup;labelCloudCover;labelHighCloud;labelIceAlignment;highCloudCoverInput;iceCrystalAlignmentInput;labelCloudDarkness;labelCloudBase;labelPrecipitationType;labelPrecipitationIntensity;labelWindDirection;labelWindSpeed;labelStorm;labelCloudsGroup;labelPrecipitationGroup;labelWindGroup;subgroupTabs;labelWeatherInferred;labelSoundGroup;labelSoundKind;labelSoundVolume;labelSoundPitch;labelSoundSrc;labelInstrument;optionPrecipitationNone;optionPrecipitationRain;optionPrecipitationSnow;optionPrecipitationHail;decorKindSelect;addDecorWitnessButton;addDecorBuildingButton;deleteDecorButton;decorSelect;decorTitleInput;decorEastInput;decorNorthInput;decorHeadingInput;decorColorInput;decorLitInput;decorLightRigSelect;lookAtDecorButton;decorAltitudeInput;labelDecorAltitude;decorSightingUrlInput;decorModelProvider=Xl[0].create();confirmOverlay;confirmMessage;confirmAcceptButton;confirmDeclineButton;confirmAnswer;milestoneSelect;milestoneLabelInput;milestoneNoteInput;addMilestoneButton;deleteMilestoneButton;currentMilestoneT;decorWidthInput;decorLengthInput;decorHeightInput;decorModelSelect;decorModelAdvanced;decorModelUrlInput;decorModelTitleInput;decorModelAuthorInput;decorModelLicenseInput;decorModelSourceInput;decorFloorsInput;decorOccupiedFloorInput;decorWitnessSideSelect;decorWindowInputs;labelDecorSide;optionWitnessSide;labelDecor;labelDecorGroup;labelDecorTitle;labelDecorEast;labelDecorNorth;labelDecorHeading;labelDecorColor;labelDecorLit;labelDecorSightingUrl;labelMilestones;labelMilestoneLabel;labelMilestoneNote;labelDecorWidth;labelDecorLength;labelDecorHeight;labelDecorModel;labelDecorModelAdvanced;labelDecorModelUrl;labelDecorModelTitle;labelDecorModelAuthor;labelDecorModelLicense;labelDecorModelSource;labelDecorFloors;labelDecorOccupiedFloor;labelDecorWitnessSide;labelDecorWindows;optionWitnessSideNone;optionDecorBuilding;optionDecorTree;optionDecorCrop;optionDecorMound;optionDecorStreetlight;optionDecorVehicle;optionDecorAircraft;optionDecorEntity;labelDecorLights;optionDecorWitness;recorder;isRecording=!1;messages=Nv;currentAppearance={...HA};currentSourceId=kl;selectedSourceIds=new Set([kl]);currentDecorId;currentReferenceId;referenceSelect;deleteReferenceButton;referenceTitleInput;referenceSrcInput;referenceKindSelect;referenceCreditInput;referenceCreditUrlInput;referenceTInput;referenceDrawingInput;referenceOpacityInput;referenceHeadingInput;referencePitchInput;referenceRollInput;referenceFovInput;referenceUsePoseButton;referenceStatus;addReferenceUrlButton;addReferenceFileInput;referenceLandmarksSelect;addReferenceLandmarkButton;deleteReferenceLandmarkButton;referenceLandmarkLabelInput;labelReferenceLandmarks;labelReferenceLandmarkLabel;referenceAdoptPoseButton;referenceStreetSearchButton;referenceStreetSelect;referenceStreetAddButton;lastCanvasMode="shape";referenceDragState;armingLandmark=!1;pendingLandmark;currentLandmarkId;referenceFit;streetPictures=[];streetPictures$=new ea;referenceFields;labelReferenceGroup;labelReference;labelReferenceTitle;labelReferenceSrc;labelReferenceKind;labelReferenceCredit;labelReferenceCreditUrl;labelReferenceT;labelReferenceDrawing;labelReferenceOpacity;labelReferenceHeading;labelReferencePitch;labelReferenceRoll;labelReferenceFov;labelAddReferenceFile;contextMenuDecorId;contextMenuPoint;dragState;cameraDragState;hoverCursor;indoorLookYawDeg=0;indoorLookPitchDeg=0;lastInhabitedKey;handleKeyDown=e=>{if(e.key==="Escape"&&(this.isRecording&&this.toggleRecording(),this.confirmOverlay.hidden||this.answerConfirm(!1),(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark(),this.contextMenu.hidden||this.hideContextMenu(),this.decorContextMenu.hidden||this.hideDecorContextMenu()),Hm.has(e.key)||e.key==="Delete"||e.key==="Backspace"){const t=e.composedPath()[0];if(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement)return;Hm.has(e.key)?this.moveOrResizeSelectedShapes(e):this.deleteShape()}};handleDragPointerMove=e=>this.onDragPointerMove(e);handleDragPointerUp=()=>this.endDrag();constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${R1}</style>${C1}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.sceneElement=document.createElement(Cu),this.sceneElement.setAttribute("show-compass",""),this.sceneElement.setAttribute(sr,""),this.sceneElement.animateWhilePaused=!0,this.ufoElement=this.sceneElement.ufoElement,this.ufoElement.enableClickToPlay=!1,this.ufoElement.showToolbar=!1,this.shadow.getElementById("ufo-slot").replaceWith(this.sceneElement),this.ufoElement.hostControls(this.shadow.getElementById("scene-controls")),this.recordButton=this.shadow.getElementById("record"),this.samplingRateInput=this.shadow.getElementById("samplingRate"),this.presetsGroup=this.shadow.getElementById("presets-group"),this.presetButtons={oval:this.shadow.getElementById("preset-oval"),polygon:this.shadow.getElementById("preset-polygon")},this.colorInput=this.shadow.getElementById("color"),this.transparencyInput=this.shadow.getElementById("transparency"),this.haloScaleInput=this.shadow.getElementById("haloScale"),this.blurInput=this.shadow.getElementById("blur"),this.brightnessInput=this.shadow.getElementById("brightness"),this.blurBoundOutput=this.shadow.getElementById("blur-bound"),this.sourceSelect=this.shadow.getElementById("source"),this.shapeTitleInput=this.shadow.getElementById("shapeTitle"),this.utcOffsetInput=this.shadow.getElementById("utcOffsetHours"),this.timeZoneSelect=this.shadow.getElementById("timeZone"),this.apparentWidthInput=this.shadow.getElementById("apparentWidth"),this.realWidthInput=this.shadow.getElementById("realWidth"),this.objectDistanceInput=this.shadow.getElementById("objectDistance"),this.sizeLockSelect=this.shadow.getElementById("sizeLock"),this.apparentSizeOutput=this.shadow.getElementById("apparent-size"),this.realSizeOutput=this.shadow.getElementById("real-size"),this.clearDistanceHypothesisButton=this.shadow.getElementById("clear-distance-hypothesis"),this.depthBasisOutput=this.shadow.getElementById("depth-basis"),this.addShapeButton=this.shadow.getElementById("add-shape"),this.deleteShapeButton=this.shadow.getElementById("delete-shape"),this.contextMenu=this.shadow.getElementById("context-menu"),this.contextGroupButton=this.shadow.getElementById("context-group"),this.contextUngroupButton=this.shadow.getElementById("context-ungroup"),this.contextBringToFrontButton=this.shadow.getElementById("context-bring-to-front"),this.contextSendToBackButton=this.shadow.getElementById("context-send-to-back"),this.contextDeleteButton=this.shadow.getElementById("context-delete"),this.contextAddVertexButton=this.shadow.getElementById("context-add-vertex"),this.contextDeleteVertexButton=this.shadow.getElementById("context-delete-vertex"),this.decorContextMenu=this.shadow.getElementById("decor-context-menu"),this.contextViewTestimonyButton=this.shadow.getElementById("context-view-testimony"),this.contextMasksSubmenu=this.shadow.getElementById("context-masks-submenu"),this.labelContextMasks=this.shadow.getElementById("label-context-masks"),this.playPauseButton=this.shadow.getElementById("play-pause"),this.seekInput=this.shadow.getElementById("seek"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end");for(const t of[this.timeStartLabel,this.timeEndLabel])t.addEventListener("click",()=>this.switchTimeDisplay()),t.addEventListener("keydown",n=>{n.key!=="Enter"&&n.key!==" "||(n.preventDefault(),this.switchTimeDisplay())});this.loopButton=this.shadow.getElementById("loop"),this.durationInput=this.shadow.getElementById("durationSeconds"),this.exportButton=this.shadow.getElementById("export"),this.importFileInput=this.shadow.getElementById("import-file"),this.importUrlInput=this.shadow.getElementById("import-url"),this.importUrlButton=this.shadow.getElementById("import-url-button"),this.narrativeKeyInput=this.shadow.getElementById("narrativeKey"),this.narrativeWorkspaceInput=this.shadow.getElementById("narrativeWorkspace"),this.narrativeRememberInput=this.shadow.getElementById("narrativeRemember"),this.narrativeDraftButton=this.shadow.getElementById("narrative-draft"),this.narrativeStopButton=this.shadow.getElementById("narrative-stop"),this.narrativeCreditLink=this.shadow.getElementById("narrative-credit"),this.narrativeStatus=this.shadow.getElementById("narrative-status"),this.narrativeReport=this.shadow.getElementById("narrative-report"),this.placeNameInput=this.shadow.getElementById("placeName"),this.searchPlaceButton=this.shadow.getElementById("search-place"),this.placeMatchRow=this.shadow.getElementById("place-match-row"),this.placeMatchSelect=this.shadow.getElementById("placeMatch"),this.placeStatusText=this.shadow.getElementById("place-status-text"),this.latInput=this.shadow.getElementById("lat"),this.lngInput=this.shadow.getElementById("lng"),this.headingInput=this.shadow.getElementById("heading"),this.pitchInput=this.shadow.getElementById("pitch"),this.rollInput=this.shadow.getElementById("roll"),this.elevationInput=this.shadow.getElementById("elevation"),this.groundElevationOutput=this.shadow.getElementById("ground-elevation"),this.obsTimeInput=this.shadow.getElementById("obs-time"),this.obsEndTimeInput=this.shadow.getElementById("obs-end-time"),this.obsTimeNativeInput=this.shadow.getElementById("obs-time-native"),this.obsEndTimeNativeInput=this.shadow.getElementById("obs-end-time-native"),this.obsTimeQualifier=this.shadow.getElementById("obs-time-qualifier"),this.obsEndTimeQualifier=this.shadow.getElementById("obs-end-time-qualifier"),this.edtfModeButton=this.shadow.getElementById("edtf-mode"),this.witnessIdInput=this.shadow.getElementById("witnessId"),this.witnessDirNameInput=this.shadow.getElementById("witnessDirName"),this.witnessTitleInput=this.shadow.getElementById("witnessTitle"),this.witnessLastNameInput=this.shadow.getElementById("witnessLastName"),this.witnessFirstNamesInput=this.shadow.getElementById("witnessFirstNames"),this.witnessAgeInput=this.shadow.getElementById("witnessAge"),this.witnessOccupationInput=this.shadow.getElementById("witnessOccupation"),this.testimonySourceSelect=this.shadow.getElementById("testimonySource"),this.testimonyFollowedUpSelect=this.shadow.getElementById("testimonyFollowedUp"),this.caseIdInput=this.shadow.getElementById("caseId"),this.descriptionInput=this.shadow.getElementById("description"),this.tagsInput=this.shadow.getElementById("tags"),this.cloudCoverInput=this.shadow.getElementById("cloudCover"),this.highCloudCoverInput=this.shadow.getElementById("highCloudCover"),this.iceCrystalAlignmentInput=this.shadow.getElementById("iceCrystalAlignment"),this.cloudDarknessInput=this.shadow.getElementById("cloudDarkness"),this.cloudBaseInput=this.shadow.getElementById("cloudBase"),this.precipitationTypeSelect=this.shadow.getElementById("precipitationType"),this.precipitationIntensityInput=this.shadow.getElementById("precipitationIntensity"),this.windDirectionInput=this.shadow.getElementById("windDirection"),this.windSpeedInput=this.shadow.getElementById("windSpeed"),this.stormInput=this.shadow.getElementById("storm"),this.weatherInferredInput=this.shadow.getElementById("weatherInferred"),this.weatherSourceText=this.shadow.getElementById("weather-source-text"),this.skyCandidatesOutput=this.shadow.getElementById("sky-candidates"),this.showMeteorButton=this.shadow.getElementById("show-meteor"),this.showCometButton=this.shadow.getElementById("show-comet"),this.showSatelliteButton=this.shadow.getElementById("show-satellite"),this.weatherSourceLink=this.shadow.getElementById("weather-source-link"),this.weatherFields=[this.cloudCoverInput,this.highCloudCoverInput,this.iceCrystalAlignmentInput,this.cloudDarknessInput,this.cloudBaseInput,this.precipitationTypeSelect,this.precipitationIntensityInput,this.windDirectionInput,this.windSpeedInput,this.stormInput],this.soundKindSelect=this.shadow.getElementById("soundKind"),this.soundVolumeInput=this.shadow.getElementById("soundVolume"),this.soundPitchInput=this.shadow.getElementById("soundPitch"),this.soundPitchValue=this.shadow.getElementById("sound-pitch-value"),this.soundSrcInput=this.shadow.getElementById("soundSrc"),this.soundFields=[this.soundKindSelect,this.soundVolumeInput,this.soundPitchInput,this.soundSrcInput],this.buildSoundKindOptions(),this.instrumentSelect=this.shadow.getElementById("instrument"),this.focalLengthInput=this.shadow.getElementById("focalLength"),this.labelFocalLength=this.shadow.getElementById("label-focal-length"),this.unitFocalLength=this.shadow.getElementById("unit-focal-length"),this.labelFNumber=this.shadow.getElementById("label-f-number"),this.labelExposure=this.shadow.getElementById("label-exposure"),this.fNumberInput=this.shadow.getElementById("fNumber"),this.exposureInput=this.shadow.getElementById("exposureSeconds"),this.focusDistanceInput=this.shadow.getElementById("focusDistance"),this.labelFocusDistance=this.shadow.getElementById("label-focus-distance"),this.refreshInstrumentOptions(),this.labelColor=this.shadow.getElementById("label-color"),this.labelTransparency=this.shadow.getElementById("label-transparency"),this.labelHalo=this.shadow.getElementById("label-halo"),this.labelBlur=this.shadow.getElementById("label-blur"),this.labelBrightness=this.shadow.getElementById("label-brightness"),this.labelShape=this.shadow.getElementById("label-shape"),this.labelShapeTitle=this.shadow.getElementById("label-shape-title"),this.labelUtcOffset=this.shadow.getElementById("label-utc-offset"),this.labelApparentWidth=this.shadow.getElementById("label-apparent-width"),this.labelRealWidth=this.shadow.getElementById("label-real-width"),this.labelObjectDistance=this.shadow.getElementById("label-object-distance"),this.labelSizeLock=this.shadow.getElementById("label-size-lock"),this.labelSamplingRate=this.shadow.getElementById("label-sampling-rate"),this.labelSoundGroup=this.shadow.getElementById("label-sound-group"),this.labelSoundKind=this.shadow.getElementById("label-sound-kind"),this.labelSoundVolume=this.shadow.getElementById("label-sound-volume"),this.labelSoundPitch=this.shadow.getElementById("label-sound-pitch"),this.labelSoundSrc=this.shadow.getElementById("label-sound-src"),this.labelReferenceGroup=this.shadow.getElementById("label-reference-group"),this.labelReference=this.shadow.getElementById("label-reference"),this.labelReferenceTitle=this.shadow.getElementById("label-reference-title"),this.labelReferenceSrc=this.shadow.getElementById("label-reference-src"),this.labelReferenceKind=this.shadow.getElementById("label-reference-kind"),this.labelReferenceCredit=this.shadow.getElementById("label-reference-credit"),this.labelReferenceCreditUrl=this.shadow.getElementById("label-reference-credit-url"),this.labelReferenceT=this.shadow.getElementById("label-reference-t"),this.labelReferenceDrawing=this.shadow.getElementById("label-reference-drawing"),this.labelReferenceOpacity=this.shadow.getElementById("label-reference-opacity"),this.labelReferenceHeading=this.shadow.getElementById("label-reference-heading"),this.labelReferencePitch=this.shadow.getElementById("label-reference-pitch"),this.labelReferenceRoll=this.shadow.getElementById("label-reference-roll"),this.labelReferenceFov=this.shadow.getElementById("label-reference-fov"),this.labelAddReferenceFile=this.shadow.getElementById("label-add-reference-file"),this.labelDuration=this.shadow.getElementById("label-duration"),this.placeSourceRow=this.shadow.getElementById("place-source-row"),this.weatherSourceRow=this.shadow.getElementById("weather-source-row"),this.terrainSourceRows=this.shadow.getElementById("terrain-source-rows"),this.labelPlaceName=this.shadow.getElementById("label-place-name"),this.labelPlaceMatch=this.shadow.getElementById("label-place-match"),this.labelLatitude=this.shadow.getElementById("label-lat"),this.labelLongitude=this.shadow.getElementById("label-lng"),this.labelHeading=this.shadow.getElementById("label-heading"),this.labelPitch=this.shadow.getElementById("label-pitch"),this.labelRoll=this.shadow.getElementById("label-roll"),this.labelElevation=this.shadow.getElementById("label-elevation"),this.labelObservationTime=this.shadow.getElementById("label-observation-time"),this.labelObservationEndTime=this.shadow.getElementById("label-observation-end-time"),this.labelWitnessId=this.shadow.getElementById("label-witness-id"),this.labelWitnessDirName=this.shadow.getElementById("label-witness-dir-name"),this.labelWitnessTitle=this.shadow.getElementById("label-witness-title"),this.labelWitnessLastName=this.shadow.getElementById("label-witness-last-name"),this.labelWitnessFirstNames=this.shadow.getElementById("label-witness-first-names"),this.labelWitnessAge=this.shadow.getElementById("label-witness-age"),this.labelWitnessOccupation=this.shadow.getElementById("label-witness-occupation"),this.labelTestimonySource=this.shadow.getElementById("label-testimony-source"),this.labelTestimonyFollowedUp=this.shadow.getElementById("label-testimony-followed-up"),this.labelCaseId=this.shadow.getElementById("label-case-id"),this.labelDescription=this.shadow.getElementById("label-description"),this.labelTags=this.shadow.getElementById("label-tags"),this.labelImportFile=this.shadow.getElementById("label-import-file"),this.labelImportUrl=this.shadow.getElementById("label-import-url"),this.labelNarrativeKey=this.shadow.getElementById("label-narrative-key"),this.labelNarrativeWorkspace=this.shadow.getElementById("label-narrative-workspace"),this.labelNarrativeRemember=this.shadow.getElementById("label-narrative-remember"),this.labelShapeGroup=this.shadow.getElementById("label-shape-group"),this.labelTemporalGroup=this.shadow.getElementById("label-temporal-group"),this.labelLocationGroup=this.shadow.getElementById("label-location-group"),this.labelObservationGroup=this.shadow.getElementById("label-observation-group"),this.labelWitnessGroup=this.shadow.getElementById("label-witness-group"),this.labelWeatherGroup=this.shadow.getElementById("label-weather-group"),this.labelCloudCover=this.shadow.getElementById("label-cloud-cover"),this.labelHighCloud=this.shadow.getElementById("label-high-cloud"),this.labelIceAlignment=this.shadow.getElementById("label-ice-alignment"),this.labelCloudDarkness=this.shadow.getElementById("label-cloud-darkness"),this.labelCloudBase=this.shadow.getElementById("label-cloud-base"),this.labelPrecipitationType=this.shadow.getElementById("label-precipitation-type"),this.labelPrecipitationIntensity=this.shadow.getElementById("label-precipitation-intensity"),this.labelWindDirection=this.shadow.getElementById("label-wind-direction"),this.labelWindSpeed=this.shadow.getElementById("label-wind-speed"),this.labelStorm=this.shadow.getElementById("label-storm"),this.labelCloudsGroup=this.shadow.getElementById("label-clouds-group"),this.labelPrecipitationGroup=this.shadow.getElementById("label-precipitation-group"),this.labelWindGroup=this.shadow.getElementById("label-wind-group"),this.labelWeatherInferred=this.shadow.getElementById("label-weather-inferred"),this.labelInstrument=this.shadow.getElementById("label-instrument"),this.optionPrecipitationNone=this.shadow.getElementById("option-precipitation-none"),this.optionPrecipitationRain=this.shadow.getElementById("option-precipitation-rain"),this.optionPrecipitationSnow=this.shadow.getElementById("option-precipitation-snow"),this.optionPrecipitationHail=this.shadow.getElementById("option-precipitation-hail"),this.decorKindSelect=this.shadow.getElementById("decorKind"),this.addDecorWitnessButton=this.shadow.getElementById("add-decor-witness"),this.addDecorBuildingButton=this.shadow.getElementById("add-decor-building"),this.deleteDecorButton=this.shadow.getElementById("delete-decor"),this.decorSelect=this.shadow.getElementById("decor"),this.referenceSelect=this.shadow.getElementById("reference"),this.deleteReferenceButton=this.shadow.getElementById("delete-reference"),this.referenceTitleInput=this.shadow.getElementById("referenceTitle"),this.referenceSrcInput=this.shadow.getElementById("referenceSrc"),this.referenceKindSelect=this.shadow.getElementById("referenceKind"),this.referenceCreditInput=this.shadow.getElementById("referenceCredit"),this.referenceCreditUrlInput=this.shadow.getElementById("referenceCreditUrl"),this.referenceTInput=this.shadow.getElementById("referenceT"),this.referenceDrawingInput=this.shadow.getElementById("referenceDrawing"),this.referenceOpacityInput=this.shadow.getElementById("referenceOpacity"),this.referenceHeadingInput=this.shadow.getElementById("referenceHeading"),this.referencePitchInput=this.shadow.getElementById("referencePitch"),this.referenceRollInput=this.shadow.getElementById("referenceRoll"),this.referenceFovInput=this.shadow.getElementById("referenceFov"),this.referenceUsePoseButton=this.shadow.getElementById("reference-use-pose"),this.referenceStatus=this.shadow.getElementById("reference-status"),this.addReferenceUrlButton=this.shadow.getElementById("add-reference-url"),this.addReferenceFileInput=this.shadow.getElementById("add-reference-file"),this.referenceLandmarksSelect=this.shadow.getElementById("reference-landmarks"),this.addReferenceLandmarkButton=this.shadow.getElementById("add-reference-landmark"),this.deleteReferenceLandmarkButton=this.shadow.getElementById("delete-reference-landmark"),this.referenceLandmarkLabelInput=this.shadow.getElementById("referenceLandmarkLabel"),this.labelReferenceLandmarks=this.shadow.getElementById("label-reference-landmarks"),this.labelReferenceLandmarkLabel=this.shadow.getElementById("label-reference-landmark-label"),this.referenceAdoptPoseButton=this.shadow.getElementById("reference-adopt-pose"),this.referenceStreetSearchButton=this.shadow.getElementById("reference-street-search"),this.referenceStreetSelect=this.shadow.getElementById("reference-street"),this.referenceStreetAddButton=this.shadow.getElementById("reference-street-add"),this.referenceFields=[this.referenceTitleInput,this.referenceSrcInput,this.referenceKindSelect,this.referenceCreditInput,this.referenceCreditUrlInput,this.referenceTInput,this.referenceDrawingInput,this.referenceOpacityInput,this.referenceHeadingInput,this.referencePitchInput,this.referenceRollInput,this.referenceFovInput],this.decorTitleInput=this.shadow.getElementById("decorTitle"),this.decorEastInput=this.shadow.getElementById("decorEast"),this.decorNorthInput=this.shadow.getElementById("decorNorth"),this.decorHeadingInput=this.shadow.getElementById("decorHeading"),this.decorColorInput=this.shadow.getElementById("decorColor"),this.decorLitInput=this.shadow.getElementById("decorLit"),this.decorLightRigSelect=this.shadow.getElementById("decorLightRig"),this.lookAtDecorButton=this.shadow.getElementById("look-at-decor"),this.decorAltitudeInput=this.shadow.getElementById("decorAltitude"),this.labelDecorAltitude=this.shadow.getElementById("label-decor-altitude"),this.decorSightingUrlInput=this.shadow.getElementById("decorSightingUrl"),this.confirmOverlay=this.shadow.getElementById("confirm-overlay"),this.confirmMessage=this.shadow.getElementById("confirm-message"),this.confirmAcceptButton=this.shadow.getElementById("confirm-ok"),this.confirmDeclineButton=this.shadow.getElementById("confirm-cancel"),this.milestoneSelect=this.shadow.getElementById("milestone"),this.milestoneLabelInput=this.shadow.getElementById("milestoneLabel"),this.milestoneNoteInput=this.shadow.getElementById("milestoneNote"),this.addMilestoneButton=this.shadow.getElementById("add-milestone"),this.deleteMilestoneButton=this.shadow.getElementById("delete-milestone"),this.decorWidthInput=this.shadow.getElementById("decorWidth"),this.decorLengthInput=this.shadow.getElementById("decorLength"),this.decorHeightInput=this.shadow.getElementById("decorHeight"),this.decorModelSelect=this.shadow.getElementById("decorModel"),this.decorModelAdvanced=this.shadow.getElementById("decor-model-advanced"),this.decorModelUrlInput=this.shadow.getElementById("decorModelUrl"),this.decorModelTitleInput=this.shadow.getElementById("decorModelTitle"),this.decorModelAuthorInput=this.shadow.getElementById("decorModelAuthor"),this.decorModelLicenseInput=this.shadow.getElementById("decorModelLicense"),this.decorModelSourceInput=this.shadow.getElementById("decorModelSource"),this.decorFloorsInput=this.shadow.getElementById("decorFloors"),this.decorOccupiedFloorInput=this.shadow.getElementById("decorOccupiedFloor"),this.decorWitnessSideSelect=this.shadow.getElementById("decorWitnessSide"),this.decorWindowInputs={front:this.shadow.getElementById("decorWindowFront"),behind:this.shadow.getElementById("decorWindowBehind"),left:this.shadow.getElementById("decorWindowLeft"),right:this.shadow.getElementById("decorWindowRight"),"front-left":this.shadow.getElementById("decorWindowFrontLeft"),"front-right":this.shadow.getElementById("decorWindowFrontRight"),"behind-left":this.shadow.getElementById("decorWindowBehindLeft"),"behind-right":this.shadow.getElementById("decorWindowBehindRight")},this.labelDecorSide={front:this.shadow.getElementById("label-decor-window-front"),behind:this.shadow.getElementById("label-decor-window-behind"),left:this.shadow.getElementById("label-decor-window-left"),right:this.shadow.getElementById("label-decor-window-right"),"front-left":this.shadow.getElementById("label-decor-window-front-left"),"front-right":this.shadow.getElementById("label-decor-window-front-right"),"behind-left":this.shadow.getElementById("label-decor-window-behind-left"),"behind-right":this.shadow.getElementById("label-decor-window-behind-right")},this.optionWitnessSide={front:this.shadow.getElementById("option-witness-side-front"),behind:this.shadow.getElementById("option-witness-side-behind"),left:this.shadow.getElementById("option-witness-side-left"),right:this.shadow.getElementById("option-witness-side-right"),"front-left":this.shadow.getElementById("option-witness-side-front-left"),"front-right":this.shadow.getElementById("option-witness-side-front-right"),"behind-left":this.shadow.getElementById("option-witness-side-behind-left"),"behind-right":this.shadow.getElementById("option-witness-side-behind-right")},this.optionWitnessSideNone=this.shadow.getElementById("option-witness-side-none"),this.labelDecor=this.shadow.getElementById("label-decor"),this.labelDecorGroup=this.shadow.getElementById("label-decor-group"),this.labelDecorTitle=this.shadow.getElementById("label-decor-title"),this.labelDecorEast=this.shadow.getElementById("label-decor-east"),this.labelDecorNorth=this.shadow.getElementById("label-decor-north"),this.labelDecorHeading=this.shadow.getElementById("label-decor-heading"),this.labelDecorColor=this.shadow.getElementById("label-decor-color"),this.labelDecorLit=this.shadow.getElementById("label-decor-lit"),this.labelDecorSightingUrl=this.shadow.getElementById("label-decor-sighting-url"),this.labelMilestones=this.shadow.getElementById("label-milestones"),this.labelMilestoneLabel=this.shadow.getElementById("label-milestone-label"),this.labelMilestoneNote=this.shadow.getElementById("label-milestone-note"),this.labelDecorWidth=this.shadow.getElementById("label-decor-width"),this.labelDecorLength=this.shadow.getElementById("label-decor-length"),this.labelDecorHeight=this.shadow.getElementById("label-decor-height"),this.labelDecorModel=this.shadow.getElementById("label-decor-model"),this.labelDecorModelAdvanced=this.shadow.getElementById("label-decor-model-advanced"),this.labelDecorModelUrl=this.shadow.getElementById("label-decor-model-url"),this.labelDecorModelTitle=this.shadow.getElementById("label-decor-model-title"),this.labelDecorModelAuthor=this.shadow.getElementById("label-decor-model-author"),this.labelDecorModelLicense=this.shadow.getElementById("label-decor-model-license"),this.labelDecorModelSource=this.shadow.getElementById("label-decor-model-source"),this.labelDecorFloors=this.shadow.getElementById("label-decor-floors"),this.labelDecorOccupiedFloor=this.shadow.getElementById("label-decor-occupied-floor"),this.labelDecorWitnessSide=this.shadow.getElementById("label-decor-witness-side"),this.labelDecorWindows=this.shadow.getElementById("label-decor-windows"),this.optionDecorBuilding=this.shadow.getElementById("option-decor-building"),this.optionDecorTree=this.shadow.getElementById("option-decor-tree"),this.optionDecorCrop=this.shadow.getElementById("option-decor-crop"),this.optionDecorMound=this.shadow.getElementById("option-decor-mound"),this.optionDecorStreetlight=this.shadow.getElementById("option-decor-streetlight"),this.optionDecorVehicle=this.shadow.getElementById("option-decor-vehicle"),this.optionDecorAircraft=this.shadow.getElementById("option-decor-aircraft"),this.optionDecorEntity=this.shadow.getElementById("option-decor-entity"),this.labelDecorLights=this.shadow.getElementById("label-decor-lights"),this.optionDecorWitness=this.shadow.getElementById("option-decor-witness"),this.ufoElement.canvasElement.addEventListener("pointerdown",t=>{this.focus({preventScroll:!0}),this.onPointerDown(t)}),this.ufoElement.canvasElement.addEventListener("pointermove",t=>this.onPointerMove(t)),this.ufoElement.canvasElement.addEventListener("contextmenu",t=>this.onContextMenu(t)),this.contextGroupButton.addEventListener("click",()=>this.groupSelected()),this.contextUngroupButton.addEventListener("click",()=>this.ungroupSelected()),this.contextBringToFrontButton.addEventListener("click",()=>this.bringSelectedToFront()),this.contextSendToBackButton.addEventListener("click",()=>this.sendSelectedToBack()),this.contextDeleteButton.addEventListener("click",()=>{this.hideContextMenu(),this.deleteShape()}),this.contextAddVertexButton.addEventListener("click",()=>this.addVertexAtContextMenu()),this.contextDeleteVertexButton.addEventListener("click",()=>this.deleteVertexAtContextMenu()),this.contextViewTestimonyButton.addEventListener("click",()=>this.viewWitnessTestimony()),this.playPauseButton.addEventListener("click",()=>{this.ufoElement.togglePlayPause(),this.syncPlaybackControls()}),this.loopButton.addEventListener("click",()=>{this.ufoElement.toggleLoop(),this.syncPlaybackControls()}),this.seekInput.addEventListener("input",()=>this.ufoElement.currentTime=Number(this.seekInput.value)),this.recordButton.addEventListener("click",()=>this.toggleRecording()),this.addShapeButton.addEventListener("click",()=>this.addShape()),this.deleteShapeButton.addEventListener("click",()=>this.deleteShape()),this.exportButton.addEventListener("click",()=>this.exportJson()),this.importFileInput.addEventListener("change",()=>this.importFromFile()),this.importUrlButton.addEventListener("click",()=>this.importFromUrl()),this.testimonySourceSelect.addEventListener("change",()=>this.updateWitnessMetadata()),this.testimonyFollowedUpSelect.addEventListener("change",()=>this.updateWitnessMetadata()),this.narrativeDraftButton.addEventListener("click",()=>this.draftFromDescription()),this.narrativeStopButton.addEventListener("click",()=>this.narrativeAbort?.abort()),this.narrativeRememberInput.addEventListener("change",()=>this.rememberNarrativeKey()),this.narrativeWorkspaceInput.addEventListener("input",()=>this.rememberNarrativeKey()),this.narrativeKeyInput.addEventListener("input",()=>{this.rememberNarrativeKey(),this.syncNarrativeEnabled()}),this.narrativeCreditLink.textContent=`${Ns[0].name} — ${Ns[0].credit}`,this.narrativeCreditLink.href=Ns[0].creditUrl,this.labelNarrativeKey.textContent=this.messages.narrativeKey.replace("{source}",Ns[0].name),this.narrativeWorkspaceInput.title=this.messages.narrativeWorkspaceHint,this.restoreNarrativeKey(),this.syncNarrativeEnabled(),this.durationInput.addEventListener("input",()=>{this.ufoElement.durationSeconds=this.durationInput.value===""?void 0:Number(this.durationInput.value),this.ufoElement.refresh(),this.updateDurationValidity(),this.scheduleWeatherLookup()}),this.sourceSelect.addEventListener("change",()=>this.selectUnit(this.sourceSelect.value)),this.shapeTitleInput.addEventListener("input",()=>this.updateShapeTitle()),this.apparentWidthInput.addEventListener("input",()=>this.typing(this.apparentWidthInput,()=>this.onApparentWidthInput())),this.realWidthInput.addEventListener("input",()=>this.typing(this.realWidthInput,()=>this.onRealWidthInput())),this.objectDistanceInput.addEventListener("input",()=>this.typing(this.objectDistanceInput,()=>this.onDistanceInput())),this.sizeLockSelect.addEventListener("change",()=>this.applySizeLock()),this.clearDistanceHypothesisButton.addEventListener("click",()=>this.clearDistanceHypothesis()),this.addDecorWitnessButton.addEventListener("click",()=>this.addDecor("witness")),this.addDecorBuildingButton.addEventListener("click",()=>this.addDecor()),this.deleteDecorButton.addEventListener("click",()=>this.deleteDecor()),this.decorSelect.addEventListener("change",()=>this.selectDecor(this.decorSelect.value)),this.referenceSelect.addEventListener("change",()=>this.selectReference(this.referenceSelect.value)),this.deleteReferenceButton.addEventListener("click",()=>this.deleteReference());for(const t of this.referenceFields)t.addEventListener("input",()=>this.updateReference());this.referenceUsePoseButton.addEventListener("click",()=>this.useWitnessPoseForReference()),this.addReferenceUrlButton.addEventListener("click",()=>this.addReferenceFromAddress()),this.addReferenceFileInput.addEventListener("change",()=>void this.addReferenceFromFile()),this.addReferenceLandmarkButton.addEventListener("click",()=>this.armLandmark()),this.deleteReferenceLandmarkButton.addEventListener("click",()=>this.deleteLandmark()),this.referenceLandmarksSelect.addEventListener("change",()=>this.selectLandmark(this.referenceLandmarksSelect.value)),this.referenceLandmarkLabelInput.addEventListener("input",()=>this.updateLandmarkLabel()),this.referenceAdoptPoseButton.addEventListener("click",()=>this.adoptReferencePose()),this.referenceStreetSearchButton.addEventListener("click",()=>void this.searchStreetPictures()),this.referenceStreetAddButton.addEventListener("click",()=>this.addStreetPicture()),this.ufoElement.canvasElement.addEventListener("wheel",t=>this.onReferenceWheel(t),{passive:!1});for(const t of[this.decorTitleInput,this.decorEastInput,this.decorNorthInput,this.decorAltitudeInput,this.decorHeadingInput,this.decorColorInput,this.decorSightingUrlInput,this.decorWidthInput,this.decorLengthInput,this.decorHeightInput,this.decorModelUrlInput,this.decorModelTitleInput,this.decorModelAuthorInput,this.decorModelLicenseInput,this.decorModelSourceInput,this.decorFloorsInput,this.decorOccupiedFloorInput])t.addEventListener("input",()=>this.updateDecor());this.decorWitnessSideSelect.addEventListener("change",()=>this.updateDecor()),this.decorModelSelect.addEventListener("change",()=>this.updateDecorModelChoice()),this.addMilestoneButton.addEventListener("click",()=>this.addMilestone()),this.deleteMilestoneButton.addEventListener("click",()=>this.deleteMilestone()),this.milestoneSelect.addEventListener("change",()=>this.selectMilestone(Number(this.milestoneSelect.value)));for(const t of[this.milestoneLabelInput,this.milestoneNoteInput])t.addEventListener("input",()=>this.updateMilestone());this.confirmAcceptButton.addEventListener("click",()=>this.answerConfirm(!0)),this.confirmDeclineButton.addEventListener("click",()=>this.answerConfirm(!1)),this.confirmOverlay.addEventListener("click",t=>{t.target===this.confirmOverlay&&this.answerConfirm(!1)});for(const t of gr)this.decorWindowInputs[t].addEventListener("input",()=>this.updateDecorWindows());this.decorLitInput.addEventListener("input",()=>this.updateDecorLit()),this.decorLightRigSelect.addEventListener("change",()=>this.updateDecorLightRig()),this.lookAtDecorButton.addEventListener("click",()=>this.lookAtDecor()),this.showMeteorButton.addEventListener("click",()=>this.showNextMeteor()),this.showCometButton.addEventListener("click",()=>this.lookAtComet()),this.showSatelliteButton.addEventListener("click",()=>this.showNextSatellite()),this.sceneElement.addEventListener(Pv,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.ufoElement.addEventListener("timeupdate",()=>{this.onSelectionOrTimeChanged(),this.syncPlaybackControls(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.addEventListener("keydown",this.handleKeyDown);for(const t of Gm)this.presetButtons[t].addEventListener("click",()=>this.setAppearance({presetId:t}));this.colorInput.addEventListener("input",()=>this.setAppearance({color:this.colorInput.value})),this.transparencyInput.addEventListener("input",()=>this.setAppearance({transparency:Number(this.transparencyInput.value)})),this.brightnessInput.addEventListener("input",()=>this.setAppearance({brightness:Number(this.brightnessInput.value)})),this.blurInput.addEventListener("input",()=>{this.setAppearance({blur:Number(this.blurInput.value)}),this.refreshBlurDistanceBound()}),this.haloScaleInput.addEventListener("input",()=>this.setAppearance({haloScale:Number(this.haloScaleInput.value)}));for(const t of[this.latInput,this.lngInput,this.headingInput,this.pitchInput,this.rollInput,this.elevationInput])t.addEventListener("input",()=>this.updateObserver());for(const t of[this.focalLengthInput,this.fNumberInput,this.exposureInput,this.focusDistanceInput])t.addEventListener("input",()=>this.updateObserver());this.searchPlaceButton.addEventListener("click",()=>void this.searchPlace()),this.placeNameInput.addEventListener("keydown",t=>{t.key==="Enter"&&(t.preventDefault(),this.searchPlace())}),this.placeMatchSelect.addEventListener("change",()=>this.applyPlaceMatch(this.placeMatchSelect.selectedIndex)),this.placeNameInput.addEventListener("input",()=>this.updatePlaceName()),this.headingInput.addEventListener("focus",()=>this.sceneElement.setCompassForced(!0)),this.headingInput.addEventListener("blur",()=>this.sceneElement.setCompassForced(!1)),this.instrumentSelect.addEventListener("change",()=>{const t=this.ufoElement.sighting.instrument;this.ufoElement.sighting.instrumentId=this.instrumentSelect.value;const n=new Map(this.ufoElement.sighting.timeline.allKeyframes.map(i=>[i.t,ln.fovOf(this.ufoElement.sighting,i.t)]));this.retuneFieldOfView(t),this.retuneExposure(t),ln.reproject(this.ufoElement.sighting,t,n),this.sceneElement.applyFrameFormat(),this.syncOpticsFromInstrument(),this.ufoElement.refresh(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.utcOffsetInput.addEventListener("input",()=>this.updateUtcOffset()),this.timeZoneSelect.addEventListener("change",()=>{this.autoFilledTimeZone=void 0,this.updateTimeZone()}),this.obsTimeInput.addEventListener("input",()=>this.updateObservationTime()),this.obsEndTimeInput.addEventListener("input",()=>this.updateObservationEndTime()),this.obsTimeNativeInput.addEventListener("change",()=>this.writeFromPicker(this.obsTimeNativeInput,this.obsTimeQualifier,this.obsTimeInput,()=>this.updateObservationTime())),this.obsEndTimeNativeInput.addEventListener("change",()=>this.writeFromPicker(this.obsEndTimeNativeInput,this.obsEndTimeQualifier,this.obsEndTimeInput,()=>this.updateObservationEndTime())),this.obsTimeQualifier.addEventListener("change",()=>this.writeFromPicker(this.obsTimeNativeInput,this.obsTimeQualifier,this.obsTimeInput,()=>this.updateObservationTime())),this.obsEndTimeQualifier.addEventListener("change",()=>this.writeFromPicker(this.obsEndTimeNativeInput,this.obsEndTimeQualifier,this.obsEndTimeInput,()=>this.updateObservationEndTime())),this.edtfModeButton.addEventListener("click",()=>this.setEdtfMode(!this.edtfMode)),this.obsTimeInput.addEventListener("blur",()=>this.validateEdtfTimeInput(this.obsTimeInput)),this.obsEndTimeInput.addEventListener("blur",()=>this.validateEdtfTimeInput(this.obsEndTimeInput));for(const t of[this.witnessIdInput,this.witnessDirNameInput,this.witnessTitleInput,this.witnessLastNameInput,this.witnessFirstNamesInput,this.witnessAgeInput,this.witnessOccupationInput,this.caseIdInput])t.addEventListener("input",()=>this.updateWitnessMetadata());this.descriptionInput.addEventListener("input",()=>{this.updateDescription(),this.syncNarrativeEnabled()}),this.tagsInput.addEventListener("input",()=>this.updateTags());for(const t of this.weatherFields){if(t===this.iceCrystalAlignmentInput){t.addEventListener("input",()=>this.applyIceAlignmentAtPlayhead());continue}t.addEventListener("input",()=>this.applyWeatherAtPlayhead())}for(const t of this.soundFields)t.addEventListener("input",()=>this.applySoundAtPlayhead());this.weatherInferredInput.addEventListener("change",()=>this.onWeatherInferredToggled()),this.skyDetailsButton=this.shadow.getElementById("sky-details"),this.clampedLines=[this.shadow.getElementById("weather-source"),this.shadow.getElementById("sky-candidates")],this.skyDetailsButton.addEventListener("click",()=>this.toggleSkyDetails()),this.groupTabs=[...this.shadow.querySelectorAll(".group-tab")],this.groupPanels=this.groupTabs.map(t=>this.shadow.getElementById(t.getAttribute("aria-controls")));for(const t of this.groupTabs)t.addEventListener("click",()=>this.toggleGroup(t,!this.isGroupOpen(t)));this.subgroupTabs=[...this.shadow.querySelectorAll(".subgroup-tab")];for(const t of this.subgroupTabs)t.addEventListener("click",()=>this.openSubgroup(t));this.paramSummary=this.shadow.getElementById("param-summary"),this.paramSummaryBuilder=new Bf(this.messages,this.showerLanguage(),this.said,this.tagNames),this.paramSummary.addEventListener("click",t=>this.onParamSummaryClick(t)),this.toggleGroup(this.groupTabs[this.groupTabs.length-1],!0),this.updatePresetButtons(),this.setRecordButtonLabel(!1),this.applyAppearanceAtPlayhead(),this.shapeTitleInput.value=this.shapeLabel(this.currentSourceId),this.updateShapeTitle(),this.currentDecorId=this.ufoElement.sighting.decor[0]?.id,this.refreshDecorList(),this.currentReferenceId=this.ufoElement.sighting.references[0]?.id,this.refreshReferenceList(),this.sceneElement.setCloudRendering("volume"),this.cloudEditor=v1(this.shadow.getElementById("cloud-editor"),this.sceneElement,(t=!0)=>{t&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())},(t,n)=>{this.headingInput.value=String(this.rounded(t)),this.pitchInput.value=String(this.rounded(n)),this.updateObserver()},na(Ts.preferencesFor(this),od)),this.currentMilestoneT=this.ufoElement.sighting.milestones[0]?.t,this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncPlaybackControls(),this.refreshSourceRows(),this.refreshTimeQualifierOptions(),this.refreshTimeZoneOptions(),this.syncWeatherSourceState(),this.loadLocaleMessages()}static get observedAttributes(){return["src"]}connectedCallback(){this.hasAttribute("tabindex")||(this.tabIndex=-1);const e=this.getAttribute("src");e&&this.importFromUrl(e)}attributeChangedCallback(e,t,n){e==="src"&&n&&n!==t&&this.isConnected&&this.importFromUrl(n)}disconnectedCallback(){this.cloudEditor.stopManipulation(),document.removeEventListener("click",this.handleOutsideContextMenuClick),this.endDrag()}setCloudRendering(e){this.sceneElement.setCloudRendering(e)}showWeatherEditor(){const e=this.groupPanels.findIndex(t=>t.id==="group-weather");e>=0&&this.toggleGroup(this.groupTabs[e],!0)}get sightingData(){return this.ufoElement.sightingData}set sightingData(e){this.endDrag(),this.ufoElement.sightingData=e,this.cloudEditor.reset(),this.currentSourceId=this.ufoElement.sighting.timeline.sourceIds[0]??kl,this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.currentDecorId=this.ufoElement.sighting.decor[0]?.id,this.refreshDecorList(),this.currentReferenceId=this.ufoElement.sighting.references[0]?.id,this.refreshReferenceList(),this.currentMilestoneT=this.ufoElement.sighting.milestones[0]?.t,this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncObservationTimeFields(),this.syncObservationEndTimeFields(),this.chooseTimeInputMode(),this.syncWitnessMetadataFields(),this.refreshTimeZoneOptions(),this.utcOffsetInput.readOnly=this.ufoElement.sighting.event.timeZone!==void 0,this.syncUtcOffsetField(),this.syncPlaceNameField(),this.syncGroundElevationField(),this.syncWeatherOwnership()}exportJson(){const e=this.sightingData,t=`${e.witness?.id??"sighting"}-sighting.json`,n=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),i=URL.createObjectURL(n),s=document.createElement("a");s.href=i,s.download=t,s.click(),URL.revokeObjectURL(i)}async importFromFile(){const e=this.importFileInput.files?.[0];if(e)try{const t=await new Promise((n,i)=>{const s=new FileReader;s.onload=()=>n(s.result),s.onerror=()=>i(s.error),s.readAsText(e)});this.sightingData=JSON.parse(t)}catch{window.alert(this.messages.importError)}finally{this.importFileInput.value=""}}async importFromUrl(e=this.importUrlInput.value.trim()){if(e)try{this.sightingData=await Lu.json(e)}catch(t){window.alert(this.importErrorFor(t))}}importErrorFor(e){if(!(e instanceof Vs))return this.messages.importError;switch(e.kind){case"cors":return this.messages.importErrorCors;case"mixed-content":return this.messages.importErrorMixedContent;case"unreachable":return this.messages.importErrorUnreachable;case"status":return this.messages.importErrorStatus.replace("{status}",String(e.status??""));case"malformed":return this.messages.importErrorMalformed;default:return this.messages.importError}}static NARRATIVE_KEY_STORAGE="rr0-sighting-editor.narrative-key";static NARRATIVE_SCOPE_STORAGE="rr0-sighting-editor.narrative-workspace";narrativeProvider=Ns[0].create();narrativeAbort;async draftFromDescription(){const e=this.descriptionInput.value.trim();if(e===""||this.narrativeAbort)return;const t=this.narrativeAbort=new AbortController;this.setNarrativeBusy(!0);try{const n=await this.narrativeProvider.draft({ask:e,current:this.sightingData,language:this.showerLanguage()==="fr"?"French":"English",credential:this.narrativeKeyInput.value.trim()||void 0,credentialScope:this.narrativeWorkspaceInput.value.trim()||void 0},t.signal);this.applyNarrativeDraft(n)}catch(n){const i=n instanceof Un&&n.kind==="cancelled";this.narrativeStatus.textContent=i?"":this.narrativeErrorFor(n),this.narrativeStatus.classList.toggle("error",!i)}finally{this.narrativeAbort=void 0,this.setNarrativeBusy(!1)}}applyNarrativeDraft(e){const{description:t,...n}=e.recording,{utcOffsetHours:i,...s}=n,a=n.timeZone?s:n,o=Si.stated(a);if(o.length>0){const l=this.ufoElement.sighting.provenance,c=ad(this.ufoElement.sighting);this.sightingData=Si.apply(c,Jl.loadable(a),o),this.ufoElement.sighting.provenance=l,this.recordNarrativeProvenance(e,o),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset()}this.narrativeStatus.textContent=o.length>0?this.messages.narrativeApplied.replace("{count}",String(o.length)):this.messages.narrativeUnchanged,this.narrativeStatus.classList.remove("error"),this.showNarrativeReport(e),this.syncNarrativeEnabled()}recordNarrativeProvenance(e,t){const n=this.ufoElement.sighting,i=new Set(t);for(const s of e.claims)!i.has(s.path)&&!t.some(a=>s.path.startsWith(`${a}.`))||n.provenance.set(s.path,{basis:s.basis,rationale:s.rationale,of:Tt.valueAt(ad(this.ufoElement.sighting),s.path)})}static valueAt(e,t){let n=e;for(const i of t.split(".")){if(typeof n!="object"||n===null)return;n=n[i]}return n}showNarrativeReport(e){this.narrativeReport.replaceChildren();for(const t of["assumed","derived","stated"]){const n=e.claims.filter(i=>i.basis===t);if(n.length!==0){this.narrativeReport.append(this.narrativeHeading(this.messages[XA[t]]));for(const i of n){const s=document.createElement("div");s.className=`claim ${t}`;const a=document.createElement("code");a.textContent=i.path;const o=document.createElement(t==="stated"?"q":"span");o.textContent=i.rationale,s.append(a,o),this.narrativeReport.append(s)}}}if(e.gaps.length>0){this.narrativeReport.append(this.narrativeHeading(this.messages.narrativeGaps));const t=document.createElement("ul");t.className="gaps";for(const n of e.gaps){const i=document.createElement("li");i.textContent=n,t.append(i)}this.narrativeReport.append(t)}this.narrativeReport.hidden=this.narrativeReport.childElementCount===0}narrativeHeading(e){const t=document.createElement("h4");return t.textContent=e,t}setNarrativeBusy(e){this.descriptionInput.disabled=e,this.narrativeStopButton.hidden=!e,e&&(this.narrativeStatus.textContent=this.messages.narrativeWorking,this.narrativeStatus.classList.remove("error")),this.syncNarrativeEnabled()}syncNarrativeEnabled(){const e=Ns[0].name,t=this.narrativeProvider.needsCredential&&this.narrativeKeyInput.value.trim()==="",n=this.descriptionInput.value.trim()==="";this.narrativeDraftButton.disabled=!!this.narrativeAbort||t||n,this.narrativeDraftButton.title=t?this.messages.narrativeNeedsKey.replace("{source}",e):n?this.messages.narrativeNeedsAsk:"",this.narrativeKeyInput.parentElement.hidden=!this.narrativeProvider.needsCredential,this.narrativeRememberInput.parentElement.hidden=!this.narrativeProvider.needsCredential,this.narrativeWorkspaceInput.parentElement.hidden=!this.narrativeProvider.acceptsCredentialScope;const i=this.narrativeKeyInput.value.trim(),s=i!==""&&!i.startsWith("sk-ant-");this.narrativeKeyInput.classList.toggle("invalid",s),this.narrativeKeyInput.title=s?this.messages.narrativeKeyUnlikely:""}narrativeErrorFor(e){if(!(e instanceof Un))return this.messages.narrativeErrorMalformed;switch(e.kind){case"rejected":return this.messages.narrativeErrorRejected.replace("{detail}",e.detail??"");case"credential":return this.messages.narrativeErrorCredential;case"rate-limited":return this.messages.narrativeErrorRateLimited;case"refused":return this.messages.narrativeErrorRefused;case"unreachable":return this.messages.narrativeErrorUnreachable;default:return this.messages.narrativeErrorMalformed}}rememberNarrativeKey(){try{this.narrativeRememberInput.checked?(localStorage.setItem(Tt.NARRATIVE_KEY_STORAGE,this.narrativeKeyInput.value),localStorage.setItem(Tt.NARRATIVE_SCOPE_STORAGE,this.narrativeWorkspaceInput.value)):(localStorage.removeItem(Tt.NARRATIVE_KEY_STORAGE),localStorage.removeItem(Tt.NARRATIVE_SCOPE_STORAGE))}catch{}}restoreNarrativeKey(){let e=null;try{e=localStorage.getItem(Tt.NARRATIVE_KEY_STORAGE)}catch{return}e!==null&&(this.narrativeKeyInput.value=e,this.narrativeWorkspaceInput.value=localStorage.getItem(Tt.NARRATIVE_SCOPE_STORAGE)??"",this.narrativeRememberInput.checked=!0)}numberOrUndefined(e){return e===""?void 0:Number(e)}stringOrUndefined(e){return e===""?void 0:e}wrapDegrees(e,t){if(e===void 0)return;const n=(e%360+360)%360;return String(n)!==t.value&&(t.value=String(n)),n}refreshSourceRows(){this.placeSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),this.sourcePicker("place",EA,e=>{this.placeProvider=e.create()})),this.weatherSourceRow.replaceChildren(this.sourcePicker("weather",TA,e=>{this.weatherInference=new Yh(e.create()),this.scheduleWeatherLookup()})),this.terrainSourceRows.replaceChildren(this.labelledPicker("elevation",this.messages.sourceElevation,jh,()=>this.applyTerrainSources()),this.labelledPicker("imagery",this.messages.sourceImagery,Fm,()=>this.applyTerrainSources()),this.labelledPicker("decor-model",this.messages.decorModel,Xl,()=>this.applyDecorModelSource()))}sourcePicker(e,t,n){const i=document.createDocumentFragment(),s=document.createElement("select");s.id=`${e}Source`;for(const l of t){const c=document.createElement("option");c.value=l.id,c.textContent=l.name,c.title=l.credit,s.appendChild(c)}s.value=this.chosenSourceId.get(e)??t[0].id;const a=document.createElement("a");a.className="source-credit",a.target="_blank",a.rel="noopener noreferrer";const o=()=>{const l=Wr(t,s.value);s.title=l.credit,a.href=l.creditUrl,a.textContent=l.credit};return o(),s.addEventListener("change",()=>{this.chosenSourceId.set(e,s.value),o(),n(Wr(t,s.value))}),i.append(s,document.createTextNode(" "),a),i}labelledPicker(e,t,n,i){const s=document.createElement("label"),a=document.createElement("span");return a.textContent=t,s.append(a,this.sourcePicker(e,n,i)),s}applyTerrainSources(){this.sceneElement.setTerrainProviders({elevation:Wr(jh,this.chosenSourceId.get("elevation")).create(),imagery:Wr(Fm,this.chosenSourceId.get("imagery")).create()}),this.ufoElement.refresh()}applyDecorModelSource(){this.decorModelProvider=Wr(Xl,this.chosenSourceId.get("decor-model")).create(),this.sceneElement.setDecorModelProvider(this.decorModelProvider),this.refreshDecorModelOptions(),this.ufoElement.refresh()}get placeSearchLanguage(){return navigator.languages?.[0]}set placeSearchProvider(e){this.placeProvider=e}async searchPlace(){const e=this.placeNameInput.value.trim();if(e==="")return;const t=++this.placeSearchToken;this.placeStatusText.textContent=this.messages.placeSearching;let n;try{n=await this.placeProvider.search(e,{language:this.placeSearchLanguage})}catch{if(t!==this.placeSearchToken)return;this.placeStatusText.textContent=this.messages.placeSearchFailed;return}t===this.placeSearchToken&&(this.placeMatches=n,this.refreshPlaceMatches(),n.length>0&&this.applyPlaceMatch(0))}refreshPlaceMatches(){this.placeMatchSelect.replaceChildren(...this.placeMatches.map(t=>{const n=document.createElement("option");return n.textContent=t.name,n.title=t.name,n})),this.placeMatchRow.hidden=this.placeMatches.length===0;const e=this.placeMatches.length===1?this.messages.placeMatchFound:this.messages.placeMatchesFound;this.placeStatusText.textContent=this.placeMatches.length===0?this.messages.placeNotFound:`${this.placeMatches.length} ${e} `,this.placeSourceRow.hidden=this.placeMatches.length===0}applyPlaceMatch(e){const t=this.placeMatches[e];t&&(this.placeMatchSelect.selectedIndex=e,this.placeNameInput.value=t.name,this.placeNameInput.title=t.name,this.latInput.value=String(t.lat),this.lngInput.value=String(t.lng),this.namedCoordinates={lat:t.lat,lng:t.lng},this.updateObserver())}updatePlaceName(){this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent="",this.placeSourceRow.hidden=!0,this.placeNameInput.title=this.placeNameInput.value,this.namedCoordinates=void 0,this.updateObserver()}schedulePlaceReverse(){if(!this.namedCoordinates)return;const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);e===void 0||t===void 0||Math.abs(e-this.namedCoordinates.lat)<Xr&&Math.abs(t-this.namedCoordinates.lng)<Xr||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(e,t),Bm))}scheduleTimeZoneLookup(){const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);if(e===void 0||t===void 0)return;const n=this.ufoElement.sighting.event.timeZone;if(n&&n!==this.autoFilledTimeZone)return;const i=this.timeZoneLookedUpAt;i&&Math.abs(e-i.lat)<Xr&&Math.abs(t-i.lng)<Xr||(clearTimeout(this.timeZoneLookupTimer),this.timeZoneLookupTimer=setTimeout(()=>void this.lookUpTimeZone(e,t),Bm))}async lookUpTimeZone(e,t){this.timeZoneLookedUpAt={lat:e,lng:t};const n=await this.timeZoneProvider.zoneAt(e,t),i=this.ufoElement.sighting.event.timeZone;!n||i&&i!==this.autoFilledTimeZone||this.timeZones.available().includes(n)&&(this.autoFilledTimeZone=n,this.timeZoneSelect.value=n,this.updateTimeZone(),this.dispatchEvent(new CustomEvent("sightingchange")))}async reversePlace(e,t){const n=++this.placeSearchToken;let i;try{i=await this.placeProvider.reverse(e,t,{language:this.placeSearchLanguage})}catch{return}n===this.placeSearchToken&&(this.namedCoordinates={lat:e,lng:t},this.placeNameInput.value=i?.name??"",this.placeNameInput.title=i?.name??"",this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent=i?"":this.messages.placeNotFound,this.placeSourceRow.hidden=!i,this.updateObserver())}updateObserver(){if(this.ufoElement.playbackState==="playing")return;const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value),n=this.wrapDegrees(this.numberOrUndefined(this.headingInput.value),this.headingInput),i=this.numberOrUndefined(this.pitchInput.value)??0,s=this.numberOrUndefined(this.rollInput.value)??0,a=this.numberOrUndefined(this.elevationInput.value)??this.groundElevationM??0,o=Math.max(0,a-(this.groundElevationM??0)),l=this.ufoElement.sighting.event,c=this.ufoElement.sighting.witnessTrack,h=this.ufoElement.currentTime,d=this.stringOrUndefined(this.placeNameInput.value.trim());l.place=e!==void 0&&t!==void 0?[{lat:e,lng:t,name:d}]:void 0;const u=this.ufoElement.sighting.instrument,f=this.numberOrUndefined(this.focalLengthInput.value),p=(u.frame&&f!==void 0?rt.fieldOfViewDegAt(u,f):f)??this.currentFovDeg(),v=this.numberOrUndefined(this.fNumberInput.value),m=this.statedExposureSeconds(u);this.ufoElement.sighting.exposureSeconds=m===u.exposureSeconds?void 0:m;const g=this.numberOrUndefined(this.focusDistanceInput.value),M=Math.abs(p-rt.fieldOfViewDeg(u))>.01||v!==u.fNumber||g!==void 0;e===void 0&&t===void 0&&n===void 0&&i===0&&s===0&&o===0&&!M?c.removeKeyframeAt(h):c.addKeyframe(h,{lat:e,lng:t,elevationM:o,headingDeg:n,pitchDeg:i,rollDeg:s===0?void 0:s,fovDeg:p,fNumber:v,focusDistanceM:g}),this.ufoElement.refresh(),this.scheduleWeatherLookup(),this.schedulePlaceReverse(),this.scheduleTimeZoneLookup(),this.scheduleGroundElevation(),this.updateUtcOffsetValidity()}applyEdtfTimeInput(e,t){const n=e.value.trim();if(n==="")t(void 0);else{const i=Tf(n);if(!i)return;t(i)}e.setCustomValidity(""),e.classList.remove("invalid"),this.dropDurationOutrankedByDates(),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset(),this.ufoElement.refresh(),this.syncDurationField(),this.scheduleWeatherLookup()}dropDurationOutrankedByDates(){const e=this.ufoElement.sighting.event;e.durationSeconds!==void 0&&ua({...e,durationSeconds:void 0})!==void 0&&(this.ufoElement.durationSeconds=void 0)}validateEdtfTimeInput(e){const t=e.value.trim();t===""||Tf(t)||(e.setCustomValidity(this.messages.edtfInvalid),e.classList.add("invalid"))}refreshTimeZoneOptions(){const e=document.createElement("option");e.value="",e.textContent=this.messages.timeZoneManual,this.timeZoneSelect.replaceChildren(e,...this.timeZones.available().map(t=>{const n=document.createElement("option");return n.value=t,n.textContent=t,n})),this.timeZoneSelect.value=this.ufoElement.sighting.event.timeZone??""}updateTimeZone(){const e=this.stringOrUndefined(this.timeZoneSelect.value);this.ufoElement.sighting.event.timeZone=e,this.applyTimeZoneOffset()}applyTimeZoneOffset(){const e=this.ufoElement.sighting.event,t=e.timeZone&&e.time?this.timeZones.offsetHoursAt(e.timeZone,e.time):void 0;t!==void 0&&(e.utcOffsetHours=t),this.utcOffsetInput.readOnly=e.timeZone!==void 0,this.syncUtcOffsetField(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}updateUtcOffset(){this.ufoElement.sighting.event.utcOffsetHours=this.numberOrUndefined(this.utcOffsetInput.value),this.updateUtcOffsetValidity(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}updateObservationTime(){this.applyEdtfTimeInput(this.obsTimeInput,e=>{this.ufoElement.sighting.event.time=e})}updateObservationEndTime(){this.applyEdtfTimeInput(this.obsEndTimeInput,e=>{this.ufoElement.sighting.event.endTime=e})}updateWitnessMetadata(){const e=this.ufoElement.sighting,t=this.witnessFirstNamesInput.value.split(",").map(i=>i.trim()).filter(i=>i.length>0),n={id:this.stringOrUndefined(this.witnessIdInput.value),dirName:this.stringOrUndefined(this.witnessDirNameInput.value),title:this.stringOrUndefined(this.witnessTitleInput.value),lastName:this.stringOrUndefined(this.witnessLastNameInput.value),firstNames:t.length>0?t:void 0};e.witness=Object.values(n).some(i=>i!==void 0)?n:void 0,e.caseId=this.stringOrUndefined(this.caseIdInput.value),this.updateTestimony(),this.ufoElement.refresh()}updateTestimony(){const e=this.ufoElement.sighting,t=this.testimonyFollowedUpSelect.value,n={witnessAgeYears:this.numberOrUndefined(this.witnessAgeInput.value),witnessOccupation:this.witnessOccupationInput.value.trim()===""?void 0:this.said.write(e.testimony?.witnessOccupation,this.witnessOccupationInput.value,this.writingLanguage),source:this.stringOrUndefined(this.testimonySourceSelect.value),followedUp:t===""?void 0:t==="yes"};e.testimony=Object.values(n).some(i=>i!==void 0)?n:void 0}updateDescription(){this.ufoElement.sighting.event.description=this.said.write(this.ufoElement.sighting.event.description,this.descriptionInput.value,this.writingLanguage),this.ufoElement.refresh()}updateTags(){const e=this.tagsInput.value.split(",").map(t=>t.trim()).filter(t=>t.length>0).map(t=>this.tagNames.stored(t));this.ufoElement.sighting.event.tags=e.length>0?e:void 0,this.ufoElement.refresh()}applyWeatherAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;this.sceneElement.resumeWeatherAudio(),this.weatherFromRecords&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState());const e={...Ut(this.ufoElement.sighting,this.ufoElement.currentTime),cloudCover:Number(this.cloudCoverInput.value),highCloudCover:Number(this.highCloudCoverInput.value),lowerCloudCover:Number(this.cloudCoverInput.value),cloudDarkness:Number(this.cloudDarknessInput.value),cloudBaseM:this.numberOrUndefined(this.cloudBaseInput.value),precipitationType:this.precipitationTypeSelect.value,precipitationIntensity:Number(this.precipitationIntensityInput.value),windDirectionDeg:this.wrapDegrees(this.numberOrUndefined(this.windDirectionInput.value),this.windDirectionInput)??0,windSpeed:Number(this.windSpeedInput.value),storm:this.stormInput.checked};this.ufoElement.sighting.weatherTrack.addKeyframe(this.ufoElement.currentTime,e),this.ufoElement.refresh()}applyIceAlignmentAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;this.sceneElement.resumeWeatherAudio();const e={...Ut(this.ufoElement.sighting,this.ufoElement.currentTime),iceCrystalAlignment:Number(this.iceCrystalAlignmentInput.value)};this.ufoElement.sighting.weatherTrack.addKeyframe(this.ufoElement.currentTime,e),this.ufoElement.refresh()}referenceLabel(e){return this.said.read(e.title)||e.src.replace(/^data:.*$/,"…")||e.id}refreshReferenceList(){const e=this.ufoElement.sighting.references;this.referenceSelect.innerHTML="";for(const t of e){const n=document.createElement("option");n.value=t.id,n.textContent=this.referenceLabel(t),this.referenceSelect.appendChild(n)}this.currentReferenceId!==void 0&&(this.referenceSelect.value=this.currentReferenceId),this.syncReferenceFields()}selectReference(e){this.currentReferenceId=e,this.referenceSelect.value=e,this.disarmLandmark(),this.currentLandmarkId=void 0,this.referenceFit=void 0,this.syncReferenceFields()}syncReferenceFields(){const e=this.ufoElement.sighting.references.find(i=>i.id===this.currentReferenceId),t=e!==void 0;this.deleteReferenceButton.disabled=!t,this.referenceUsePoseButton.disabled=!t;for(const i of[this.referenceSelect,...this.referenceFields])i.disabled=!t,this.setRowVisible(i,t);this.setRowVisible(this.referenceUsePoseButton,t);for(const i of[this.referenceLandmarksSelect,this.addReferenceLandmarkButton,this.deleteReferenceLandmarkButton,this.referenceLandmarkLabelInput])this.setRowVisible(i,t);if(this.refreshLandmarkList(),this.setRowVisible(this.referenceAdoptPoseButton,t),this.syncCanvasMode(),!e){this.referenceStatus.textContent="";return}this.referenceTitleInput.value=this.said.read(e.title)??"";const n=e.src.startsWith("data:");this.referenceSrcInput.value=n?"":e.src,this.referenceSrcInput.disabled=n,this.referenceKindSelect.value=e.kind,this.referenceCreditInput.value=e.credit??"",this.referenceCreditUrlInput.value=e.creditUrl??"",this.referenceTInput.value=e.t===void 0?"":String(e.t/1e3),this.referenceDrawingInput.checked=e.drawing===!0,this.referenceOpacityInput.value=String(e.opacity),this.referenceHeadingInput.value=String(e.registration.headingDeg),this.referencePitchInput.value=String(e.registration.pitchDeg),this.referenceRollInput.value=String(e.registration.rollDeg??0),this.referenceFovInput.value=String(e.registration.fovDeg),this.syncReferenceStatus(e)}syncReferenceStatus(e){if(this.canvasMode()==="picture"){this.syncRegisterStatus();return}if(e.src.startsWith("data:")){const t=Math.round(e.src.length*3/4/1024);this.referenceStatus.textContent=e.src.length>lA?this.messages.referenceEmbedded.replace("{kb}",String(t)):"";return}this.referenceStatus.textContent=this.sceneElement.referenceFailedToLoad(e.src)?this.messages.referenceUnreachable:""}updateReference(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting,t=this.wrapDegrees(Number(this.referenceHeadingInput.value),this.referenceHeadingInput)??0,n=this.referenceTInput.value.trim()===""?void 0:Number(this.referenceTInput.value);e.references=e.references.map(s=>{if(s.id!==this.currentReferenceId)return s;const a=s.src.startsWith("data:")?s.src:this.referenceSrcInput.value.trim();return{...s,kind:this.referenceKindSelect.value,src:a,title:this.said.write(s.title,this.referenceTitleInput.value,this.writingLanguage),credit:this.stringOrUndefined(this.referenceCreditInput.value),creditUrl:this.stringOrUndefined(this.referenceCreditUrlInput.value),t:n===void 0||Number.isNaN(n)?void 0:Math.round(n*1e3),drawing:this.referenceDrawingInput.checked||void 0,opacity:Number(this.referenceOpacityInput.value),registration:{headingDeg:t,pitchDeg:Number(this.referencePitchInput.value)||0,rollDeg:Number(this.referenceRollInput.value)||void 0,fovDeg:Math.min(179,Math.max(1,Number(this.referenceFovInput.value)||Pl))}}});const i=e.references.find(s=>s.id===this.currentReferenceId);this.referenceSelect.options[this.referenceSelect.selectedIndex].textContent=this.referenceLabel(i),this.syncReferenceStatus(i),this.ufoElement.refresh()}useWitnessPoseForReference(){const e=tt(this.ufoElement.sighting,this.ufoElement.currentTime);e&&(this.referenceHeadingInput.value=String(this.rounded(e.headingDeg??0)),this.referencePitchInput.value=String(this.rounded(e.pitchDeg)),this.referenceRollInput.value=String(this.rounded(e.rollDeg??0)),this.referenceFovInput.value=String(this.rounded(e.fovDeg)),this.updateReference())}addReference(e,t,n={}){const i=this.ufoElement.sighting,s=tt(this.ufoElement.sighting,this.ufoElement.currentTime),a=`picture-${i.references.length+1}`,o={id:a,kind:"photo",src:e,title:t?this.said.write(void 0,t,this.writingLanguage):void 0,opacity:oA,registration:{headingDeg:s?.headingDeg??0,pitchDeg:s?.pitchDeg??0,fovDeg:Pl},...n};i.references=[...i.references,o],this.currentReferenceId=a,this.refreshReferenceList(),this.ufoElement.refresh()}addReferenceFromAddress(){this.addReference(""),this.referenceSrcInput.focus()}async addReferenceFromFile(){const e=this.addReferenceFileInput.files?.[0];if(!e)return;const t=await new Promise((n,i)=>{const s=new FileReader;s.onload=()=>n(s.result),s.onerror=()=>i(s.error),s.readAsDataURL(e)});this.addReferenceFileInput.value="",this.addReference(t,e.name.replace(/\.[^.]+$/,""))}currentReference(){return this.ufoElement.sighting.references.find(e=>e.id===this.currentReferenceId)}currentLandmarks(){return this.currentReference()?.landmarks??[]}writeLandmarks(e){const t=this.ufoElement.sighting;t.references=t.references.map(n=>n.id===this.currentReferenceId?{...n,landmarks:e.length>0?e:void 0}:n)}beginReferenceDrag(e){const t=this.currentReference();if(!t)return;if(this.armingLandmark||this.pendingLandmark){this.nameLandmarkAt(e);return}const n=this.landmarkEndAt(e);if(n){this.selectLandmark(n.landmarkId),this.referenceDragState={kind:"anchor",...n},this.setCanvasCursor("landmark"),this.startDragListening();return}this.referenceDragState={kind:"picture",startPointer:e,startHeadingDeg:t.registration.headingDeg,startPitchDeg:t.registration.pitchDeg,moved:!1},this.setCanvasCursor("panning"),this.startDragListening()}landmarkEndAt(e){const t=this.currentReference(),n=t?this.sceneElement.referenceAspect(t.id):void 0;if(!t||n===void 0)return;const i=8;for(const s of this.currentLandmarks()){const a=this.canvasPointOfDirection(Fn.worldDirectionOf(s.picture,t.registration,n));if(a&&Math.hypot(a.x-e.x,a.y-e.y)<=i)return{landmarkId:s.id,end:"picture"};const o=this.canvasPointOfDirection(Fn.worldDirection(s.scene));if(o&&Math.hypot(o.x-e.x,o.y-e.y)<=i)return{landmarkId:s.id,end:"scene"}}}onReferenceDragPointerMove(e){const t=this.referenceDragState,n=this.canvasPointFromEvent(e);if(!t||!n)return;if(t.kind==="anchor"){this.moveLandmarkEnd(t.landmarkId,t.end,n);return}const i=n.x-t.startPointer.x,s=n.y-t.startPointer.y;if(!t.moved&&Math.hypot(i,s)<3)return;t.moved=!0;const a=this.currentFovDeg()/this.ufoElement.canvasElement.height;this.referenceHeadingInput.value=String(this.rounded(t.startHeadingDeg+i*a)),this.referencePitchInput.value=String(this.rounded(Math.max(-90,Math.min(90,t.startPitchDeg-s*a)))),this.updateReference()}moveLandmarkEnd(e,t,n){const i=this.currentReference(),s=i?this.sceneElement.referenceAspect(i.id):void 0;if(!i||s===void 0)return;const a=this.directionAtCanvasPoint(n);this.writeLandmarks(this.currentLandmarks().map(o=>{if(o.id!==e)return o;if(t==="scene")return{...o,scene:Fn.aimOf(a)};const l=Fn.picturePointOf(a,i.registration,s);return l?{...o,picture:l}:o})),this.ufoElement.refresh()}endReferenceDrag(){const e=this.referenceDragState;this.referenceDragState=void 0,this.setCanvasCursor(this.canvasMode()==="picture"?"pan":this.hoverCursor),document.removeEventListener("pointermove",this.handleDragPointerMove),document.removeEventListener("pointerup",this.handleDragPointerUp),e?.kind==="anchor"&&this.fitReferenceToLandmarks()}onReferenceWheel(e){if(this.canvasMode()!=="picture")return;e.preventDefault();const t=Number(this.referenceFovInput.value)||Pl,n=Math.min(179,Math.max(1,t*Math.exp(Math.sign(e.deltaY)*.05)));this.referenceFovInput.value=String(this.rounded(n)),this.updateReference()}directionAtCanvasPoint(e){const t=this.ufoElement.canvasElement;return this.sceneElement.directionAt(e.x/t.width*2-1,-(e.y/t.height*2-1))}armLandmark(){this.currentReference()&&(this.armingLandmark=!0,this.pendingLandmark=void 0,this.setCanvasCursor("landmark"),this.syncRegisterStatus(),this.ufoElement.refresh())}disarmLandmark(){this.armingLandmark=!1,this.pendingLandmark=void 0,this.canvasMode()==="picture"&&(this.setCanvasCursor("pan"),this.syncRegisterStatus()),this.ufoElement.refresh()}nameLandmarkAt(e){const t=this.currentReference();if(!t)return;const n=this.directionAtCanvasPoint(e);if(!this.pendingLandmark){const a=this.sceneElement.referenceAspect(t.id);if(a===void 0){this.referenceStatus.textContent=this.messages.referenceNotLoaded;return}const o=Fn.picturePointOf(n,t.registration,a);if(!o){this.referenceStatus.textContent=this.messages.referenceLandmarkOffPicture;return}this.pendingLandmark=o,this.syncRegisterStatus(),this.ufoElement.refresh();return}const i=this.currentLandmarks(),s=this.nextLandmarkId(i);this.writeLandmarks([...i,{id:s,picture:this.pendingLandmark,scene:Fn.aimOf(n)}]),this.armingLandmark=!1,this.pendingLandmark=void 0,this.currentLandmarkId=s,this.setCanvasCursor("pan"),this.fitReferenceToLandmarks()}nextLandmarkId(e){let t=e.length+1;for(;e.some(n=>n.id===`landmark-${t}`);)t++;return`landmark-${t}`}fitReferenceToLandmarks(){const e=this.currentReference(),t=e?this.sceneElement.referenceAspect(e.id):void 0;if(!e||t===void 0)return;const n=this.currentLandmarks(),i=Fn.solve(n,t,e.registration.fovDeg);i?(this.referenceFit={n:n.length,residualDeg:i.residualDeg},this.referenceHeadingInput.value=String(this.rounded(i.registration.headingDeg)),this.referencePitchInput.value=String(this.rounded(i.registration.pitchDeg)),this.referenceRollInput.value=String(this.rounded(i.registration.rollDeg??0)),this.referenceFovInput.value=String(this.rounded(i.registration.fovDeg)),this.updateReference()):this.referenceFit=void 0,this.refreshLandmarkList(),this.syncRegisterStatus(),this.ufoElement.refresh()}landmarkResidualDeg(e,t,n){return Fn.worldDirectionOf(e.picture,t.registration,n).angleTo(Fn.worldDirection(e.scene))*180/Math.PI}landmarkLabel(e,t){const n=this.said.read(e.label);return n?`${t+1} · ${n}`:String(t+1)}refreshLandmarkList(){const e=this.currentReference(),t=this.currentLandmarks(),n=e?this.sceneElement.referenceAspect(e.id):void 0;this.referenceLandmarksSelect.innerHTML="";for(const[s,a]of t.entries()){const o=document.createElement("option");o.value=a.id;const l=e&&n!==void 0?` · ${this.landmarkResidualDeg(a,e,n).toFixed(1)}°`:"";o.textContent=this.landmarkLabel(a,s)+l,this.referenceLandmarksSelect.appendChild(o)}this.currentLandmarkId!==void 0&&!t.some(s=>s.id===this.currentLandmarkId)&&(this.currentLandmarkId=void 0),this.currentLandmarkId!==void 0&&(this.referenceLandmarksSelect.value=this.currentLandmarkId);const i=t.find(s=>s.id===this.currentLandmarkId);this.referenceLandmarksSelect.disabled=t.length===0,this.deleteReferenceLandmarkButton.disabled=i===void 0,this.referenceLandmarkLabelInput.disabled=i===void 0,this.shadow.activeElement!==this.referenceLandmarkLabelInput&&(this.referenceLandmarkLabelInput.value=this.said.read(i?.label)??"")}selectLandmark(e){this.currentLandmarkId=e,this.refreshLandmarkList(),this.ufoElement.refresh()}updateLandmarkLabel(){const e=this.currentLandmarkId;if(e===void 0)return;this.writeLandmarks(this.currentLandmarks().map(o=>o.id===e?{...o,label:this.said.write(o.label,this.referenceLandmarkLabelInput.value,this.writingLanguage)}:o));const t=this.referenceLandmarksSelect.options[this.referenceLandmarksSelect.selectedIndex],n=this.currentLandmarks(),i=n.findIndex(o=>o.id===e),s=this.currentReference(),a=s?this.sceneElement.referenceAspect(s.id):void 0;if(t&&i>=0){const o=s&&a!==void 0?` · ${this.landmarkResidualDeg(n[i],s,a).toFixed(1)}°`:"";t.textContent=this.landmarkLabel(n[i],i)+o}this.ufoElement.refresh()}deleteLandmark(){const e=this.currentLandmarkId;if(e===void 0)return;const t=this.currentLandmarks().filter(n=>n.id!==e);this.writeLandmarks(t),this.currentLandmarkId=t[t.length-1]?.id,this.fitReferenceToLandmarks()}landmarkHint(){const e=this.currentLandmarks().length+1;if(this.pendingLandmark)return this.messages.referenceLandmarkScene.replace("{n}",String(e));if(this.armingLandmark)return this.messages.referenceLandmarkPicture.replace("{n}",String(e))}syncRegisterStatus(){const e=this.landmarkHint();e?this.referenceStatus.textContent=e:this.referenceFit?this.referenceStatus.textContent=this.messages.referenceLandmarksFit.replace("{n}",String(this.referenceFit.n)).replace("{deg}",this.referenceFit.residualDeg.toFixed(1)):this.referenceStatus.textContent=this.messages.referenceRegisterHint}canvasPointOfDirection(e){const t=this.sceneElement.screenPointOf(e);if(!t)return;const n=this.ufoElement.canvasElement;return{x:(t.ndcX+1)/2*n.width,y:(1-t.ndcY)/2*n.height}}paintPictureOverlay=e=>{const t=this.currentReference();if(!t)return;const n=this.sceneElement.referenceAspect(t.id);if(n===void 0)return;const{registration:i}=t,s=[{u:0,v:0},{u:1,v:0},{u:1,v:1},{u:0,v:1}].map(o=>this.canvasPointOfDirection(Fn.worldDirectionOf(o,i,n))),a=this.currentLandmarks().map((o,l)=>({picture:this.canvasPointOfDirection(Fn.worldDirectionOf(o.picture,i,n)),scene:this.canvasPointOfDirection(Fn.worldDirection(o.scene)),label:this.landmarkLabel(o,l),selected:o.id===this.currentLandmarkId,residualDeg:this.landmarkResidualDeg(o,t,n)}));this.pendingLandmark&&a.push({picture:this.canvasPointOfDirection(Fn.worldDirectionOf(this.pendingLandmark,i,n)),scene:void 0,label:String(this.currentLandmarks().length+1),selected:!0,residualDeg:void 0}),e.paintPictureFrame(s.every(o=>o!==void 0)?s:void 0,a.filter(o=>o.picture!==void 0),this.landmarkHint())};adoptReferencePose(){const e=this.currentReference();if(!e)return;const{headingDeg:t,pitchDeg:n,rollDeg:i}=e.registration;this.headingInput.value=String(this.rounded(t)),this.pitchInput.value=String(this.rounded(n)),this.rollInput.value=String(this.rounded(i??0)),this.updateObserver();const s=this.ufoElement.currentTime,a=this.ufoElement.sighting.witnessTrack.toJSON().keyframes.findIndex(c=>c.t===s);if(a<0)return;const o=this.messages.referenceAdoptRationale.replace("{title}",this.referenceLabel(e)).replace("{n}",String(this.currentLandmarks().length)).replace("{deg}",(this.referenceFit?.residualDeg??0).toFixed(1)),l=[["headingDeg",t],["pitchDeg",n],["rollDeg",i??0]];for(const[c,h]of l)this.ufoElement.sighting.provenance.set(`witnessTrack.keyframes.${a}.pose.${c}`,{basis:"derived",rationale:o,of:this.rounded(h)})}syncStreetSearchAvailability(){const e=this.numberOrUndefined(this.latInput.value)!==void 0&&this.numberOrUndefined(this.lngInput.value)!==void 0;this.referenceStreetSearchButton.disabled=!e}async searchStreetPictures(){const e=tt(this.ufoElement.sighting,0),t=e?.lat??this.numberOrUndefined(this.latInput.value),n=e?.lng??this.numberOrUndefined(this.lngInput.value);if(t===void 0||n===void 0)return;const i=300;this.referenceStatus.textContent=this.messages.referenceStreetSearching,this.referenceStreetSearchButton.disabled=!0;try{this.streetPictures=await this.streetPictures$.nearby(t,n,i)}catch{this.streetPictures=[],this.referenceStatus.textContent=this.messages.referenceStreetFailed,this.referenceStreetSearchButton.disabled=!1;return}this.referenceStreetSearchButton.disabled=!1,this.referenceStreetSelect.innerHTML="";for(const[a,o]of this.streetPictures.entries()){const l=document.createElement("option");l.value=String(a),l.textContent=this.streetPictureLabel(o,this.messages.referenceStreetItem),this.referenceStreetSelect.appendChild(l)}const s=this.streetPictures.length>0;this.referenceStreetSelect.hidden=!s,this.referenceStreetAddButton.hidden=!s,this.referenceStatus.textContent=s?"":this.messages.referenceStreetNone.replace("{m}",String(i))}streetPictureLabel(e,t){return t.replace("{distance}",String(Math.round(e.distanceM))).replace("{bearing}",String(Math.round(e.bearingDeg))).replace("{date}",e.takenAt.slice(0,10)).replace("{panorama}",e.panorama?this.messages.referenceStreetPanorama:"")}addStreetPicture(){const e=this.streetPictures[Number(this.referenceStreetSelect.value)];e&&this.addReference(e.src,this.streetPictureLabel(e,this.messages.referenceStreetTitle),{kind:e.panorama?"panorama":"photo",credit:e.credit,creditUrl:e.creditUrl,registration:{headingDeg:e.azimuthDeg??0,pitchDeg:0,fovDeg:Pl}})}deleteReference(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting;e.references=e.references.filter(t=>t.id!==this.currentReferenceId),this.currentReferenceId=e.references[0]?.id,this.refreshReferenceList(),this.ufoElement.refresh()}buildSoundKindOptions(){for(const e of a1){const t=document.createElement("option");t.value=e,t.textContent=this.soundKindLabel(e,this.messages),this.soundKindOptions.set(e,t),this.soundKindSelect.appendChild(t)}}soundKindLabel(e,t){switch(e){case"hum":return t.soundHum;case"whistle":return t.soundWhistle;case"rumble":return t.soundRumble;case"crackle":return t.soundCrackle;default:return t.soundNone}}applySoundAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;const e=this.readSound();this.ufoElement.sighting.soundTrack.addKeyframe(this.ufoElement.currentTime,e),this.updateSoundPitchReadout(e.pitchHz),this.updateSoundFieldsDisabledState(e),this.ufoElement.refresh(),this.previewSound(e)}previewSound(e){clearTimeout(this.soundPreviewTimer),this.ufoElement.previewSound(e),this.soundPreviewTimer=setTimeout(()=>this.ufoElement.stopSoundPreview(),LA)}readSound(){return{kind:this.soundKindSelect.value,volume:Number(this.soundVolumeInput.value),pitchHz:Number(this.soundPitchInput.value),src:this.soundSrcInput.value.trim()||void 0}}syncSoundFromTimeline(){if(this.ufoElement.playbackState==="playing")return;const e=Pu(this.ufoElement.sighting,this.ufoElement.currentTime),t=this.shadow.activeElement;t!==this.soundKindSelect&&(this.soundKindSelect.value=e.kind),t!==this.soundVolumeInput&&(this.soundVolumeInput.value=String(e.volume)),t!==this.soundPitchInput&&(this.soundPitchInput.value=String(e.pitchHz)),t!==this.soundSrcInput&&(this.soundSrcInput.value=e.src??""),this.updateSoundPitchReadout(e.pitchHz),this.updateSoundFieldsDisabledState(e)}updateSoundPitchReadout(e){this.soundPitchValue.textContent=`${Math.round(e)} Hz`}updateSoundFieldsDisabledState(e){const t=e.kind==="none"&&!e.src;this.soundVolumeInput.disabled=t,this.soundSrcInput.disabled=t,this.soundPitchInput.disabled=t||e.src!==void 0}set weatherProvider(e){this.weatherInference=new Yh(e),this.scheduleWeatherLookup()}onWeatherInferredToggled(){this.weatherFromRecords=this.weatherInferredInput.checked,this.weatherFromRecords?this.scheduleWeatherLookup():(this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())}scheduleWeatherLookup(){this.weatherFromRecords&&(clearTimeout(this.weatherLookupTimer),this.weatherLookupTimer=setTimeout(()=>void this.inferWeather(),kA))}cancelWeatherLookup(){clearTimeout(this.weatherLookupTimer),this.weatherLookupToken++,this.weatherLookupPending=!1}async inferWeather(){if(!this.weatherFromRecords)return;const e=++this.weatherLookupToken;this.weatherLookupPending=!0,this.syncWeatherSourceState();const t=await this.weatherInference.infer(this.ufoElement.sighting);e!==this.weatherLookupToken||!this.weatherFromRecords||(this.weatherLookupPending=!1,this.weatherLookupResult=t,t.status==="inferred"?(this.weatherInference.applyTo(this.ufoElement.sighting,t),this.weatherTrackSpan=this.ufoElement.seekableDuration,this.ufoElement.refresh(),this.syncWeatherFromTimeline()):this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())}ensureWeatherTrackSpan(){if(!this.weatherFromRecords||this.ufoElement.sighting.weatherSource===void 0)return;const e=this.ufoElement.seekableDuration;this.weatherTrackSpan===void 0||e===this.weatherTrackSpan||(this.weatherTrackSpan=e,this.scheduleWeatherLookup())}syncWeatherSourceState(){const e=this.ufoElement.sighting.weatherSource,t=this.weatherFromRecords;for(const o of this.weatherFields)o.disabled=t&&e!==void 0&&o!==this.iceCrystalAlignmentInput||this.ufoElement.playbackState==="playing",this.ufoElement.playbackState==="playing"?o.title=this.messages.weatherWhilePlaying:o.title===this.messages.weatherWhilePlaying&&(o.title="");const n=this.weatherInference.canInfer(this.ufoElement.sighting);this.weatherInferredInput.disabled=!n,this.weatherInferredInput.checked=n&&this.weatherFromRecords;const i=n?this.messages.weatherInferredTitle:this.messages.weatherNeedsDateAndPlace;this.weatherInferredInput.title=i,this.labelWeatherInferred.title=i;const s=t&&e!==void 0;if(this.weatherSourceLink.hidden=!s,s){this.weatherSourceRow.hidden=!1,this.weatherSourceText.textContent="",this.weatherSourceLink.href=e.url,this.weatherSourceLink.textContent=this.observationInstantLabel();return}const a=t?this.weatherStatusMessage():"";this.weatherSourceText.textContent=a===""?"":`${a} `,this.weatherSourceRow.hidden=a===""}weatherStatusMessage(){if(this.weatherLookupPending)return this.messages.weatherLookingUp;switch(this.weatherLookupResult?.status){case"unavailable":return this.messages.weatherNoRecord;case"failed":return this.messages.weatherLookupFailed;default:return""}}observationInstantLabel(){const e=this.ufoElement.sighting.event,t=e.time&&Ds(e.time,e.place?.[0]?.lng??0,e.utcOffsetHours);return t?`, ${t.toISOString().slice(0,16).replace("T"," ")} UTC`:""}syncWeatherOwnership(){const e=this.ufoElement.sighting;this.cancelWeatherLookup(),this.weatherLookupResult=void 0,this.weatherFromRecords=e.weatherSource!==void 0||e.weatherTrack.allKeyframes.length===0,this.syncWeatherSourceState(),this.weatherFromRecords&&e.weatherSource===void 0&&this.scheduleWeatherLookup()}syncDurationField(){if(this.shadow.activeElement!==this.durationInput){const e=ua(this.ufoElement.sighting.event);this.durationInput.value=e!==void 0?String(e/1e3):""}this.updateDurationValidity()}updateDurationValidity(){const e=this.durationInput.value==="";this.durationInput.classList.toggle("missing-required",e),this.markUnansweredQuestions(),this.durationInput.setAttribute("aria-invalid",String(e));const t=u1(this.ufoElement.sighting.event);this.durationInput.title=t==="imprecise"?this.messages.durationImprecise:""}syncPlaybackControls(){this.ensureWeatherTrackSpan();const e=this.ufoElement.playbackState==="playing",t=this.ufoElement.seekableDuration>0;this.playPauseButton.textContent=e?"⏸":"▶",this.playPauseButton.disabled=!t;const n=t?e?this.messages.pause:this.messages.play:this.messages.noDuration;this.playPauseButton.title=n,this.playPauseButton.setAttribute("aria-label",n),this.loopButton.setAttribute("aria-pressed",String(this.ufoElement.autoReplayEnabled)),this.seekInput.max=String(this.ufoElement.seekableDuration),this.shadow.activeElement!==this.seekInput&&(this.seekInput.value=String(this.ufoElement.currentTime)),this.timeStartLabel.textContent=this.ufoElement.positionLabel,this.timeEndLabel.textContent=this.ufoElement.durationLabel,this.syncTimeDisplaySwitch()}switchTimeDisplay(){this.ufoElement.toggleTimeDisplay(),this.timeStartLabel.textContent=this.ufoElement.positionLabel,this.timeEndLabel.textContent=this.ufoElement.durationLabel,this.syncTimeDisplaySwitch()}syncTimeDisplaySwitch(){const e=this.ufoElement.canSwitchTimeDisplay,t=this.ufoElement.showingClockTime?this.messages.switchToElapsed:this.messages.switchToClockTime;for(const[n,i]of[[this.timeStartLabel,this.messages.currentPosition],[this.timeEndLabel,this.messages.duration]])n.title=e?`${i} — ${t}`:i,n.classList.toggle("switchable",e),e?(n.setAttribute("role","button"),n.setAttribute("tabindex","0")):(n.removeAttribute("role"),n.removeAttribute("tabindex"))}static TIME_QUALIFIERS=[{value:"",key:"timeQualifierExact"},{value:"~",key:"timeQualifierApproximate"},{value:"?",key:"timeQualifierUncertain"},{value:"%",key:"timeQualifierBoth"}];refreshTimeQualifierOptions(){for(const e of[this.obsTimeQualifier,this.obsEndTimeQualifier]){const t=e.value;e.replaceChildren(...Tt.TIME_QUALIFIERS.map(n=>{const i=document.createElement("option");return i.value=n.value,i.textContent=this.messages[n.key],i})),e.value=t}}qualifierOf(e){const t=e.trim().slice(-1);return"?~%".includes(t)?t:""}isPickable(e){return e?e.year!==void 0&&e.month!==void 0&&e.day!==void 0&&e.hour!==void 0&&e.minute!==void 0&&(e.second===void 0||e.second===0):!1}pickerValueOf(e){if(!this.isPickable(e))return"";const t=(n,i=2)=>String(n).padStart(i,"0");return`${t(e.year,4)}-${t(e.month)}-${t(e.day)}T${t(e.hour)}:${t(e.minute)}`}writeFromPicker(e,t,n,i){e.value===""&&e.validity.badInput||(n.value=e.value===""?"":`${e.value}${t.value}`,i())}chooseTimeInputMode(){const e=this.ufoElement.sighting.event,t=n=>n===void 0||this.isPickable(n);this.setEdtfMode(!(t(e.time)&&t(e.endTime)))}setEdtfMode(e){this.edtfMode=e,this.edtfModeButton.setAttribute("aria-pressed",String(e));for(const[t,n,i]of[[this.obsTimeInput,this.obsTimeNativeInput,this.obsTimeQualifier],[this.obsEndTimeInput,this.obsEndTimeNativeInput,this.obsEndTimeQualifier]])t.hidden=!e,n.hidden=e,i.hidden=e}syncObservationTimeFields(){const e=this.ufoElement.sighting.event.time;this.obsTimeInput.value=e?Kl(e):"",this.obsTimeNativeInput.value=this.pickerValueOf(e),this.obsTimeQualifier.value=this.qualifierOf(this.obsTimeInput.value),this.obsTimeInput.setCustomValidity(""),this.obsTimeInput.classList.remove("invalid")}syncObservationEndTimeFields(){const e=this.ufoElement.sighting.event.endTime;this.obsEndTimeInput.value=e?Kl(e):"",this.obsEndTimeNativeInput.value=this.pickerValueOf(e),this.obsEndTimeQualifier.value=this.qualifierOf(this.obsEndTimeInput.value),this.obsEndTimeInput.setCustomValidity(""),this.obsEndTimeInput.classList.remove("invalid")}syncUtcOffsetField(){const e=this.ufoElement.sighting.event.utcOffsetHours;this.utcOffsetInput.value=e===void 0?"":String(e),this.updateUtcOffsetValidity()}updateUtcOffsetValidity(){const e=this.ufoElement.sighting.event.utcOffsetHours,t=this.ufoElement.sighting.event.place?.[0]?.lng,n=t===void 0?void 0:Math.round(t/15),i=e!==void 0&&n!==void 0&&Math.abs(e-n)>FA;this.utcOffsetInput.classList.toggle("invalid",i),this.utcOffsetInput.title=i?this.messages.utcOffsetImplausible.replace("{solar}",n>=0?`+${n}`:String(n)):""}scheduleGroundElevation(){const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);e===void 0||t===void 0||this.groundElevationFor&&this.isSamePlace(this.groundElevationFor,e,t)||(clearTimeout(this.groundElevationTimer),this.groundElevationTimer=setTimeout(()=>void this.applyGroundElevation(e,t),NA))}isSamePlace(e,t,n){return Math.abs(e.lat-t)<Xr&&Math.abs(e.lng-n)<Xr}async applyGroundElevation(e,t){const n=++this.groundElevationToken,i=Wr(jh,this.chosenSourceId.get("elevation")),s=await new pf(i.create()).at(e,t);if(n!==this.groundElevationToken||s===void 0)return;this.groundElevationFor={lat:e,lng:t};const a=Math.max(0,(this.numberOrUndefined(this.elevationInput.value)??0)-(this.groundElevationM??0));this.groundElevationM=Math.round(s),this.syncElevationField(a),this.updateObserver()}syncElevationField(e){const t=this.groundElevationM;this.elevationInput.value=String(Math.round((t??0)+e)),this.elevationInput.min=t===void 0?"":String(t),this.elevationInput.title=t===void 0?"":this.messages.altitudeAboveSeaLevel,this.groundElevationOutput.textContent=t===void 0?"":this.messages.groundAt.replace("{m}",String(t))}syncGroundElevationField(){this.groundElevationToken++,clearTimeout(this.groundElevationTimer),this.groundElevationM=void 0,this.groundElevationFor=void 0,this.syncElevationField(tt(this.ufoElement.sighting,0)?.elevationM??0),this.scheduleGroundElevation()}syncPlaceNameField(){const e=this.ufoElement.sighting.event.place?.[0],t=e?.name??"";this.placeNameInput.value=t,this.placeNameInput.title=t,this.namedCoordinates=e&&t?{lat:e.lat,lng:e.lng}:void 0,this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent=""}syncWitnessMetadataFields(){const e=this.ufoElement.sighting;this.witnessIdInput.value=e.witness?.id??"",this.witnessDirNameInput.value=e.witness?.dirName??"",this.witnessTitleInput.value=e.witness?.title??"",this.witnessLastNameInput.value=e.witness?.lastName??"",this.witnessFirstNamesInput.value=e.witness?.firstNames?.join(", ")??"",this.caseIdInput.value=e.caseId??"",this.witnessAgeInput.value=e.testimony?.witnessAgeYears?.toString()??"",this.witnessOccupationInput.value=this.said.read(e.testimony?.witnessOccupation)??"",this.testimonySourceSelect.value=e.testimony?.source??"",this.testimonyFollowedUpSelect.value=e.testimony?.followedUp===void 0?"":e.testimony.followedUp?"yes":"no",this.descriptionInput.value=this.said.read(e.event.description)??"",this.showTags(),this.instrumentSelect.value=e.instrument.id}syncWeatherFromTimeline(){if(this.cloudEditor?.sync(),this.ufoElement.playbackState==="playing")return;const e=Ut(this.ufoElement.sighting,this.ufoElement.currentTime),t=this.shadow.activeElement;t!==this.cloudCoverInput&&(this.cloudCoverInput.value=String(e.cloudCover)),t!==this.highCloudCoverInput&&(this.highCloudCoverInput.value=String(e.highCloudCover??0)),t!==this.iceCrystalAlignmentInput&&(this.iceCrystalAlignmentInput.value=String(e.iceCrystalAlignment??.65)),t!==this.cloudDarknessInput&&(this.cloudDarknessInput.value=String(e.cloudDarkness)),t!==this.cloudBaseInput&&(this.cloudBaseInput.value=e.cloudBaseM===void 0?"":String(e.cloudBaseM)),t!==this.precipitationTypeSelect&&(this.precipitationTypeSelect.value=e.precipitationType),t!==this.precipitationIntensityInput&&(this.precipitationIntensityInput.value=String(e.precipitationIntensity)),t!==this.windDirectionInput&&(this.windDirectionInput.value=String(Math.round(e.windDirectionDeg))),t!==this.windSpeedInput&&(this.windSpeedInput.value=String(Math.round(e.windSpeed*2)/2)),t!==this.stormInput&&(this.stormInput.checked=e.storm)}syncObserverFromTimeline(){if(this.ufoElement.playbackState==="playing")return;this.syncStreetSearchAvailability();const e=this.ufoElement.sighting,t=e.witnessTrack.getInterpolatedPoseAt(this.ufoElement.currentTime),n=e.event.place?.[0],i=this.shadow.activeElement;i!==this.latInput&&(this.latInput.value=t?.lat!==void 0?String(t.lat):n?String(n.lat):""),i!==this.lngInput&&(this.lngInput.value=t?.lng!==void 0?String(t.lng):n?String(n.lng):""),i!==this.headingInput&&(this.headingInput.value=t?.headingDeg!==void 0?String(this.rounded(t.headingDeg)):""),i!==this.pitchInput&&(this.pitchInput.value=String(this.rounded(t?.pitchDeg??0)),this.rollInput.value=String(this.rounded(t?.rollDeg??0))),i!==this.elevationInput&&this.syncElevationField(t?.elevationM??0)}get appearance(){return{...this.currentAppearance}}set appearance(e){this.setAppearance(e)}setAppearance(e){const t="presetId"in e;this.currentAppearance={...this.currentAppearance,...e},this.updatePresetButtons(),!(this.isRecording||this.ufoElement.playbackState==="playing")&&this.applyAppearanceAtPlayhead(void 0,t)}applyAppearanceAtPlayhead(e,t=!0){const n=this.ufoElement.sighting.timeline,i=this.ufoElement.currentTime,s=n.getInterpolatedShapeAt(i,this.currentSourceId),a=this.buildAppearanceShape(e??s?.bounds??this.defaultBounds(),s,t);this.commitShapes(i,[{sourceId:this.currentSourceId,shape:a}]),this.ufoElement.refresh()}buildAppearanceShape(e,t,n=!0){if(t&&!n)return{...t,color:this.currentAppearance.color,transparency:this.currentAppearance.transparency,haloScale:this.currentAppearance.haloScale,blur:this.currentAppearance.blur,brightness:this.currentAppearance.brightness};const i=_f(e,this.currentAppearance);return t?{...i,angle:t.angle,title:t.title,selected:t.selected}:i}toggleSkyDetails(){const e=this.skyDetailsButton.getAttribute("aria-expanded")!=="true";this.skyDetailsButton.setAttribute("aria-expanded",String(e)),this.skyDetailsButton.textContent=e?"▴":"▾",this.skyDetailsButton.title=e?this.messages.skyDetailsHide:this.messages.skyDetails,this.skyDetailsButton.setAttribute("aria-label",this.skyDetailsButton.title);for(const t of this.clampedLines)t.classList.toggle("clamped",!e)}isGroupOpen(e){return e.getAttribute("aria-expanded")==="true"}toggleGroup(e,t){this.cloudEditor?.stopManipulation();for(const[n,i]of this.groupTabs.entries()){const s=i===e&&t;i.setAttribute("aria-expanded",String(s)),this.groupPanels[n].hidden=!s}this.syncCanvasMode()}isGroupIdOpen(e){const t=this.groupTabs.find(n=>n.getAttribute("aria-controls")===e);return t!==void 0&&this.isGroupOpen(t)}canvasMode(){return this.isGroupIdOpen("group-reference")&&this.currentReferenceId!==void 0?"picture":this.isGroupIdOpen("group-shape")?"shape":"scene"}syncCanvasMode(){const e=this.canvasMode(),t=e==="picture",n=this.lastCanvasMode==="picture",i=e!==this.lastCanvasMode;this.lastCanvasMode=e,this.ufoElement.selectionShown=e==="shape",this.ufoElement.overlayPainter=t?this.paintPictureOverlay:void 0,i&&this.ufoElement.refresh(),t!==n&&this.setCanvasCursor(t?"pan":this.hoverCursor),!t&&(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark();const s=this.currentReference();s&&this.syncReferenceStatus(s),this.syncStreetSearchAvailability()}openSubgroup(e){this.cloudEditor?.stopManipulation();const t=e.parentElement;for(const n of this.subgroupTabs){if(n.parentElement!==t)continue;const i=n===e;n.setAttribute("aria-expanded",String(i)),this.shadow.getElementById(n.getAttribute("aria-controls")).hidden=!i}}revealSubgroupOf(e){const t=e.closest(".subgroup-panel"),n=t&&this.subgroupTabs.find(i=>i.getAttribute("aria-controls")===t.id);n&&this.openSubgroup(n)}static SUMMARY_GROUPS=["observation","witness","location","decor","temporal","weather","sound"];static PANEL_ORDER=["observation","witness","location","decor","temporal","weather","sound","shape"];refreshParamSummary(){const t=this.paramSummaryBuilder.entriesFor(this.ufoElement.sighting,this.ufoElement.currentTime,{decorId:this.currentDecorId,decorPicker:!0,groundElevationM:this.groundElevationM??0}).map(i=>({...i,panel:Tt.SUMMARY_GROUPS.indexOf(i.group)})),n=t.map(i=>`${i.field}=${i.label}=${i.value}${i.unit}${i.fromSource?"*":""}`).join("|");n!==this.paramSummarySignature&&(this.paramSummarySignature=n,this.paramChips=t,this.renderParamSummary(),this.runAssessments())}paramChips=[];renderParamSummary(){const e=Tt.NESTED_GROUPS,t=[];let n;for(const i of[...this.paramChips,...this.assessmentChips]){if(n&&n.group!==i.group&&(n=void 0),e.includes(i.group)&&!n){const a=document.createElement("span");a.className="param-nest",a.dataset.group=i.group;const o=document.createElement("span");o.className="param-nest-label",o.textContent=i.group==="assessment"?this.messages.assessmentGroup:Tt.tabLabel(this.groupTabs[Tt.SUMMARY_GROUPS.indexOf(i.group)]),a.append(o),n={group:i.group,element:a},t.push(a)}const s=this.paramChip(i);n?n.element.append(s):t.push(s)}this.paramSummary.replaceChildren(...t)}static NESTED_GROUPS=["witness","decor","assessment"];static QUESTION_FIELDS={when:{panel:"temporal",fields:["obs-time","obs-time-native"]},where:{panel:"location",fields:["lat","lng"]},facing:{panel:"location",fields:["heading"]},"apparent-size":{panel:"shape",fields:[]},"sky-position":{panel:"shape",fields:[]},"how-long":{panel:"temporal",fields:["durationSeconds","obs-end-time","obs-end-time-native"]},appearance:{panel:"shape",fields:["shapeTitle","color"]},movement:{panel:"shape",fields:[]},sound:{panel:"sound",fields:["soundKind"]},conditions:{panel:"weather",fields:["cloudCover"]}};assessmentChips=[];assessmentToken=0;async runAssessments(){const e=++this.assessmentToken,t=await new E1(this.messages).read(this.ufoElement.sighting);e===this.assessmentToken&&(this.assessmentChips=t.entries.map(n=>({...n,panel:Tt.PANEL_ORDER.indexOf(n.about??"")})),this.markUnansweredQuestions(t.unanswered),this.renderParamSummary())}static tabLabel(e){return(e.querySelector("span:not(.tab-badge)")??e).textContent.trim()}static badgeOn(e){const t=e.querySelector(".tab-badge");if(t)return t;const n=document.createElement("span");return n.className="tab-badge",n.hidden=!0,e.append(n),n}unansweredQuestions=new Set;markUnansweredQuestions(e=this.unansweredQuestions){this.unansweredQuestions=e;const t=new Set;for(const s of e){const a=Tt.QUESTION_FIELDS[s];if(a&&!a.fields.some(o=>this.shadow.getElementById(o)?.classList.contains("missing-required")))for(const o of a.fields){const l=this.shadow.getElementById(o);l&&!l.hidden&&l.value===""&&t.add(o)}}for(const[s,a]of Object.entries(Tt.QUESTION_FIELDS))for(const o of Tt.QUESTION_FIELDS[s].fields){const l=this.shadow.getElementById(o);if(!l)continue;const c=t.has(o)&&!l.classList.contains("missing-required");l.classList.toggle("wanted",c),(c||l.title===this.messages.questionUnanswered)&&(l.title=c?this.messages.questionUnanswered:"")}const n=new Map;let i;for(const[s,a]of Object.entries(Tt.QUESTION_FIELDS))for(const o of a.fields){const l=this.shadow.getElementById(o);if(!l)continue;const c=l.classList.contains("missing-required");!c&&!l.classList.contains("wanted")||(c&&(i=a.panel),n.set(a.panel,(n.get(a.panel)??0)+1))}for(const[s,a]of this.groupTabs.entries()){const o=Tt.PANEL_ORDER[s],l=n.get(o)??0,c=o===i,h=Tt.badgeOn(a);h.hidden=l===0,h.textContent=String(l),h.classList.toggle("optional",!c),a.title=l===0?"":c?this.messages.durationRequired:this.messages.questionsUnanswered.replace("{count}",String(l))}}paramChip(e){const t=document.createElement("button");t.type="button",t.className=e.fromSource?"param-chip from-source":"param-chip",t.dataset.panel=String(e.panel),t.dataset.field=e.field;const n=document.createElement("span");if(n.className="param-chip-label",n.textContent=`${e.label} `,t.append(n),e.color!==void 0){const s=document.createElement("span");s.className="param-chip-swatch",s.style.background=e.color,t.append(s)}const i=document.createElement("span");return i.className="param-chip-value",i.textContent=e.unit===""?e.value:`${e.value} ${e.unit}`,t.append(i),t}onParamSummaryClick(e){const t=e.target.closest(".param-chip");if(t==null)return;const n=Number(t.dataset.panel);if(n<0)return;const i=this.groupPanels[n];this.toggleGroup(this.groupTabs[n],!0);const s=t.dataset.field;if(s.startsWith("decor:")){this.currentDecorId=s.slice(6),this.refreshDecorList(),this.decorSelect.focus();return}const a=this.shadow.getElementById(s);a===null||!i.contains(a)||(this.revealSubgroupOf(a),a.focus(),a instanceof HTMLInputElement&&a.type!=="checkbox"&&a.type!=="color"&&a.type!=="range"&&a.select(),a.scrollIntoView?.({block:"center"}))}onSelectionOrTimeChanged(){this.syncAppearanceFromTimeline(),this.syncObserverFromTimeline(),this.syncWeatherFromTimeline(),this.syncWeatherSourceState(),this.syncSoundFromTimeline(),this.syncDecorLitFromTimeline(),this.syncDecorPlacementFromTimeline(),this.syncIndoorLookReset(),this.updateAppearanceFieldsDisabledState(),this.updateShapeTitleValidity(),this.refreshRealSize(),this.refreshBlurDistanceBound(),this.refreshSkyCandidates(),this.refreshInstrumentOptions(),this.syncOpticsFromInstrument(),this.ufoElement.selectedSourceIds=this.selectedSourceIds;const e=this.ufoElement.sighting.timeline.sourceIds,t=e.filter(n=>this.selectedSourceIds.has(n)).length;this.deleteShapeButton.disabled=this.isRecording||this.ufoElement.playbackState==="playing"||t===0||e.length-t<1,this.refreshParamSummary()}updateAppearanceFieldsDisabledState(){const e=this.selectedSourceIds.size>1,t=e?this.messages.multipleShapesSelected:"";for(const n of[this.shapeTitleInput,this.colorInput,this.transparencyInput,this.haloScaleInput,this.blurInput,this.brightnessInput,this.apparentWidthInput,this.realWidthInput,this.objectDistanceInput,this.sizeLockSelect,this.clearDistanceHypothesisButton,this.sourceSelect,...Object.values(this.presetButtons)])n.disabled=e,n.title=t}syncAppearanceFromTimeline(){if(this.ufoElement.playbackState==="playing"||this.selectedSourceIds.size>1)return;const e=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId);e&&(this.currentAppearance={presetId:GA(e),color:e.color,transparency:e.transparency,haloScale:e.haloScale,blur:e.blur??0,brightness:e.brightness??0},this.updatePresetButtons(),this.colorInput.value=this.currentAppearance.color,this.transparencyInput.value=String(this.currentAppearance.transparency),this.haloScaleInput.value=String(this.currentAppearance.haloScale),this.blurInput.value=String(this.currentAppearance.blur),this.brightnessInput.value=String(this.currentAppearance.brightness),this.shadow.activeElement!==this.shapeTitleInput&&(this.shapeTitleInput.value=this.said.read(e.title)??""),this.refreshApparentSize())}updateShapeTitle(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime,n=e.getInterpolatedShapeAt(t,this.currentSourceId);n&&(this.commitShapes(t,[{sourceId:this.currentSourceId,shape:{...n,title:this.said.write(n.title,this.shapeTitleInput.value,this.writingLanguage)}}]),this.ufoElement.refresh(),this.refreshSourceList(),this.updateShapeTitleValidity())}sizeLock="none";onApparentWidthInput(){const e=this.numberOrUndefined(this.apparentWidthInput.value);if(!(e===void 0||e<=0||this.selectedSourceIds.size!==1)){if(this.sizeLock==="real"){const t=this.numberOrUndefined(this.realWidthInput.value);t!==void 0&&t>0&&this.sceneElement.setDistanceHypothesis(this.currentSourceId,et.distanceMAt(t,e))}this.applyApparentWidth(e)}}onRealWidthInput(){const e=this.numberOrUndefined(this.realWidthInput.value);if(e===void 0||e<=0||this.selectedSourceIds.size!==1)return;if(this.sizeLock==="apparent"){const n=this.currentApparentWidthDeg();n!==void 0&&n>0&&(this.sceneElement.setDistanceHypothesis(this.currentSourceId,et.distanceMAt(e,n)),this.refreshDepth());return}const t=this.currentDistanceM();t!==void 0&&t>0&&this.applyApparentWidth(et.angularWidthDeg({sizeM:e,distanceM:t}))}onDistanceInput(){const e=this.numberOrUndefined(this.objectDistanceInput.value);e===void 0||e<=0||this.applyDistance(e)}applyDistance(e){if(this.selectedSourceIds.size===1){if(this.sizeLock!=="apparent"){const t=this.numberOrUndefined(this.realWidthInput.value);t!==void 0&&t>0&&this.applyApparentWidth(et.angularWidthDeg({sizeM:t,distanceM:e}))}this.sceneElement.setDistanceHypothesis(this.currentSourceId,e),this.refreshDepth()}}applySizeLock(){this.sizeLock=this.sizeLockSelect.value,this.apparentWidthInput.readOnly=this.sizeLock==="apparent",this.realWidthInput.readOnly=this.sizeLock==="real",this.objectDistanceInput.readOnly=this.sizeLock==="distance"}currentApparentWidthDeg(){const e=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId);if(e)return e.angular?.widthDeg??this.currentProjection().pxToDeg(e.bounds.width)}currentDistanceM(){return this.sceneElement.depthOf(this.currentSourceId)?.distanceM}applyApparentWidth(e){const t=this.ufoElement.sighting.timeline,n=this.ufoElement.currentTime,i=t.getInterpolatedShapeAt(n,this.currentSourceId);if(!i)return;const s=this.currentProjection(),a=s.degToPx(e),o=i.bounds.height*(i.bounds.width===0?1:a/i.bounds.width),l={x:i.bounds.x+(i.bounds.width-a)/2,y:i.bounds.y+(i.bounds.height-o)/2,width:a,height:o},c=s.ofBounds(l),h=i.kind==="oval"?{...i,bounds:l,angular:c}:{...i,bounds:l,angular:c,points:this.scalePoints(i,l)};this.commitShapes(n,[{sourceId:this.currentSourceId,shape:h}]),this.ufoElement.refresh(),this.refreshApparentSize()}scalePoints(e,t){const n=e.bounds.width===0?1:t.width/e.bounds.width,i=e.bounds.height===0?1:t.height/e.bounds.height;return e.points.map(s=>({x:s.x*n,y:s.y*i}))}refreshInstrumentOptions(){const e=this.ufoElement.sighting,t=e.event.time?.year,n=rt.availableAt(t),i=e.instrument,s=n.includes(i)?n:[...n,i],a=this.instrumentSelect.value||i.id;this.instrumentSelect.replaceChildren();for(const o of s){const l=document.createElement("option");l.value=o.id;const c=o.name[this.showerLanguage()];l.textContent=n.includes(o)?c:this.messages.instrumentOutOfPeriod.replace("{name}",c),this.instrumentSelect.appendChild(l)}this.instrumentSelect.value=s.some(o=>o.id===a)?a:i.id}static exposureText(e){return e>=1?String(Math.round(e*100)/100):`1/${Math.round(1/e)}`}statedExposureSeconds(e){const t=Tt.exposureSeconds(this.exposureInput.value),n=e.exposureRangeSeconds;if(!n)return e.exposureSeconds??t;if(t!==void 0)return Math.min(n.max,Math.max(n.min,t))}static exposureSeconds(e){const t=e.trim();if(!t)return;const n=/^(\d*\.?\d+)\s*\/\s*(\d*\.?\d+)$/.exec(t);if(n){const s=Number(n[1]),a=Number(n[2]);return a>0?s/a:void 0}const i=Number(t);return Number.isFinite(i)&&i>0?i:void 0}syncOpticsFromInstrument(){const e=this.ufoElement.sighting,t=e.instrument,n=tt(e,this.ufoElement.currentTime),i=t.frame,s=n?.fovDeg??rt.fieldOfViewDeg(t),a=i?rt.focalLengthMmFor(t,s):s;this.focalLengthInput!==this.shadow.activeElement&&(this.focalLengthInput.value=a===void 0?"":String(Math.round(a*10)/10)),this.unitFocalLength.textContent=i?this.messages.unitMillimetres:this.messages.unitDegrees,this.labelFocalLength.textContent=i?this.messages.focalLength:this.messages.fieldOfView,this.focalLengthInput.disabled=i!==void 0&&i.focalRangeMm===void 0,this.focalLengthInput.min=String(i?.focalRangeMm?.minMm??1),this.focalLengthInput.max=String(i?.focalRangeMm?.maxMm??2e3);const o=n?.fNumber??t.fNumber;this.fNumberInput!==this.shadow.activeElement&&(this.fNumberInput.value=o===void 0?"":String(o)),this.setRowVisible(this.fNumberInput,t.fNumber!==void 0),this.fNumberInput.disabled=t.fNumberRange===void 0,this.fNumberInput.min=String(t.fNumberRange?.min??.7),this.fNumberInput.max=String(t.fNumberRange?.max??64);const l=e.exposure;this.exposureInput!==this.shadow.activeElement&&(this.exposureInput.value=l===void 0?"":Tt.exposureText(l)),this.setRowVisible(this.exposureInput,t.exposureSeconds!==void 0),this.exposureInput.disabled=t.exposureRangeSeconds===void 0,this.focusDistanceInput!==this.shadow.activeElement&&(this.focusDistanceInput.value=n?.focusDistanceM===void 0?"":String(n.focusDistanceM)),this.setRowVisible(this.focusDistanceInput,i!==void 0&&t.fNumber!==void 0)}retuneFieldOfView(e){const t=this.ufoElement.sighting,n=rt.fieldOfViewDeg(e),i=rt.fieldOfViewDeg(t.instrument);for(const s of[...t.witnessTrack.allKeyframes])Math.abs(s.pose.fovDeg-n)>UA||t.witnessTrack.addKeyframe(s.t,{...s.pose,fovDeg:i})}retuneExposure(e){const t=this.ufoElement.sighting,n=t.exposureSeconds,i=t.instrument.exposureRangeSeconds;if(n===void 0||n===e.exposureSeconds||!i){t.exposureSeconds=void 0;return}t.exposureSeconds=Math.min(i.max,Math.max(i.min,n))}currentFovDeg(){const e=this.ufoElement.sighting;return tt(e,this.ufoElement.currentTime)?.fovDeg??rt.fieldOfViewDeg(e.instrument)}currentProjection(){return oi.of(this.ufoElement.sighting.instrument,this.ufoElement.canvasElement.height,this.currentFovDeg())}refreshApparentSize(){const e=this.selectedSourceIds.size===1?this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId):void 0;if(!e){this.apparentSizeOutput.textContent="",this.hasFocus(this.apparentWidthInput)||(this.apparentWidthInput.value=""),this.refreshRealSize();return}const t=e.angular?.widthDeg??this.currentProjection().pxToDeg(e.bounds.width),n=et.inMoons(t);this.hasFocus(this.apparentWidthInput)||(this.apparentWidthInput.value=this.plain(t,t<1?2:1)),this.apparentSizeOutput.textContent=this.messages.apparentSize.replace("{moons}",n.toLocaleString(void 0,{maximumFractionDigits:n<10?1:0})),this.refreshRealSize()}hasFocus(e){return this.typingIn===e}typingIn;typing(e,t){this.typingIn=e;try{t()}finally{this.typingIn=void 0}}plain(e,t){return String(Number(e.toFixed(t)))}refreshBlurDistanceBound(){const e=this.currentAppearance.blur;if(e<=0||this.selectedSourceIds.size!==1){this.blurBoundOutput.textContent="";return}const t=this.ufoElement.sighting.instrument,n=t.frame;if(!n){this.blurBoundOutput.textContent=this.messages.blurBoundNoInstrument;return}const i=tt(this.ufoElement.sighting,this.ufoElement.currentTime),s=i?.focusDistanceM;if(s!==void 0){this.blurBoundOutput.textContent=this.messages.blurBoundNotAtInfinity.replace("{focus}",this.meters(s));return}const a=(i?rt.focalLengthMmFor(t,i.fovDeg):void 0)??n.focalLengthMm,o=i?.fNumber??t.fNumber;if(o===void 0||a<=0){this.blurBoundOutput.textContent="";return}const l=this.ufoElement.canvasElement.height;if(l<=0)return;const c=2*td*e/l*n.heightMm,h=a*a/(o*c)/1e3;this.blurBoundOutput.textContent=this.messages.blurBound.replace("{max}",this.meters(h))}refreshRealSize(){if(this.refreshDepth(),this.selectedSourceIds.size!==1){this.realSizeOutput.textContent="";return}const e=this.currentSourceId;if(this.sceneElement.sizeContradictory(e)){this.realSizeOutput.textContent=this.messages.realSizeContradiction;return}const{minM:t,maxM:n}=this.sceneElement.sizeRangeOf(e);if(t===void 0&&n===void 0){this.realSizeOutput.textContent=this.messages.realSizeUnknown;return}const i=this.numberOrUndefined(this.realWidthInput.value),s=i!==void 0&&(t!==void 0&&i<t||n!==void 0&&i>n)?this.messages.realSizeOutside:"";if(t!==void 0&&n!==void 0){const a=this.sceneElement.distanceRangeAt(e,this.ufoElement.currentTime),o=a.minM===void 0||a.maxM===void 0?"":this.messages.realDistanceHere.replace("{min}",this.meters(a.minM)).replace("{max}",this.meters(a.maxM));this.realSizeOutput.textContent=this.messages.realSizeBetween.replace("{min}",this.meters(t)).replace("{max}",this.meters(n))+o+s;return}this.realSizeOutput.textContent=(t!==void 0?this.messages.realSizeAtLeast.replace("{min}",this.meters(t)):this.messages.realSizeAtMost.replace("{max}",this.meters(n)))+s}decimal(e,t){return e.toLocaleString(void 0,{minimumFractionDigits:t,maximumFractionDigits:t})}clearDistanceHypothesis(){this.selectedSourceIds.size===1&&(this.sceneElement.setDistanceHypothesis(this.currentSourceId,void 0),this.refreshDepth())}refreshDepth(){const e=this.selectedSourceIds.size===1?this.sceneElement.depthOf(this.currentSourceId):void 0;if(!e){this.depthBasisOutput.textContent="",this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=""),this.hasFocus(this.realWidthInput)||(this.realWidthInput.value="");return}const t=this.meters(e.distanceM);this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=this.plain(e.distanceM,e.distanceM<10?1:0));const n=this.currentApparentWidthDeg();if(!this.hasFocus(this.realWidthInput)){const s=n===void 0||n<=0?void 0:et.sizeMAt(e.distanceM,n);this.realWidthInput.value=s===void 0?"":this.plain(s,s<1?2:s<10?1:0)}this.clearDistanceHypothesisButton.hidden=e.basis!=="hypothesis";const i={stated:this.messages.depthStated,hypothesis:this.messages.depthHypothesis,derived:this.messages.depthDerived,bounded:this.messages.depthBounded,conventional:this.messages.depthConventional}[e.basis];this.depthBasisOutput.textContent=i.replace("{m}",t)}commitShapes(e,t){const n=this.ufoElement.sighting,i=oi.of(n.instrument,et.CANVAS_HEIGHT_PX,ln.fovOf(n,e));n.timeline.addKeyframe(e,t.map(s=>{const a=ln.aimOf(n,e,s.shape.bounds),o=i.ofBounds(s.shape.bounds);return{...s,shape:a?{...s.shape,aim:a,angular:o}:{...s.shape,angular:o}}}))}meters(e){const t=e<1?2:e<10?1:0;return e.toLocaleString(void 0,{maximumFractionDigits:t})}updateShapeTitleValidity(){const e=this.selectedSourceIds.size===1&&this.shapeTitleInput.value==="";this.shapeTitleInput.classList.toggle("invalid",e),this.shapeTitleInput.setAttribute("aria-invalid",String(e))}shapeLabel(e){const t=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,e),n=this.said.read(t?.title);if(n)return n;const i=/^ufo-(\d+)$/.exec(e);return i?`${this.messages.shape} ${i[1]}`:e}addShape(){if(this.isRecording)return;const e=this.ufoElement.sighting.timeline,t=new Set([...e.sourceIds,this.currentSourceId]);let n=t.size+1;for(;t.has(`ufo-${n}`);)n++;this.currentSourceId=`ufo-${n}`,this.selectedSourceIds=new Set([this.currentSourceId]),this.applyAppearanceAtPlayhead(this.offsetDefaultBounds(e.sourceIds.length)),this.shapeTitleInput.value=this.shapeLabel(this.currentSourceId),this.updateShapeTitle()}deleteShape(){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const e=this.ufoElement.sighting.timeline,t=e.sourceIds.filter(i=>this.selectedSourceIds.has(i));if(t.length===0||e.sourceIds.length-t.length<1)return;const n=t.length===1?this.messages.confirmDeleteShape.replace("{name}",this.shapeLabel(t[0])):this.messages.confirmDeleteShapes.replace("{count}",String(t.length));this.askConfirm(n,()=>this.removeShapes(t))}removeShapes(e){const t=this.ufoElement.sighting.timeline;for(const n of e)t.removeSource(n);this.currentSourceId=t.sourceIds[0],this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.ufoElement.refresh()}askConfirm(e,t){this.answerConfirm(!1),this.confirmMessage.textContent=e,this.confirmOverlay.hidden=!1,this.confirmAcceptButton.focus(),this.confirmAnswer=t}answerConfirm(e){const t=this.confirmAnswer;this.confirmAnswer=void 0,this.confirmOverlay.hidden=!0,e&&t?.()}offsetDefaultBounds(e){const t=this.defaultBounds(),n=24;return{...t,x:t.x+e*n,y:t.y+e*n}}refreshSourceList(){const e=this.ufoElement.sighting.timeline,t=[...new Set([...e.sourceIds,this.currentSourceId])];this.sourceSelect.innerHTML="";for(const n of t){const i=document.createElement("option");i.value=n,i.textContent=this.shapeLabel(n),this.sourceSelect.appendChild(i)}this.sourceSelect.value=this.currentSourceId}decorLabel(e){const t=this.said.read(e.title);if(t)return t;const i=this.ufoElement.sighting.decor.filter(a=>a.kind===e.kind).indexOf(e)+1;return`${this.decorKindSelect.querySelector(`option[value="${e.kind}"]`)?.textContent??e.kind} ${i}`}addDecor(e=this.decorKindSelect.value){const t=this.ufoElement.sighting,i={id:`decor-${t.decor.length+1}`,kind:e,title:this.nextDecorLabel(e),eastM:8*t.decor.length,northM:15,headingDeg:0,lit:!1,...e==="aircraft"?this.defaultAircraft():{},...e==="building"?{floors:ta}:{},windows:jm(e)};t.decor=[...t.decor,i],this.currentDecorId=i.id,this.refreshDecorList(),this.ufoElement.refresh()}defaultAircraft(){const e=2*Jh,t=Math.round(e/zA*1e3);return{lights:Nc.byId("airliner")?.create(),track:[{t:0,eastM:-Jh,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:Jh,northM:1e3,altitudeM:1500,headingDeg:90}]}}nextDecorLabel(e){const t=this.ufoElement.sighting.decor.filter(i=>i.kind===e).length;return`${this.decorKindSelect.querySelector(`option[value="${e}"]`)?.textContent??e} ${t+1}`}deleteDecor(){if(this.currentDecorId===void 0)return;const e=this.ufoElement.sighting;e.decor=e.decor.filter(t=>t.id!==this.currentDecorId),this.currentDecorId=e.decor[0]?.id,this.refreshDecorList(),this.ufoElement.refresh()}selectDecor(e){this.currentDecorId=e,this.decorSelect.value=e,this.syncDecorFields()}updateDecor(){if(this.currentDecorId===void 0)return;const e=this.ufoElement.sighting,t=this.wrapDegrees(Number(this.decorHeadingInput.value),this.decorHeadingInput)??0,n=this.decorWitnessSideSelect.value;e.decor=e.decor.map(i=>{if(i.id!==this.currentDecorId)return i;const s=Kr(i.kind)&&n!==""?n:void 0,a=Number(this.decorEastInput.value),o=Number(this.decorNorthInput.value),l=Number(this.decorAltitudeInput.value),c=i.track??(l!==0?[]:void 0);if(c){const h=this.ufoElement.currentTime,d={t:h,eastM:a,northM:o,altitudeM:l,headingDeg:t},u=c.filter(f=>f.t!==h);return{...i,title:this.said.write(i.title,this.decorTitleInput.value,this.writingLanguage),color:this.statedDecorColor(i),track:[...u,d].sort((f,p)=>f.t-p.t),sightingUrl:this.stringOrUndefined(this.decorSightingUrlInput.value),witnessSide:s,sizeM:this.statedDecorSize(),model:this.statedDecorModel(),floors:i.kind==="building"?Number(this.decorFloorsInput.value):void 0,occupiedFloor:i.kind==="building"?Number(this.decorOccupiedFloorInput.value):void 0}}return{...i,title:this.said.write(void 0,this.decorTitleInput.value,this.writingLanguage),color:this.statedDecorColor(i),eastM:a,northM:o,headingDeg:t,sightingUrl:this.stringOrUndefined(this.decorSightingUrlInput.value),witnessSide:s,sizeM:this.statedDecorSize(),model:this.statedDecorModel(),floors:i.kind==="building"?Number(this.decorFloorsInput.value):void 0,occupiedFloor:i.kind==="building"?Number(this.decorOccupiedFloorInput.value):void 0}}),this.decorSelect.options[this.decorSelect.selectedIndex].textContent=this.decorLabel(e.decor.find(i=>i.id===this.currentDecorId)),this.syncDecorVisibility(),this.updateDecorTitleValidity(),this.ufoElement.refresh()}syncDecorSizeFields(e){const t=e?nn.naturalSize(e.kind,e.floors):void 0,n=[[this.decorWidthInput,e?.sizeM?.widthM,t?.widthM],[this.decorLengthInput,e?.sizeM?.lengthM,t?.lengthM],[this.decorHeightInput,e?.sizeM?.heightM,t?.heightM]];for(const[i,s,a]of n)i.value=s===void 0?"":String(this.roundedMeters(s)),i.placeholder=a===void 0?"":String(this.roundedMeters(a))}syncDecorModelFields(e){this.refreshDecorModelOptions(e),this.decorModelSelect.value=e?.model?.id??"",this.decorModelUrlInput.value=e?.model?.url??"",this.decorModelTitleInput.value=e?.model?.credit?.title??"",this.decorModelAuthorInput.value=e?.model?.credit?.author??"",this.decorModelLicenseInput.value=e?.model?.credit?.license??"",this.decorModelSourceInput.value=e?.model?.credit?.sourceUrl??"",this.decorModelAdvanced.open=e?.model?.url!==void 0}async refreshDecorModelOptions(e){const t=e??this.ufoElement.sighting.decor.find(a=>a.id===this.currentDecorId),n=t?await this.decorModelProvider.entries(t.kind).catch(()=>[]):[],i=t?.model?.id??"",s=document.createElement("option");s.value="",s.textContent=this.messages.decorModelNone,this.decorModelSelect.replaceChildren(s,...n.map(a=>{const o=document.createElement("option");return o.value=a.id,o.textContent=a.name,o.title=`${a.credit.title}${a.credit.author?` — ${a.credit.author}`:""} (${a.credit.license})`,o})),this.decorModelSelect.value=i}updateDecorModelChoice(){const e=this.decorModelSelect.value;(async()=>{const t=e?await this.decorModelProvider.entry(e).catch(()=>{}):void 0,n=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId);if(t?.sizeM&&n&&!n.sizeM){const i=[[this.decorWidthInput,t.sizeM.widthM],[this.decorLengthInput,t.sizeM.lengthM],[this.decorHeightInput,t.sizeM.heightM]];for(const[s,a]of i)a!==void 0&&(s.value=String(this.roundedMeters(a)))}this.updateDecor()})()}roundedMeters(e){return Math.round(e*100)/100}positiveMeters(e){const t=Number(e);return e.trim()===""||!Number.isFinite(t)||t<=0?void 0:t}statedDecorColor(e){const t=this.decorColorInput.value;return t==="#808080"&&e.color===void 0?void 0:t}statedDecorSize(){const e=this.positiveMeters(this.decorWidthInput.value),t=this.positiveMeters(this.decorLengthInput.value),n=this.positiveMeters(this.decorHeightInput.value);return e===void 0&&t===void 0&&n===void 0?void 0:{widthM:e,lengthM:t,heightM:n}}statedDecorModel(){const e=this.stringOrUndefined(this.decorModelUrlInput.value);if(e){const n=this.stringOrUndefined(this.decorModelTitleInput.value),i=this.stringOrUndefined(this.decorModelLicenseInput.value);return{url:e,credit:n!==void 0&&i!==void 0?{title:n,license:i,author:this.stringOrUndefined(this.decorModelAuthorInput.value),sourceUrl:this.stringOrUndefined(this.decorModelSourceInput.value)}:void 0}}const t=this.stringOrUndefined(this.decorModelSelect.value);return t===void 0?void 0:{id:t}}addMilestone(){const e=Math.round(this.ufoElement.currentTime),t=this.ufoElement.sighting;t.milestones.find(i=>i.t===e)||(t.milestones=pa([...t.milestones,{t:e,label:this.nextMilestoneLabel()}])),this.currentMilestoneT=e,this.refreshMilestoneList(),this.ufoElement.refresh()}nextMilestoneLabel(){const e=new Set(this.ufoElement.sighting.milestones.map(t=>t.label));for(let t=0;t<26;t++){const n=String.fromCharCode(65+t);if(!e.has(n))return n}return String(this.ufoElement.sighting.milestones.length+1)}deleteMilestone(){const e=this.currentMilestoneT;if(e===void 0)return;const t=this.ufoElement.sighting,n=t.milestones.find(i=>i.t===e);n&&this.askConfirm(this.messages.confirmDeleteMilestone.replace("{name}",this.said.read(n.label)??""),()=>{t.milestones=t.milestones.filter(i=>i.t!==e),this.currentMilestoneT=t.milestones[0]?.t,this.refreshMilestoneList(),this.ufoElement.refresh()})}selectMilestone(e){this.currentMilestoneT=e,this.syncMilestoneFields(),this.ufoElement.currentTime=e}updateMilestone(){const e=this.currentMilestoneT;if(e===void 0)return;const t=this.ufoElement.sighting;t.milestones=t.milestones.map(n=>n.t===e?{...n,label:this.said.write(n.label,this.milestoneLabelInput.value,this.writingLanguage)??"",note:this.said.write(n.note,this.milestoneNoteInput.value,this.writingLanguage)}:n),this.refreshMilestoneList(),this.ufoElement.refresh()}refreshMilestoneList(){const e=pa(this.ufoElement.sighting.milestones);e.some(t=>t.t===this.currentMilestoneT)||(this.currentMilestoneT=e[0]?.t),this.milestoneSelect.replaceChildren(...e.map(t=>{const n=document.createElement("option");return n.value=String(t.t),n.textContent=`${this.said.read(t.label)??""} — ${this.formatSeconds(t.t)}`,n.title=this.said.read(t.note)??"",n})),this.currentMilestoneT!==void 0&&(this.milestoneSelect.value=String(this.currentMilestoneT)),this.syncMilestoneFields()}formatSeconds(e){return`${(e/1e3).toFixed(1)} s`}syncMilestoneFields(){const e=this.ufoElement.sighting.milestones.find(n=>n.t===this.currentMilestoneT),t=e!==void 0;for(const n of[this.milestoneSelect,this.milestoneLabelInput,this.milestoneNoteInput,this.deleteMilestoneButton])n.disabled=!t,this.setRowVisible(n,t);this.milestoneLabelInput.value=this.said.read(e?.label)??"",this.milestoneNoteInput.value=this.said.read(e?.note)??""}updateDecorTitleValidity(){const e=this.currentDecorId!==void 0&&this.decorTitleInput.value==="";this.decorTitleInput.classList.toggle("invalid",e),this.decorTitleInput.setAttribute("aria-invalid",String(e))}updateDecorWindows(){if(this.currentDecorId===void 0)return;const e=this.ufoElement.sighting;e.decor=e.decor.map(t=>{if(t.id!==this.currentDecorId)return t;const n={};for(const i of gr){const s=this.decorWindowInputs[i];if(s.value==="")continue;const a=id(t.kind,i)?0:nd,o=Math.max(a,Math.min(100,Number(s.value)));n[i]=o,String(o)!==s.value&&(s.value=String(o))}return{...t,windows:n}}),this.ufoElement.refresh()}updateDecorLit(){if(this.currentDecorId===void 0||this.ufoElement.playbackState==="playing")return;const e=this.ufoElement.sighting,t=this.ufoElement.currentTime,n=this.decorLitInput.checked;e.decor=e.decor.map(i=>{if(i.id!==this.currentDecorId)return i;const s=[...(i.litKeyframes??[]).filter(a=>a.t!==t),{t,lit:n}].sort((a,o)=>a.t-o.t);return{...i,litKeyframes:s}}),this.ufoElement.refresh()}refreshDecorList(){const e=this.ufoElement.sighting.decor;this.decorSelect.innerHTML="";for(const t of e){const n=document.createElement("option");n.value=t.id,n.textContent=this.decorLabel(t),this.decorSelect.appendChild(n)}this.currentDecorId!==void 0&&(this.decorSelect.value=this.currentDecorId),this.syncDecorFields()}syncDecorFields(){const e=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId),t=e!==void 0;this.deleteDecorButton.disabled=!t;for(const n of[this.decorSelect,this.decorTitleInput,this.decorEastInput,this.decorNorthInput,this.decorHeadingInput,this.decorLitInput,this.decorSightingUrlInput,this.decorWidthInput,this.decorLengthInput,this.decorHeightInput,this.decorModelSelect,this.decorModelUrlInput,this.decorModelTitleInput,this.decorModelAuthorInput,this.decorModelLicenseInput,this.decorModelSourceInput,this.decorFloorsInput,this.decorOccupiedFloorInput,this.decorWitnessSideSelect,this.decorLightRigSelect,this.decorAltitudeInput,this.lookAtDecorButton])n.disabled=!t;this.decorTitleInput.value=this.said.read(e?.title)??"",this.decorColorInput.value=e?.color??"#808080",this.showDecorPlacement(e),this.decorLitInput.checked=e?jl(e,this.ufoElement.currentTime):!1,this.refreshDecorLightRigOptions(e),this.decorSightingUrlInput.value=e?.sightingUrl??"",this.syncDecorSizeFields(e),this.syncDecorModelFields(e),this.decorFloorsInput.value=String(e?.floors??ta),this.decorOccupiedFloorInput.value=String(e?.occupiedFloor??0),this.decorWitnessSideSelect.value=e?.witnessSide??"";for(const n of gr){const i=e?.windows?.[n];this.decorWindowInputs[n].value=i===void 0?"":String(i)}this.syncDecorVisibility(),this.updateDecorTitleValidity()}setRowVisible(e,t){const n=e.closest("label")??e;n.hidden=!t}syncDecorVisibility(){const e=this.ufoElement.sighting.decor.find(c=>c.id===this.currentDecorId),t=e!==void 0,n=e?.kind;this.setRowVisible(this.decorSelect,t),this.setRowVisible(this.deleteDecorButton,t),this.setRowVisible(this.decorTitleInput,t),this.setRowVisible(this.decorEastInput,t),this.setRowVisible(this.decorNorthInput,t),this.setRowVisible(this.decorAltitudeInput,t),this.setRowVisible(this.decorHeadingInput,t),this.setRowVisible(this.decorWidthInput,t),this.setRowVisible(this.decorLengthInput,t),this.setRowVisible(this.decorHeightInput,t),this.setRowVisible(this.decorModelSelect,t),this.decorModelAdvanced.hidden=!t,this.setRowVisible(this.decorLitInput,t&&e?.kind!=="aircraft");const i=t&&n!==void 0&&Nu(n);this.setRowVisible(this.labelDecorWindows,i);const s=n!==void 0?ku(n):[];for(const c of gr)this.decorWindowInputs[c].disabled=!t,this.decorWindowInputs[c].min=String(n!==void 0&&id(n,c)?0:nd),this.setRowVisible(this.decorWindowInputs[c],i&&s.includes(c));const a=t&&n!==void 0&&Kr(n);this.setRowVisible(this.decorWitnessSideSelect,a);const o=n!==void 0?T1(n):[];for(const c of gr)this.optionWitnessSide[c].hidden=!o.includes(c);const l=t&&n==="building";this.setRowVisible(this.decorFloorsInput,l),this.setRowVisible(this.decorOccupiedFloorInput,l),this.decorOccupiedFloorInput.max=String(e?.floors??ta)}showDecorPlacement(e){const t=e?fa(e,this.ufoElement.currentTime):void 0,n=[[this.decorEastInput,t?.eastM??0],[this.decorNorthInput,t?.northM??0],[this.decorAltitudeInput,t?.altitudeM??0],[this.decorHeadingInput,t?.headingDeg??0]];for(const[i,s]of n)this.shadow.activeElement!==i&&(i.value=String(this.rounded(s)))}syncDecorPlacementFromTimeline(){this.ufoElement.playbackState!=="playing"&&this.showDecorPlacement(this.ufoElement.sighting.decor.find(e=>e.id===this.currentDecorId))}showNextMeteor(){const e=this.sceneElement.meteorByRank(this.meteorRank++);e&&(this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=e.t,this.headingInput.value=String(Math.round(e.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(e.altitudeDeg*10)/10),this.updateObserver())}resetMeteorRankIfSkyChanged(){const e=this.sceneElement.meteorByRank(0),t=e?`${e.t}`:"";t!==this.meteorRankFor&&(this.meteorRankFor=t,this.meteorRank=0)}meteorRankFor;skyCandidatesKey;meteorRank=0;showerLanguage(){return na(Ts.preferencesFor(this),["en","fr"])}get said(){return this.saidTexts??=new Zi(Ts.preferencesFor(this))}saidTexts;tagNames=new rd({});get writingLanguage(){return this.showerLanguage()}refreshSkyCandidates(){this.resetMeteorRankIfSkyChanged();const e=this.ufoElement.sighting,t=e.event.place?.[0],n=e.event.time,i=t&&t.lat!==void 0&&t.lng!==void 0&&n?.year!==void 0?Ds(n,t.lng,e.event.utcOffsetHours):void 0,s=JSON.stringify([i?.getTime(),t?.lat,t?.lng,this.groundElevationM,e.instrumentId,e.exposureSeconds,Ut(e,0),this.messages.skyLine,this.meteorRankFor,this.sceneElement.satelliteState.status,this.satelliteSpanMs()]);if(s===this.skyCandidatesKey)return;if(this.skyCandidatesKey=s,!i||!t||t.lat===void 0||t.lng===void 0){this.showMeteorButton.hidden=!0,this.showCometButton.hidden=!0,this.showSatelliteButton.hidden=!0,this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",this.messages.skyUnknown);return}const a={lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0},o=[this.starsClause(i,a),this.showerClause(i,a),this.cometClause(i,a),this.satelliteClause(i,a),this.opticsClause(i,a),this.rainbowClause(i,a),this.glowClause(i,a)].filter(l=>l!==void 0);this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",o.join(" · "))}instrumentGain(){const e=this.ufoElement.sighting;return mn.gainFor(e.instrument,{fNumber:tt(e,0)?.fNumber,fieldOfViewDeg:ln.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const n=Cn("Sun",e,t).altitudeDeg,i=this.instrumentGain(),s=nr(n,i),a=c=>c.toLocaleString(void 0,{maximumFractionDigits:1});if(s<OA)return this.messages.skyStarsNone;const o=this.ufoElement.sighting.instrument,l=Math.abs(i)<.1?this.messages.skyStarsEye.replace("{limit}",a(s)):(i>0?this.messages.skyStarsDeeper:this.messages.skyStarsShallower).replace("{limit}",a(s)).replace("{device}",o.name[this.showerLanguage()]).replace("{gain}",a(Math.abs(i))).replace("{eye}",a(nr(n)));return s<=ao?l:l+this.messages.skyStarsCatalogue.replace("{catalogue}",a(ao))}showerClause(e,t){const n=Dt.observedRatePerHour(Dt.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),i=da.activeAt(e);if(i.length===0)return this.showMeteorButton.hidden=!this.sceneElement.meteorByRank(0),this.messages.skyNothingActive.replace("{sporadic}",n);const s=i.map(a=>{const o=da.radiantPosition(a.shower,e,t);return{entry:a,position:o,rate:da.observedRatePerHour(a.zhr,o.altitudeDeg,a.shower.populationIndex)}}).sort((a,o)=>o.rate-a.rate)[0];return s.rate<=0?(this.showMeteorButton.hidden=!this.sceneElement.meteorByRank(0),this.messages.skyShowerBelowHorizon.replace("{name}",s.entry.shower.name[this.showerLanguage()])):(this.showMeteorButton.hidden=!this.sceneElement.meteorByRank(0),this.messages.skyShowerActive.replace("{name}",s.entry.shower.name[this.showerLanguage()]).replace("{altitude}",String(Math.round(s.position.altitudeDeg))).replace("{bearing}",_s.towards(s.position.azimuthDeg,this.showerLanguage())).replace("{rate}",s.rate.toLocaleString(void 0,{maximumFractionDigits:s.rate<10?1:0})).replace("{sporadic}",n))}cometClause(e,t){const n=ql.brightestAt(e,t);if(!n||n.magnitude>xo){this.showCometButton.hidden=!0;return}return this.showCometButton.hidden=n.position.altitudeDeg<=0,this.cometText(n)}satelliteClause(e,t){const n=Mi.visibilityAt(e,t),i=this.realSatelliteClause(n.lowOrbitLit||n.sunAltitudeDeg>=0);if(i!==void 0)return i;if(this.showSatelliteButton.hidden=!0,!n.anythingInOrbit)return n.sunAltitudeDeg<0?this.messages.skySatellitesNotYet:void 0;const s=nr(n.sunAltitudeDeg,this.instrumentGain()),a=n.classes.filter(d=>d.peakMagnitude<=s),o=this.listed(a.map(d=>d.name[this.showerLanguage()]));if(n.sunAltitudeDeg>=0)return a.length===0?void 0:(a.length===1?this.messages.skySatellitesDaylightOne:this.messages.skySatellitesDaylight).replace("{eras}",o);const l=Math.round(n.shadowHeightKm).toLocaleString(),c=(n.trackedObjects??0).toLocaleString(),h=d=>d.replace("{height}",l).replace("{count}",c);return n.lowOrbitLit?a.length===0?h(this.messages.skySatellitesLit):h(this.messages.skySatellitesLitWith).replace("{eras}",o):h(this.messages.skySatellitesShadowed)}realSatelliteClause(e){const t=this.sceneElement.satelliteState;if(t.status!=="ready")return;if(t.coverage?.every(h=>h.status!=="covered"))return this.showSatelliteButton.hidden=!0,t.coverage.some(h=>h.status==="gap")?this.messages.skySatelliteElementsGap:void 0;const n=this.visibleSatellitePasses(),i=n.filter(h=>this.passTimelineMs(h)<=this.ufoElement.seekableDuration);if(this.showSatelliteButton.hidden=i.length===0,n.length===0)return e?this.messages.skySatellitePassesNone:void 0;const a=n[0].peak,l=(n.length===1?this.messages.skySatellitePassesOne:this.messages.skySatellitePasses).replace("{count}",String(n.length)).replace("{name}",a.object.name).replace("{magnitude}",a.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(a.altitudeDeg))).replace("{bearing}",_s.towards(a.azimuthDeg,this.showerLanguage())).replace("{time}",this.witnessClock(a.date)),c=this.starlinkTrain(n);return c?`${l}, ${c}`:l}visibleSatellitePasses(){const e=this.instrumentGain(),t=this.observerAtStart();return this.sceneElement.satellitePassesDuring(this.satelliteSpanMs()).filter(n=>{const i=n.peak.magnitude;if(i===void 0)return!1;const s=Cn("Sun",n.peak.date,t);return i<=nr(s.altitudeDeg,e)}).sort((n,i)=>n.peak.magnitude-i.peak.magnitude)}starlinkTrain(e){const t=new Map;for(const a of e){const{kind:o,launch:l}=a.peak.object;o!=="starlink"||!l||(a.peak.date.getTime()-Date.parse(`${l}T00:00:00Z`))/864e5>60||t.set(l,(t.get(l)??0)+1)}const[n,i]=[...t.entries()].sort((a,o)=>o[1]-a[1])[0]??[];if(!n||!i||i<3)return;const s=new Date(`${n}T00:00:00Z`).toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skySatelliteTrain.replace("{count}",String(i)).replace("{date}",s)}satelliteSpanMs(){const e=(this.ufoElement.sighting.event.durationSeconds??0)*1e3;return Math.max(e,this.ufoElement.seekableDuration)}observerAtStart(){const e=this.ufoElement.sighting.event.place?.[0],t=tt(this.ufoElement.sighting,0);return{lat:t?.lat??e?.lat??0,lng:t?.lng??e?.lng??0,elevationM:this.groundElevationM??0}}passTimelineMs(e){const t=this.ufoElement.sighting,n=Ds(t.event.time??{},this.observerAtStart().lng,t.event.utcOffsetHours);return n?e.peak.date.getTime()-n.getTime():1/0}witnessClock(e){const n=this.ufoElement.sighting.event.utcOffsetHours??Math.round(this.observerAtStart().lng/15);return new Date(e.getTime()+n*36e5).toLocaleTimeString(this.showerLanguage(),{hour:"2-digit",minute:"2-digit",second:"2-digit",timeZone:"UTC"})}showNextSatellite(){const e=this.visibleSatellitePasses().filter(i=>this.passTimelineMs(i)<=this.ufoElement.seekableDuration);if(e.length===0)return;const t=e.map(i=>`${i.object.norad}@${i.peak.date.getTime()}`).join();t!==this.satelliteRankFor&&(this.satelliteRankFor=t,this.satelliteRank=0);const n=e[this.satelliteRank++%e.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.passTimelineMs(n),this.headingInput.value=String(Math.round(n.peak.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(n.peak.altitudeDeg*10)/10),this.updateObserver()}satelliteRankFor;satelliteRank=0;opticsClause(e,t){const n=Ut(this.ufoElement.sighting,0),i=Cn("Sun",e,t),s=Cn("Moon",e,t),a=Je.deckLitUntilDeg(Je.DECK_HEIGHT_M),o=i.altitudeDeg>-a,l=o?i:s;if(l.altitudeDeg<=-a)return;const c=n.highCloudCover;if(c===void 0||c<=0)return this.messages.skyOpticsNoIce;if(Je.strength(c,n.lowerCloudCover??n.cloudCover,l.altitudeDeg,a)<=0)return this.messages.skyOpticsHidden;const h=o?this.messages.skyOpticsSun:this.messages.skyOpticsMoon,d=this.listed(Je.formsAt(l.altitudeDeg,a).map(f=>this.opticsFormName(f))),u=n.iceCrystalAlignment??.65;return this.messages.skyOpticsPossible.replace("{forms}",d).replace("{source}",h)+this.messages.skyOpticsAlignment.replace("{alignment}",String(Math.round(u*100)))}rainbowClause(e,t){const n=Ut(this.ufoElement.sighting,0);if(n.precipitationType!=="rain"||n.precipitationIntensity<=0)return;const i=Cn("Sun",e,t),s=Cn("Moon",e,t),a=i.altitudeDeg>0,o=a?i:s;if(o.altitudeDeg<=0)return this.messages.skyBowNoSource;const l=n.lowerCloudCover??n.cloudCover;if(an.strength(n.precipitationIntensity,l,o.altitudeDeg)<=0)return this.messages.skyBowHidden;const c=an.formsAt(o.altitudeDeg);if(c.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(o.altitudeDeg))).replace("{radius}",String(Math.round(an.primary().radiusDeg)));const h=this.listed(c.map(u=>this.bowFormName(u)));if(a)return this.messages.skyBowPossible.replace("{forms}",h);const d=Math.round(vc(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",h).replace("{lit}",String(d))}glowClause(e,t){if(Cn("Sun",e,t).altitudeDeg>WA)return;const i=this.glows.assess(e,t),s=this.showerLanguage(),a=[];if(i.milkyWay&&a.push(this.messages.skyGlowBand.replace("{contrast}",this.decimal(i.milkyWay.contrast,1)).replace("{altitude}",String(Math.round(i.milkyWay.altitudeDeg))).replace("{bearing}",_s.towards(i.milkyWay.azimuthDeg,s))),i.zodiacal){const h=i.zodiacal.sunSeparationDeg<=it.CONE_SEPARATION_DEG;a.push((h?this.messages.skyGlowCone:this.messages.skyGlowZodiacalBand).replace("{contrast}",this.decimal(i.zodiacal.contrast,1)).replace("{altitude}",String(Math.round(i.zodiacal.altitudeDeg))).replace("{bearing}",_s.towards(i.zodiacal.azimuthDeg,s)).replace("{elongation}",String(Math.round(i.zodiacal.sunSeparationDeg))))}if(a.length>0)return this.listed(a);const o=this.decimal(i.darkestSkyMagPerArcsec2,1),l=Cn("Moon",e,t),c=i.darkestSkyMagPerArcsec2<VA;if(c&&l.altitudeDeg>0){const h=Math.round(vc(e).illuminatedFraction*100);return this.messages.skyGlowMoon.replace("{lit}",String(h)).replace("{sky}",o)}return c?this.messages.skyGlowTwilight.replace("{sky}",o):this.messages.skyGlowNothingUp.replace("{sky}",o)}glows=new it;bowFormName(e){return(e.id==="primary"?this.messages.skyBowPrimary:this.messages.skyBowSecondary).replace("{radius}",String(Math.round(e.radiusDeg))).replace("{top}",String(Math.round(e.topAltitudeDeg)))}opticsFormName(e){const t=n=>String(Math.round(n??0));switch(e.id){case"halo22":return this.messages.skyOpticsHalo22.replace("{angle}",t(e.angleDeg));case"halo46":return this.messages.skyOpticsHalo46.replace("{angle}",t(e.angleDeg));case"parhelia":return this.messages.skyOpticsParhelia.replace("{angle}",t(e.angleDeg));case"tangentArc":return this.messages.skyOpticsTangentArc;case"parhelicCircle":return this.messages.skyOpticsParhelicCircle;case"circumzenithal":return this.messages.skyOpticsCircumzenithal.replace("{angle}",t(e.angleDeg));case"circumhorizontal":return this.messages.skyOpticsCircumhorizontal;case"pillar":return this.messages.skyOpticsPillar}}listed(e){return new Intl.ListFormat(this.showerLanguage(),{style:"long",type:"conjunction"}).format(e)}cometText(e){const t=e.apparition.name[this.showerLanguage()],n=e.magnitude.toLocaleString(void 0,{maximumFractionDigits:1});return e.position.altitudeDeg<=0?this.messages.skyCometBelowHorizon.replace("{name}",t).replace("{magnitude}",n):(e.elongationDeg<ql.TWILIGHT_ELONGATION_DEG?this.messages.skyCometInDaylight:e.tailLengthDeg===void 0?this.messages.skyCometNoTail:this.messages.skyComet).replace("{name}",t).replace("{magnitude}",n).replace("{altitude}",String(Math.round(e.position.altitudeDeg))).replace("{bearing}",_s.towards(e.position.azimuthDeg,this.showerLanguage())).replace("{tail}",String(Math.round(e.tailLengthDeg??0))).replace("{elongation}",String(Math.round(e.elongationDeg)))}lookAtComet(){const e=this.ufoElement.sighting,t=e.event.place?.[0],n=e.event.time;if(!t||t.lat===void 0||t.lng===void 0||n?.year===void 0)return;const i=Ds(n,t.lng,e.event.utcOffsetHours);if(!i)return;const s=ql.brightestAt(i,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});s&&(this.headingInput.value=String(this.rounded(s.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(s.position.altitudeDeg)),this.updateObserver())}rounded(e){return Math.round(e*10)/10}lookAtDecor(){const e=this.ufoElement.sighting.decor.find(l=>l.id===this.currentDecorId);if(!e)return;const{eastM:t,northM:n,altitudeM:i}=fa(e,this.ufoElement.currentTime),s=Math.hypot(t,n);if(s===0&&i===0)return;const a=Math.atan2(t,n)*180/Math.PI,o=Math.atan2(i-BA,s)*180/Math.PI;this.headingInput.value=String(Math.round(a*10)/10),this.pitchInput.value=String(Math.round(o*10)/10),this.updateObserver()}refreshDecorLightRigOptions(e){const t=e?Nc.forKind(e.kind):[],n=document.createElement("option");n.value="",n.textContent=this.messages.decorLightsNone,this.decorLightRigSelect.replaceChildren(n,...t.map(s=>{const a=document.createElement("option");return a.value=s.id,a.textContent=s.name,a}));const i=e?.lights?.map(s=>s.id).join()??"";this.decorLightRigSelect.value=t.find(s=>s.create().map(a=>a.id).join()===i)?.id??""}updateDecorLightRig(){const e=this.ufoElement.sighting,t=e.decor.find(i=>i.id===this.currentDecorId);if(!t)return;const n=Nc.byId(this.decorLightRigSelect.value);e.decor=e.decor.map(i=>i.id===t.id?{...i,lights:n?n.create():void 0}:i),this.ufoElement.refresh(),this.dispatchEvent(new CustomEvent("sightingchange"))}syncDecorLitFromTimeline(){if(this.ufoElement.playbackState==="playing"||this.shadow.activeElement===this.decorLitInput)return;const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);e&&(this.decorLitInput.checked=jl(e,this.ufoElement.currentTime))}updatePresetButtons(){for(const e of Gm)this.presetButtons[e]?.setAttribute("aria-pressed",String(e===this.currentAppearance.presetId))}get samplingRate(){return Number(this.samplingRateInput.value)}buildPrototype(e=this.defaultBounds()){return _f(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-Vr.width/2,y:e.height/2-Vr.height/2,width:Vr.width,height:Vr.height}}toggleRecording(){this.endDrag();const e=this.ufoElement.canvasElement;this.isRecording?(this.recorder?.stop(),this.isRecording=!1,this.setRecordButtonLabel(!1),this.setCanvasCursor(void 0),e.style.touchAction="",this.sourceSelect.disabled=!1,this.addShapeButton.disabled=!1,this.ufoElement.refresh(),this.refreshSourceList()):(this.recorder=new tA(this.ufoElement.sighting.timeline,new nA(this.samplingRate)),this.recorder.start(this.currentSourceId,this.buildPrototype()),this.isRecording=!0,this.setRecordButtonLabel(!0),this.setCanvasCursor("record"),e.style.touchAction="none",this.sourceSelect.disabled=!0,this.addShapeButton.disabled=!0,this.deleteShapeButton.disabled=!0)}setRecordButtonLabel(e){this.recordButton.textContent=e?"⏹":"⏺";const t=e?this.messages.stop:this.messages.record;this.recordButton.title=t,this.recordButton.setAttribute("aria-label",t)}async loadLocaleMessages(){const e=na(Ts.preferencesFor(this),od);e!=="en"&&(this.tagNames=new rd(await q1(e)),this.showTags(),this.applyMessages(await X1(e)))}showTags(){this.tagsInput.value=this.ufoElement.sighting.event.tags?.map(e=>this.tagNames.name(e)).join(", ")??""}applyMessages(e){this.currentSourceId===kl&&this.shapeTitleInput.value===`${this.messages.shape} 1`?(this.messages=e,this.shapeTitleInput.value=`${this.messages.shape} 1`,this.updateShapeTitle()):this.messages=e,this.presetButtons.oval.textContent=e.oval,this.presetButtons.polygon.textContent=e.polygon,this.contextAddVertexButton.textContent=e.addVertex,this.contextDeleteVertexButton.textContent=e.deleteVertex,this.labelColor.textContent=e.color,this.labelTransparency.textContent=e.transparency,this.labelHalo.textContent=e.halo,this.labelBlur.textContent=e.blur,this.labelBrightness.textContent=e.brightness,this.labelShape.textContent=e.shape,this.labelShapeTitle.textContent=e.shapeTitle,this.labelUtcOffset.textContent=e.utcOffset,this.utcOffsetInput.placeholder=e.utcOffsetPlaceholder,this.labelApparentWidth.textContent=e.apparentWidth,this.labelRealWidth.textContent=e.realWidth,this.labelObjectDistance.textContent=e.distance,this.labelSizeLock.textContent=e.sizeLock;for(const[i,s]of[["option-lock-none",e.lockNone],["option-lock-apparent",e.lockApparent],["option-lock-real",e.lockReal],["option-lock-distance",e.lockDistance]])this.shadow.getElementById(i).textContent=s;this.clearDistanceHypothesisButton.textContent=e.clearDistanceHypothesis,this.clearDistanceHypothesisButton.title=e.clearDistanceHypothesisTitle,this.refreshApparentSize(),this.labelSamplingRate.textContent=e.samplingRate,this.labelDuration.textContent=e.duration,this.durationInput.placeholder=e.durationPlaceholder,this.addShapeButton.title=e.addShape,this.addShapeButton.setAttribute("aria-label",e.addShape),this.deleteShapeButton.title=e.deleteShape,this.deleteShapeButton.setAttribute("aria-label",e.deleteShape),this.contextGroupButton.textContent=e.group,this.contextUngroupButton.textContent=e.ungroup,this.contextBringToFrontButton.textContent=e.bringToFront,this.contextSendToBackButton.textContent=e.sendToBack,this.contextDeleteButton.textContent=e.contextMenuDelete,this.exportButton.textContent=e.export,this.labelImportFile.textContent=e.importFile,this.labelImportUrl.textContent=e.importUrl,this.importUrlInput.placeholder=e.importUrlPlaceholder,this.importUrlButton.textContent=e.importButton,this.labelWitnessAge.textContent=e.witnessAge,this.labelWitnessOccupation.textContent=e.witnessOccupation,this.labelTestimonySource.textContent=e.testimonySource,this.labelTestimonyFollowedUp.textContent=e.testimonyFollowedUp;for(const[i,s]of[["option-source-unknown",e.testimonySourceUnknown],["option-source-on-site",e.testimonySourceOnSite],["option-source-interview",e.testimonySourceInterview],["option-source-telephone",e.testimonySourceTelephone],["option-source-questionnaire",e.testimonySourceQuestionnaire],["option-source-letter",e.testimonySourceLetter],["option-source-press",e.testimonySourcePress],["option-followed-unknown",e.testimonyUnknown],["option-followed-yes",e.testimonyYes],["option-followed-no",e.testimonyNo]]){const a=this.shadow.getElementById(i);a&&(a.textContent=s)}this.labelNarrativeKey.textContent=e.narrativeKey.replace("{source}",Ns[0].name),this.labelNarrativeWorkspace.textContent=e.narrativeWorkspace,this.narrativeWorkspaceInput.placeholder=e.narrativeWorkspacePlaceholder,this.narrativeWorkspaceInput.title=e.narrativeWorkspaceHint,this.labelNarrativeRemember.textContent=e.narrativeRemember,this.narrativeStopButton.textContent=e.narrativeStop,this.narrativeDraftButton.textContent=e.narrativeDraft,this.descriptionInput.placeholder=e.narrativePlaceholder,this.syncNarrativeEnabled(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.labelPlaceName.textContent=e.placeName,this.placeNameInput.placeholder=e.placeNamePlaceholder,this.searchPlaceButton.textContent=e.searchPlace,this.labelPlaceMatch.textContent=e.placeMatch,this.labelLatitude.textContent=e.latitude,this.labelLongitude.textContent=e.longitude,this.labelHeading.textContent=e.heading,this.headingInput.placeholder=e.headingPlaceholder,this.labelPitch.textContent=e.pitch,this.labelRoll.textContent=e.roll,this.labelElevation.textContent=e.elevation,this.labelObservationTime.textContent=e.observationTime,this.labelObservationEndTime.textContent=e.observationEndTime,this.obsTimeInput.placeholder=e.edtfPlaceholder,this.obsTimeInput.title=e.observationTimeHint,this.obsEndTimeInput.placeholder=e.edtfPlaceholder,this.obsEndTimeInput.title=e.observationEndTimeHint,this.presetsGroup.setAttribute("aria-label",e.presetsGroupLabel),this.labelDecor.textContent=e.decor,this.labelDecorGroup.textContent=e.decor,this.optionDecorBuilding.textContent=e.decorBuilding,this.optionDecorTree.textContent=e.decorTree,this.optionDecorCrop.textContent=e.decorCrop,this.optionDecorMound.textContent=e.decorMound,this.optionDecorStreetlight.textContent=e.decorStreetlight,this.optionDecorVehicle.textContent=e.decorVehicle,this.optionDecorAircraft.textContent=e.decorAircraft,this.optionDecorEntity.textContent=e.decorEntity,this.labelDecorLights.textContent=e.decorLights,this.labelDecorAltitude.textContent=e.decorAltitude,this.showMeteorButton.title=e.showMeteor,this.showMeteorButton.setAttribute("aria-label",e.showMeteor),this.showCometButton.title=e.showComet,this.showCometButton.setAttribute("aria-label",e.showComet),this.showSatelliteButton.title=e.showSatellite,this.showSatelliteButton.setAttribute("aria-label",e.showSatellite),this.lookAtDecorButton.title=e.lookAtDecor,this.lookAtDecorButton.setAttribute("aria-label",e.lookAtDecor),this.optionDecorWitness.textContent=e.decorWitness,this.deleteDecorButton.title=e.deleteDecor,this.deleteDecorButton.setAttribute("aria-label",e.deleteDecor),this.labelDecorTitle.textContent=e.decorTitle,this.labelDecorEast.textContent=e.decorEast,this.labelDecorNorth.textContent=e.decorNorth,this.labelDecorHeading.textContent=e.decorHeading,this.labelDecorColor.textContent=e.decorColor,this.labelDecorLit.textContent=e.decorLit,this.labelDecorSightingUrl.textContent=e.decorSightingUrl,this.contextViewTestimonyButton.textContent=e.viewTestimony,this.labelContextMasks.textContent=`${e.masks} ▸`,this.addDecorWitnessButton.textContent=e.addWitness,this.addDecorBuildingButton.title=e.addDecor,this.addDecorBuildingButton.setAttribute("aria-label",e.addDecor),this.confirmAcceptButton.textContent=e.confirmAccept,this.confirmDeclineButton.textContent=e.confirmDecline,this.labelMilestones.textContent=e.milestones,this.labelMilestoneLabel.textContent=e.milestoneLabel,this.labelMilestoneNote.textContent=e.milestoneNote;for(const[i,s]of[[this.addMilestoneButton,e.addMilestone],[this.deleteMilestoneButton,e.deleteMilestone]])i.title=s,i.setAttribute("aria-label",s);this.labelDecorWidth.textContent=e.decorWidth,this.labelDecorLength.textContent=e.decorLength,this.labelDecorHeight.textContent=e.decorHeight,this.labelDecorModel.textContent=e.decorModel,this.labelDecorModelAdvanced.textContent=e.decorModelAdvanced,this.labelDecorModelUrl.textContent=e.decorModelUrl,this.labelDecorModelTitle.textContent=e.decorModelTitle,this.labelDecorModelAuthor.textContent=e.decorModelAuthor,this.labelDecorModelLicense.textContent=e.decorModelLicense,this.labelDecorModelSource.textContent=e.decorModelSource,this.labelDecorFloors.textContent=e.decorFloors,this.labelDecorOccupiedFloor.textContent=e.decorOccupiedFloor,this.labelDecorWitnessSide.textContent=e.decorWitnessSide,this.labelDecorWindows.textContent=e.decorWindows,this.optionWitnessSideNone.textContent=e.decorWitnessSideNone;const t={front:e.decorSideFront,behind:e.decorSideBehind,left:e.decorSideLeft,right:e.decorSideRight,"front-left":e.decorSideFrontLeft,"front-right":e.decorSideFrontRight,"behind-left":e.decorSideBehindLeft,"behind-right":e.decorSideBehindRight};for(const i of gr)this.labelDecorSide[i].textContent=t[i],this.optionWitnessSide[i].textContent=t[i];this.refreshDecorList(),this.labelWitnessId.textContent=e.witnessId,this.labelWitnessDirName.textContent=e.witnessDirName,this.labelWitnessTitle.textContent=e.witnessTitle,this.labelWitnessLastName.textContent=e.witnessLastName,this.labelWitnessFirstNames.textContent=e.witnessFirstNames,this.witnessFirstNamesInput.placeholder=e.tagsPlaceholder,this.labelCaseId.textContent=e.caseId,this.labelDescription.textContent=e.description,this.labelTags.textContent=e.tags,this.tagsInput.placeholder=e.tagsPlaceholder,this.labelShapeGroup.textContent=e.shapeGroup,this.labelTemporalGroup.textContent=e.temporalGroup,this.labelLocationGroup.textContent=e.locationGroup,this.labelObservationGroup.textContent=e.observationGroup,this.labelWitnessGroup.textContent=e.witnessGroup,this.labelWeatherGroup.textContent=e.weather,this.refreshTimeQualifierOptions(),this.edtfModeButton.title=e.edtfModeTitle,this.edtfModeButton.setAttribute("aria-label",e.edtfModeTitle),this.paramSummaryBuilder=new Bf(e,this.showerLanguage(),this.said,this.tagNames),this.refreshParamSummary();const n=this.skyDetailsButton.getAttribute("aria-expanded")==="true";this.skyDetailsButton.title=n?e.skyDetailsHide:e.skyDetails,this.skyDetailsButton.setAttribute("aria-label",this.skyDetailsButton.title),this.labelCloudCover.textContent=e.cloudCover,this.labelHighCloud.textContent=e.highCloudCover,this.labelIceAlignment.textContent=e.iceCrystalAlignment,this.labelFNumber.textContent=e.aperture,this.labelExposure.textContent=e.exposure,this.labelFocusDistance.textContent=e.focusDistance,this.syncOpticsFromInstrument(),this.labelCloudDarkness.textContent=e.cloudDarkness,this.labelCloudBase.textContent=e.cloudBase,this.labelPrecipitationType.textContent=e.precipitationType,this.optionPrecipitationNone.textContent=e.precipitationNone,this.optionPrecipitationRain.textContent=e.precipitationRain,this.optionPrecipitationSnow.textContent=e.precipitationSnow,this.optionPrecipitationHail.textContent=e.precipitationHail,this.labelPrecipitationIntensity.textContent=e.precipitationIntensity,this.labelWindDirection.textContent=e.windDirection,this.labelWindSpeed.textContent=e.windSpeed,this.labelStorm.textContent=e.storm,this.labelCloudsGroup.textContent=e.cloudsGroup,this.labelPrecipitationGroup.textContent=e.precipitationGroup,this.labelWindGroup.textContent=e.windGroup,this.labelWeatherInferred.textContent=e.weatherInferred,this.syncWeatherSourceState(),this.labelSoundGroup.textContent=e.soundGroup,this.labelSoundKind.textContent=e.soundKind,this.labelSoundVolume.textContent=e.soundVolume,this.labelSoundPitch.textContent=e.soundPitch,this.labelSoundSrc.textContent=e.soundSrc,this.soundSrcInput.placeholder=e.soundSrcPlaceholder,this.labelReferenceGroup.textContent=e.referenceGroup,this.labelReference.textContent=e.reference,this.labelReferenceTitle.textContent=e.referenceTitle,this.labelReferenceSrc.textContent=e.referenceSrc,this.referenceSrcInput.placeholder=e.referenceSrcPlaceholder,this.labelReferenceKind.textContent=e.referenceKind,this.referenceKindSelect.querySelector("#reference-kind-photo").textContent=e.referencePhoto,this.referenceKindSelect.querySelector("#reference-kind-panorama").textContent=e.referencePanorama,this.labelReferenceCredit.textContent=e.referenceCredit,this.labelReferenceCreditUrl.textContent=e.referenceCreditUrl,this.labelReferenceT.textContent=e.referenceT,this.labelReferenceDrawing.textContent=e.referenceDrawing,this.labelReferenceOpacity.textContent=e.referenceOpacity,this.labelReferenceHeading.textContent=e.referenceHeading,this.labelReferencePitch.textContent=e.referencePitch,this.labelReferenceRoll.textContent=e.referenceRoll,this.labelReferenceFov.textContent=e.referenceFov,this.referenceUsePoseButton.textContent=e.referenceUsePose,this.addReferenceUrlButton.textContent=e.addReferenceUrl,this.labelAddReferenceFile.textContent=e.addReferenceFile,this.deleteReferenceButton.title=e.deleteReference,this.deleteReferenceButton.setAttribute("aria-label",e.deleteReference),this.labelReferenceLandmarks.textContent=e.referenceLandmarks,this.addReferenceLandmarkButton.textContent=e.addReferenceLandmark,this.deleteReferenceLandmarkButton.title=e.deleteReferenceLandmark,this.deleteReferenceLandmarkButton.setAttribute("aria-label",e.deleteReferenceLandmark),this.labelReferenceLandmarkLabel.textContent=e.referenceLandmarkLabel,this.referenceLandmarkLabelInput.placeholder=e.referenceLandmarkLabelPlaceholder,this.referenceAdoptPoseButton.textContent=e.referenceAdoptPose,this.referenceStreetSearchButton.textContent=e.referenceStreetSearch,this.referenceStreetAddButton.textContent=e.referenceStreetAdd;for(const[i,s]of this.soundKindOptions)s.textContent=this.soundKindLabel(i,e);this.labelInstrument.textContent=e.instrument,this.loopButton.title=e.autoReplay,this.loopButton.setAttribute("aria-label",e.autoReplay),this.setRecordButtonLabel(this.isRecording),this.syncPlaybackControls()}onPointerDown(e){if(this.isRecording){this.onPointerMove(e);return}const t=this.canvasPointFromEvent(e);if(!t)return;const n=this.canvasMode();if(n==="picture"){this.ufoElement.playbackState!=="playing"&&this.beginReferenceDrag(t);return}const i=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,a=this.ufoElement.playbackState==="playing",o=n==="shape";if(o)if(this.selectedSourceIds.size>1){const h=new kc(this.selectedMembers()),d=st.hitTestHandle({bounds:h.bounds(),angle:0},t);if(d==="rotate"){if(a)return;this.dragState={kind:"group-rotate",group:h,startPointer:t},this.startDragListening();return}if(d){if(a)return;this.dragState={kind:"group-resize",group:h,handle:d},this.startDragListening();return}}else{const h=i.getInterpolatedShapeAt(s,this.currentSourceId),d=h?.kind==="polygon"?st.hitTestVertex(h,t):void 0;if(h?.kind==="polygon"&&d!==void 0){if(a)return;this.dragState={kind:"vertex",sourceId:this.currentSourceId,original:h,vertexIndex:d},this.startDragListening();return}const u=h&&st.hitTestHandle(h,t);if(h&&u){if(a)return;this.beginDrag(u==="rotate"?"rotate":"resize",this.currentSourceId,h,t,u);return}}const l=this.ufoElement.shapeAt(t.x,t.y,Um);if(!l){const h=this.pickDecorAt(e);if(h!==void 0){this.selectDecor(h);return}a||this.beginCameraDrag(t);return}if(this.revealShapePanel(),e.shiftKey?this.toggleUnitSelection(l.sourceId):this.selectedSourceIds.has(l.sourceId)||this.selectUnit(l.sourceId),a||!o)return;const c=[...this.selectedSourceIds].map(h=>({sourceId:h,original:h===l.sourceId?l.shape:i.getInterpolatedShapeAt(s,h)??l.shape}));this.dragState={kind:"move",sources:c,startPointer:t},this.startDragListening()}revealShapePanel(){const e=this.groupTabs.find(t=>t.getAttribute("aria-controls")==="group-shape");e&&this.toggleGroup(e,!0)}selectedMembers(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime;return[...this.selectedSourceIds].map(n=>({sourceId:n,shape:e.getInterpolatedShapeAt(t,n)})).filter(n=>!!n.shape)}selectUnit(e){const t=this.ufoElement.sighting.timeline.groupMembers(e)??[e];t.length===this.selectedSourceIds.size&&t.every(n=>this.selectedSourceIds.has(n))&&e===this.currentSourceId||(this.selectedSourceIds=new Set(t),this.currentSourceId=e,this.refreshSourceList(),this.onSelectionOrTimeChanged())}toggleUnitSelection(e){const t=this.ufoElement.sighting.timeline,n=t.groupMembers(e)??[e];if(n.every(s=>this.selectedSourceIds.has(s))){if(n.length>=this.selectedSourceIds.size)return;for(const s of n)this.selectedSourceIds.delete(s);if(!this.selectedSourceIds.has(this.currentSourceId)){const s=t.sourceIds;this.currentSourceId=[...this.selectedSourceIds].sort((a,o)=>s.indexOf(a)-s.indexOf(o)).pop()}}else{for(const s of n)this.selectedSourceIds.add(s);this.currentSourceId=e}this.refreshSourceList(),this.onSelectionOrTimeChanged()}onContextMenu(e){if(e.preventDefault(),this.isRecording||this.ufoElement.playbackState==="playing")return;this.hideContextMenu(),this.hideDecorContextMenu();const t=this.canvasPointFromEvent(e);if(!t)return;const n=this.ufoElement.sighting.timeline,i=this.ufoElement.currentTime,s=this.selectedSourceIds.size===1?n.getInterpolatedShapeAt(i,this.currentSourceId):void 0,o=s?.kind==="polygon"&&st.hitTestVertex(s,t)!==void 0?{sourceId:this.currentSourceId}:this.ufoElement.shapeAt(t.x,t.y,Um);if(o){this.selectedSourceIds.has(o.sourceId)||this.selectUnit(o.sourceId),this.currentSourceId=o.sourceId,this.contextMenuPoint=t,this.showContextMenu(e.clientX,e.clientY);return}const l=this.pickDecorAt(e),c=l?this.ufoElement.sighting.decor.find(h=>h.id===l):void 0;c&&this.showDecorContextMenu(e.clientX,e.clientY,c)}pickDecorAt(e){const n=this.ufoElement.canvasElement.getBoundingClientRect();if(n.width===0||n.height===0)return;const i=(e.clientX-n.left)/n.width*2-1,s=-((e.clientY-n.top)/n.height*2-1);return this.sceneElement.pickDecorAt(i,s)}showContextMenu(e,t){this.contextMenu.style.left=`${e}px`,this.contextMenu.style.top=`${t}px`,this.contextMenu.hidden=!1;const n=this.ufoElement.sighting.timeline.sourceIds,i=n.filter(f=>this.selectedSourceIds.has(f)),s=n.length<=i.length,a=i.length>0&&n.slice(n.length-i.length).every(f=>this.selectedSourceIds.has(f)),o=i.length>0&&n.slice(0,i.length).every(f=>this.selectedSourceIds.has(f));this.contextBringToFrontButton.disabled=s||a,this.contextSendToBackButton.disabled=s||o,this.contextBringToFrontButton.title=s?this.messages.onlyOneShape:a?this.messages.alreadyAtFront:"",this.contextSendToBackButton.title=s?this.messages.onlyOneShape:o?this.messages.alreadyAtBack:"",this.contextGroupButton.disabled=this.selectedSourceIds.size<2,this.contextGroupButton.title=this.contextGroupButton.disabled?this.messages.needTwoShapesToGroup:"";const l=this.ufoElement.sighting.timeline.groupMembers(this.currentSourceId)!==void 0;this.contextUngroupButton.disabled=!l,this.contextUngroupButton.title=l?"":this.messages.notGrouped,this.contextDeleteButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.title=this.contextDeleteButton.disabled?this.messages.onlyOneShape:"";const c=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId),h=this.selectedSourceIds.size===1&&c?.kind==="polygon";this.contextAddVertexButton.disabled=!h,this.contextAddVertexButton.title=h?"":this.messages.notAPolygon;const d=h&&this.contextMenuPoint?st.hitTestVertex(c,this.contextMenuPoint):void 0,u=h&&c.points.length<=Zm;this.contextDeleteVertexButton.disabled=!h||d===void 0||u,this.contextDeleteVertexButton.title=h?u?this.messages.tooFewVertices:"":this.messages.notAPolygon,document.addEventListener("click",this.handleOutsideContextMenuClick)}hideContextMenu(){this.contextMenu.hidden=!0,this.contextMenuPoint=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}handleOutsideContextMenuClick=e=>{e.composedPath().includes(this.contextMenu)||e.composedPath().includes(this.decorContextMenu)||(this.hideContextMenu(),this.hideDecorContextMenu())};showDecorContextMenu(e,t,n){this.contextMenuDecorId=n.id,this.decorContextMenu.style.left=`${e}px`,this.decorContextMenu.style.top=`${t}px`,this.decorContextMenu.hidden=!1,this.contextViewTestimonyButton.disabled=!n.sightingUrl,this.contextViewTestimonyButton.title=n.sightingUrl?"":this.messages.noWitnessRecording,this.refreshContextMasksSubmenu(n),document.addEventListener("click",this.handleOutsideContextMenuClick)}hideDecorContextMenu(){this.decorContextMenu.hidden=!0,this.contextMenuDecorId=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}refreshContextMasksSubmenu(e){this.contextMasksSubmenu.innerHTML="";for(const t of this.ufoElement.sighting.timeline.sourceIds){const n=document.createElement("label"),i=document.createElement("input");i.type="checkbox",i.checked=e.occludesSourceIds?.includes(t)??!1,i.addEventListener("change",()=>this.updateDecorOccludesShape(e.id,t,i.checked)),n.appendChild(i),n.appendChild(document.createTextNode(this.shapeLabel(t))),this.contextMasksSubmenu.appendChild(n)}}updateDecorOccludesShape(e,t,n){const i=this.ufoElement.sighting;i.decor=i.decor.map(s=>{if(s.id!==e)return s;const a=n?[...new Set([...s.occludesSourceIds??[],t])]:(s.occludesSourceIds??[]).filter(o=>o!==t);return{...s,occludesSourceIds:a.length>0?a:void 0}}),this.ufoElement.refresh()}viewWitnessTestimony(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.contextMenuDecorId);this.hideDecorContextMenu(),e?.sightingUrl&&this.importFromUrl(e.sightingUrl)}addVertexAtContextMenu(){const e=this.contextMenuPoint;if(this.hideContextMenu(),!e)return;const t=this.ufoElement.currentTime,n=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(n?.kind!=="polygon")return;const i=st.insertVertexNear(n,e);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:i}]),this.ufoElement.refresh()}deleteVertexAtContextMenu(){const e=this.contextMenuPoint;if(this.hideContextMenu(),!e)return;const t=this.ufoElement.currentTime,n=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(n?.kind!=="polygon")return;const i=st.hitTestVertex(n,e);if(i===void 0)return;const s=st.deleteVertex(n,i);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:s}]),this.ufoElement.refresh()}bringSelectedToFront(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(n=>this.selectedSourceIds.has(n)))e.bringToFront(t);this.hideContextMenu(),this.ufoElement.refresh()}sendSelectedToBack(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(n=>this.selectedSourceIds.has(n)).reverse())e.sendToBack(t);this.hideContextMenu(),this.ufoElement.refresh()}groupSelected(){this.selectedSourceIds.size<2||(this.ufoElement.sighting.timeline.group([...this.selectedSourceIds]),this.hideContextMenu(),this.ufoElement.refresh())}ungroupSelected(){this.ufoElement.sighting.timeline.ungroup(this.currentSourceId),this.selectedSourceIds=new Set([this.currentSourceId]),this.hideContextMenu(),this.ufoElement.refresh()}beginDrag(e,t,n,i,s){this.dragState={kind:e,sourceId:t,original:n,handle:s,startPointer:i},this.startDragListening()}beginCameraDrag(e){const t=this.isWitnessInsideDecor();this.cameraDragState={startPointer:e,startHeadingDeg:t?this.indoorLookYawDeg:this.numberOrUndefined(this.headingInput.value)??0,startPitchDeg:t?this.indoorLookPitchDeg:this.numberOrUndefined(this.pitchInput.value)??0,insideDecor:t},t||this.sceneElement.setCompassForced(!0),this.setCanvasCursor("panning"),this.startDragListening()}isWitnessInsideDecor(){return this.ufoElement.sighting.decor.some(e=>e.witnessSide!==void 0&&Kr(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(n=>n.witnessSide!==void 0&&Kr(n.kind)),t=e?`${e.id}:${e.witnessSide}`:void 0;t!==this.lastInhabitedKey&&(this.lastInhabitedKey=t,this.indoorLookYawDeg=0,this.indoorLookPitchDeg=0,this.sceneElement.setIndoorLook(0,0))}startDragListening(){document.addEventListener("pointermove",this.handleDragPointerMove),document.addEventListener("pointerup",this.handleDragPointerUp)}onDragPointerMove(e){if(this.referenceDragState){this.onReferenceDragPointerMove(e);return}if(this.cameraDragState){this.onCameraDragPointerMove(e);return}if(!this.dragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const n=this.ufoElement.currentTime;if(this.dragState.kind==="move"){const{sources:i,startPointer:s}=this.dragState,a=t.x-s.x,o=t.y-s.y,l=i.map(({sourceId:c,original:h})=>({sourceId:c,shape:{...h,bounds:{...h.bounds,x:h.bounds.x+a,y:h.bounds.y+o}}}));this.commitShapes(n,l)}else if(this.dragState.kind==="group-resize"){const{group:i,handle:s}=this.dragState;this.commitShapes(n,i.resize(s,t))}else if(this.dragState.kind==="group-rotate"){const{group:i,startPointer:s}=this.dragState;this.commitShapes(n,i.rotate(t,s))}else if(this.dragState.kind==="vertex"){const{sourceId:i,original:s,vertexIndex:a}=this.dragState,o=st.moveVertex(s,a,t);this.commitShapes(n,[{sourceId:i,shape:o}])}else{const{kind:i,sourceId:s,original:a,handle:o}=this.dragState,l=i==="resize"?st.resizeShape(a,o,t):st.rotateShape(a,t);this.commitShapes(n,[{sourceId:s,shape:l}])}this.ufoElement.refresh()}onCameraDragPointerMove(e){if(!this.cameraDragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const{startPointer:n,startHeadingDeg:i,startPitchDeg:s,insideDecor:a}=this.cameraDragState,o=i+(t.x-n.x)*zm,l=Math.max(-90,Math.min(90,s-(t.y-n.y)*zm));if(a){this.indoorLookYawDeg=o,this.indoorLookPitchDeg=l,this.sceneElement.setIndoorLook(o,l),this.ufoElement.refresh();return}this.headingInput.value=String(this.rounded(o)),this.pitchInput.value=String(this.rounded(l)),this.updateObserver()}endDrag(){if(this.referenceDragState){this.endReferenceDrag();return}!this.dragState&&!this.cameraDragState||(this.cameraDragState&&!this.cameraDragState.insideDecor&&this.sceneElement.setCompassForced(!1),this.dragState=void 0,this.cameraDragState=void 0,this.setCanvasCursor(this.hoverCursor),document.removeEventListener("pointermove",this.handleDragPointerMove),document.removeEventListener("pointerup",this.handleDragPointerUp))}nudgeBounds(e,t){const n={...e};if(t.shiftKey){switch(t.key){case"ArrowLeft":n.width=Math.max(Es,n.width-vs);break;case"ArrowRight":n.width+=vs;break;case"ArrowUp":n.height=Math.max(Es,n.height-vs);break;case"ArrowDown":n.height+=vs;break}n.x-=(n.width-e.width)/2,n.y-=(n.height-e.height)/2}else switch(t.key){case"ArrowLeft":n.x-=vs;break;case"ArrowRight":n.x+=vs;break;case"ArrowUp":n.y-=vs;break;case"ArrowDown":n.y+=vs;break}return n}moveOrResizeSelectedShapes(e){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.currentTime,n=this.selectedMembers();if(n.length!==0){if(e.preventDefault(),n.length===1){const{sourceId:i,shape:s}=n[0];this.commitShapes(t,[{sourceId:i,shape:{...s,bounds:this.nudgeBounds(s.bounds,e)}}])}else{const i=new kc(n),s=this.nudgeBounds(i.bounds(),e);this.commitShapes(t,i.scaleTo(s))}this.ufoElement.refresh()}}updateHoverCursor(e){this.isRecording||this.dragState||this.cameraDragState||(this.hoverCursor=this.hoverCursorAt(e),this.setCanvasCursor(this.hoverCursor))}hoverCursorAt(e){const t=this.canvasPointFromEvent(e);if(!t)return;const n=this.canvasMode(),i=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,a=this.ufoElement.playbackState!=="playing";if(n==="picture")return a?"pan":void 0;const o=n==="shape";if(a&&o)if(this.selectedSourceIds.size>1){const l=st.hitTestHandle({bounds:new kc(this.selectedMembers()).bounds(),angle:0},t);if(l)return this.cursorForHandle(l,0)}else{const l=i.getInterpolatedShapeAt(s,this.currentSourceId);if(l?.kind==="polygon"&&st.hitTestVertex(l,t)!==void 0)return"vertex";const c=l&&st.hitTestHandle(l,t);if(l&&c)return this.cursorForHandle(c,l.angle)}return i.hitTest(s,t.x,t.y)?a&&o?"move":"select":this.pickDecorAt(e)!==void 0?"select":a?"pan":void 0}cursorForHandle(e,t){return e==="rotate"?"rotate":`resize-${st.resizeAxisFor(e,t)}`}setCanvasCursor(e){const t=this.ufoElement.canvasElement;e?t.dataset.cursor=e:delete t.dataset.cursor}onPointerMove(e){if(!this.isRecording){this.updateHoverCursor(e);return}const t=this.ufoElement.canvasElement,n=t.getBoundingClientRect(),i=e.clientX-n.left,s=e.clientY-n.top;this.recorder?.onPointerMove(i,s),this.ufoElement.renderer.clear(t.width,t.height),this.ufoElement.renderer.paintShape($m(this.buildPrototype({x:0,y:0,width:Vr.width,height:Vr.height}),i,s))}canvasPointFromEvent(e){const t=this.ufoElement.canvasElement,n=t.getBoundingClientRect();if(!(n.width===0||n.height===0))return{x:(e.clientX-n.left)/n.width*t.width,y:(e.clientY-n.top)/n.height*t.height}}}const XA={stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed"},Wm="rr0-sighting-editor",Vm="rr0-ufo-recorder";class qA extends Tt{}function YA(){xc(),customElements.get(Wm)||customElements.define(Wm,Tt),customElements.get(Vm)||customElements.define(Vm,qA)}YA();export{Pn as $,si as A,ut as B,le as C,cw as D,ki as E,sI as F,pt as G,St as H,QA as I,JA as J,qe as K,To as L,nI as M,Oo as N,xt as O,ow as P,Oi as Q,po as R,oo as S,$A as T,eI as U,Re as V,Cg as W,tI as X,to as Y,cn as Z,jn as _,ZA as a,jA as a0,ur as a1,Dg as a2,iI as a3,Db as a4,tc as a5,Kd as a6,oc as a7,rn as a8,Ng as a9,Qu as aa,ef as ab,Qe as ac,Ps as ad,Eo as ae,di as af,is as ag,KA as b,Cn as c,oI as d,ic as e,Rn as f,aI as g,Ve as h,P as i,Dp as j,rI as k,lI as l,Eb as m,Qs as n,zc as o,ad as p,Cy as q,wt as r,Ds as s,Kt as t,yd as u,Sn as v,ju as w,ss as x,Nb as y,Gb as z};
7545
+ `);let s=xi.cache.get(i);return s||(s=Promise.all(n.map(a=>xi.load(a.url))).then(a=>a.reduce((o,l)=>xi.concat(o,l))),xi.cache.set(i,s)),s}static parse(e){const t=e.byteLength/(4*Float32Array.BYTES_PER_ELEMENT),n=t*Float32Array.BYTES_PER_ELEMENT;return{count:t,ra:new Float32Array(e,0*n,t),dec:new Float32Array(e,1*n,t),mag:new Float32Array(e,2*n,t),ci:new Float32Array(e,3*n,t)}}static concat(e,t){const n=(i,s)=>{const a=new Float32Array(i.length+s.length);return a.set(i,0),a.set(s,i.length),a};return{count:e.count+t.count,ra:n(e.ra,t.ra),dec:n(e.dec,t.dec),mag:n(e.mag,t.mag),ci:n(e.ci,t.ci)}}}const kT=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,NT=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,OT=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,FT=20,UT=1;class BT{context;buffers=new Map;ambientSource;ambientGain;ambientKey="none";ambientToken=0;ambientVolume=0;windSource;windGain;windActive=!1;windToken=0;windVolume=0;paused=!0;requested={type:"none",intensity:0,windSpeed:0};resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("WeatherAudio: Web Audio unavailable, weather sounds disabled:",e);return}}this.context.state==="suspended"&&this.context.resume()}setAmbient(e,t,n){if(this.requested={type:e,intensity:t,windSpeed:n},!this.context)return;this.paused&&(e="none",t=0,n=0);const i=e==="rain"||e==="hail"?e:"none";if(this.ambientVolume=i==="hail"?Math.min(1,t*1.3+.2):i==="rain"?t:0,i!==this.ambientKey){this.ambientKey=i;const a=++this.ambientToken;this.stopSource(this.ambientSource,this.ambientGain),this.ambientSource=void 0,this.ambientGain=void 0,i!=="none"&&this.startLoop(kT,this.ambientVolume).then(o=>this.applyIfCurrent(o,a,()=>this.ambientToken,l=>{this.ambientSource=l?.source,this.ambientGain=l?.gain,l&&(l.gain.gain.value=this.ambientVolume)}))}else this.ambientGain&&(this.ambientGain.gain.value=this.ambientVolume);this.windVolume=Math.min(n/FT,1);const s=n>UT;if(s!==this.windActive){this.windActive=s;const a=++this.windToken;this.stopSource(this.windSource,this.windGain),this.windSource=void 0,this.windGain=void 0,s&&this.startLoop(NT,this.windVolume).then(o=>this.applyIfCurrent(o,a,()=>this.windToken,l=>{this.windSource=l?.source,this.windGain=l?.gain,l&&(l.gain.gain.value=this.windVolume)}))}else this.windGain&&(this.windGain.gain.value=this.windVolume)}setPaused(e){if(e===this.paused)return;this.paused=e;const{type:t,intensity:n,windSpeed:i}=this.requested;this.setAmbient(t,n,i)}playThunder(){!this.context||this.paused||this.playOneShot(OT,.9)}dispose(){this.ambientToken++,this.windToken++,this.stopSource(this.ambientSource,this.ambientGain),this.stopSource(this.windSource,this.windGain),this.ambientSource=void 0,this.ambientGain=void 0,this.windSource=void 0,this.windGain=void 0,this.context?.close(),this.context=void 0,this.buffers.clear()}applyIfCurrent(e,t,n,i){if(t!==n()){e?.source.stop();return}i(e)}async startLoop(e,t){const n=this.context;if(n)try{const i=await this.getBuffer(e),s=n.createBufferSource();s.buffer=i,s.loop=!0;const a=n.createGain();return a.gain.value=t,s.connect(a).connect(n.destination),s.start(),{source:s,gain:a}}catch(i){console.warn("Weather ambient sound failed to load, staying silent:",i);return}}async playOneShot(e,t){const n=this.context;if(n)try{const i=await this.getBuffer(e),s=n.createBufferSource();s.buffer=i;const a=n.createGain();a.gain.value=t,s.connect(a).connect(n.destination),s.start()}catch(i){console.warn("Thunder sound failed to load:",i)}}async getBuffer(e){const t=this.context;if(!t)throw new Error("WeatherAudio: AudioContext not ready — resume() must be called first");let n=this.buffers.get(e);return n||(n=fetch(e).then(i=>{if(!i.ok)throw new Error(`Audio fetch failed (${i.status}): ${e}`);return i.arrayBuffer()}).then(i=>t.decodeAudioData(i)),this.buffers.set(e,n)),n}stopSource(e,t){try{e?.stop()}catch{}e?.disconnect(),t?.disconnect()}}class Ki{constructor(e){this.elements=e;const{eccentricity:t,perihelionAu:n}=e,[i,s]=this.perifocalAxes(),a=Math.sqrt(Ki.SUN_GM_AU3_PER_DAY2*(1+t)/n);this.perihelionPosition=this.scale(i,n),this.perihelionVelocity=this.scale(s,a),this.inverseSemiMajorAxis=(1-t)/n}static SUN_GM_AU3_PER_DAY2=.0002959122082855911;static MAX_ITERATIONS=200;perihelionPosition;perihelionVelocity;inverseSemiMajorAxis;positionAt(e){const t=e-this.elements.perihelionJd,n=this.universalAnomaly(t),i=this.inverseSemiMajorAxis*n*n,s=this.elements.perihelionAu,a=1-n*n/s*Ki.stumpffC(i),o=t-n*n*n/Math.sqrt(Ki.SUN_GM_AU3_PER_DAY2)*Ki.stumpffS(i);return{x:a*this.perihelionPosition.x+o*this.perihelionVelocity.x,y:a*this.perihelionPosition.y+o*this.perihelionVelocity.y,z:a*this.perihelionPosition.z+o*this.perihelionVelocity.z}}heliocentricDistanceAt(e){const t=this.positionAt(e);return Math.hypot(t.x,t.y,t.z)}universalAnomaly(e){if(e===0)return 0;const t=Math.sign(e),n=Math.sqrt(Ki.SUN_GM_AU3_PER_DAY2)*Math.abs(e),i=o=>{const l=this.inverseSemiMajorAxis*o*o,c=this.elements.perihelionAu;return(1-this.inverseSemiMajorAxis*c)*o*o*o*Ki.stumpffS(l)+c*o};let s=Math.max(1,n/this.elements.perihelionAu);for(;i(s)<n;)s*=2;let a=0;for(let o=0;o<Ki.MAX_ITERATIONS&&s-a>1e-13*Math.max(1,s);o++){const l=(a+s)/2;i(l)<n?a=l:s=l}return t*(a+s)/2}perifocalAxes(){const e=this.elements.ascendingNodeDeg*Math.PI/180,t=this.elements.argumentOfPerihelionDeg*Math.PI/180,n=this.elements.inclinationDeg*Math.PI/180,i=Math.cos(e),s=Math.sin(e),a=Math.cos(t),o=Math.sin(t),l=Math.cos(n),c=Math.sin(n);return[{x:i*a-s*o*l,y:s*a+i*o*l,z:o*c},{x:-i*o-s*a*l,y:-s*o+i*a*l,z:a*c}]}scale(e,t){return{x:e.x*t,y:e.y*t,z:e.z*t}}static stumpffC(e){if(Math.abs(e)<1e-6)return 1/2-e/24+e*e/720;if(e>0)return(1-Math.cos(Math.sqrt(e)))/e;const t=Math.sqrt(-e);return(Math.cosh(t)-1)/-e}static stumpffS(e){if(Math.abs(e)<1e-6)return 1/6-e/120+e*e/5040;if(e>0){const n=Math.sqrt(e);return(n-Math.sin(n))/(n*n*n)}const t=Math.sqrt(-e);return(Math.sinh(t)-t)/(t*t*t)}}const Rv=[{id:"halley-1910",designation:"1P/Halley",name:{en:"Halley's Comet",fr:"comète de Halley"},orbit:{eccentricity:.9672960498922706,perihelionAu:.5872100477652511,inclinationDeg:162.218798367122,ascendingNodeDeg:58.56208298700436,argumentOfPerihelionDeg:111.7366940639061,perihelionJd:2.4187816784171113e6},peakMagnitude:0,peakOn:"1910-05-20",absoluteMagnitude:4.72,activityExponent:4,tailLengthDeg:100,tailLengthAu:.1638,note:"Passed 0.15 au from Earth on 20 May 1910, and the Earth crossed the outer tail the day before — the apparition that produced a genuine public panic."},{id:"brooks-1911",designation:"C/1911 O1",name:{en:"Comet Brooks",fr:"comète Brooks"},orbit:{eccentricity:.9876404970138669,perihelionAu:.4898172916113738,inclinationDeg:33.34043866978714,ascendingNodeDeg:293.7022074981857,argumentOfPerihelionDeg:153.5578007321686,perihelionJd:2.4193378856140426e6},peakMagnitude:2,peakOn:"1911-10-25",absoluteMagnitude:5.59,activityExponent:4},{id:"skjellerup-maristany-1927",designation:"C/1927 X1",name:{en:"Comet Skjellerup-Maristany",fr:"comète Skjellerup-Maristany"},orbit:{eccentricity:.999839726885059,perihelionAu:.1761569619628186,inclinationDeg:85.1125991950808,ascendingNodeDeg:78.24360172472711,argumentOfPerihelionDeg:47.15877857390136,perihelionJd:2.4252326808989984e6},peakMagnitude:-6,peakOn:"1927-12-15",absoluteMagnitude:1.19,activityExponent:4,note:"One of the few comets of the century seen in full daylight."},{id:"de-kock-paraskevopoulos-1941",designation:"C/1941 B2",name:{en:"Comet de Kock-Paraskevopoulos",fr:"comète de Kock-Paraskevopoulos"},orbit:{eccentricity:.9991026715181549,perihelionAu:.7900329662827822,inclinationDeg:168.2039226531089,ascendingNodeDeg:43.10609347214336,argumentOfPerihelionDeg:268.6990344196369,perihelionJd:2430022157765061e-9},peakMagnitude:2,peakOn:"1941-02-05",absoluteMagnitude:5.01,activityExponent:4},{id:"southern-1947",designation:"C/1947 X1",name:{en:"the Southern Comet",fr:"comète australe"},orbit:{eccentricity:.9998424430916737,perihelionAu:.1100045955093761,inclinationDeg:138.5113919632757,ascendingNodeDeg:337.3114969669252,argumentOfPerihelionDeg:196.1820121395961,perihelionJd:2.4325220864727003e6},peakMagnitude:-3,peakOn:"1947-12-08",absoluteMagnitude:3.01,activityExponent:4,note:"A bright southern-hemisphere comet of December 1947, the month the American sighting wave of that year was still being argued over."},{id:"eclipse-1948",designation:"C/1948 V1",name:{en:"the Eclipse Comet",fr:"comète de l'éclipse"},orbit:{eccentricity:.9999130678247334,perihelionAu:.1354437057263306,inclinationDeg:23.11668597152911,ascendingNodeDeg:211.0454985994762,argumentOfPerihelionDeg:107.2474157073104,perihelionJd:2.4328519265329437e6},peakMagnitude:-2,peakOn:"1948-11-01",absoluteMagnitude:4.79,activityExponent:4,note:"Found during the total solar eclipse of 1 November 1948, which is how a comet that bright had gone unnoticed: it had been hidden in the Sun's glare."},{id:"arend-roland-1957",designation:"C/1956 R1",name:{en:"Comet Arend-Roland",fr:"comète Arend-Roland"},orbit:{eccentricity:1.0002570255357,perihelionAu:.3160532361485914,inclinationDeg:119.9440863251822,ascendingNodeDeg:215.8548157717755,argumentOfPerihelionDeg:308.775920364167,perihelionJd:2.4359365327396123e6},peakMagnitude:.5,peakOn:"1957-04-25",absoluteMagnitude:3.96,activityExponent:4,note:"Showed a spike pointing back TOWARD the Sun in late April 1957 — a real anti-tail, and much reported at the time."},{id:"mrkos-1957",designation:"C/1957 P1",name:{en:"Comet Mrkos",fr:"comète Mrkos"},orbit:{eccentricity:.9993521583504134,perihelionAu:.3549238508212375,inclinationDeg:93.9433042053929,ascendingNodeDeg:68.32441518619923,argumentOfPerihelionDeg:40.31823675802871,perihelionJd:243605193752228e-8},peakMagnitude:1,peakOn:"1957-08-05",absoluteMagnitude:5.07,activityExponent:4,note:"The second bright naked-eye comet of 1957, four months after Arend-Roland."},{id:"seki-lines-1962",designation:"C/1962 C1",name:{en:"Comet Seki-Lines",fr:"comète Seki-Lines"},orbit:{eccentricity:1.000003791331562,perihelionAu:.03139689112215131,inclinationDeg:65.01487186102287,ascendingNodeDeg:304.6776602796538,argumentOfPerihelionDeg:11.47295326312573,perihelionJd:2437756163010178e-9},peakMagnitude:-2.5,peakOn:"1962-04-01",absoluteMagnitude:9.3,activityExponent:4},{id:"ikeya-seki-1965",designation:"C/1965 S1",name:{en:"Comet Ikeya-Seki",fr:"comète Ikeya-Seki"},orbit:{eccentricity:.9999141178248997,perihelionAu:.007785966366889336,inclinationDeg:141.8642315267051,ascendingNodeDeg:346.9951764632611,argumentOfPerihelionDeg:69.04909813996062,perihelionJd:2.4390546837018197e6},peakMagnitude:-10,peakOn:"1965-10-21",alsoRecordedMagnitude:2,alsoRecordedOn:"1965-10-30",absoluteMagnitude:5.26,activityExponent:4.002,tailLengthDeg:25,tailLengthAu:.5048,note:"A sungrazer that passed 450 000 km above the Sun's surface and was seen beside it in broad daylight — the brightest comet of the twentieth century. It then stood in the dawn sky for a fortnight with a tail some 25 degrees long, which is the second magnitude recorded here."},{id:"bennett-1970",designation:"C/1969 Y1",name:{en:"Comet Bennett",fr:"comète Bennett"},orbit:{eccentricity:.9962979048768408,perihelionAu:.5376209981502136,inclinationDeg:90.03975717147327,ascendingNodeDeg:224.6576652531314,argumentOfPerihelionDeg:354.1494209173161,perihelionJd:2.4406655455270996e6},peakMagnitude:0,peakOn:"1970-03-26",absoluteMagnitude:3.36,activityExponent:4},{id:"white-ortiz-bolelli-1970",designation:"C/1970 K1",name:{en:"Comet White-Ortiz-Bolelli",fr:"comète White-Ortiz-Bolelli"},orbit:{eccentricity:.9999488875801225,perihelionAu:.00884411465256722,inclinationDeg:138.9520738221631,ascendingNodeDeg:336.8194095816687,argumentOfPerihelionDeg:61.10224765396615,perihelionJd:2.4407209807728203e6},peakMagnitude:1,peakOn:"1970-05-22",absoluteMagnitude:4.35,activityExponent:4},{id:"kohoutek-1973",designation:"C/1973 E1",name:{en:"Comet Kohoutek",fr:"comète Kohoutek"},orbit:{eccentricity:1.000007152175185,perihelionAu:.1424250377812859,inclinationDeg:14.30414984159355,ascendingNodeDeg:258.4893339663974,argumentOfPerihelionDeg:37.79772760699667,perihelionJd:2442044930687027e-9},peakMagnitude:0,peakOn:"1974-01-05",absoluteMagnitude:4.89,activityExponent:4,note:"Announced in advance as the comet of the century and remembered for disappointing: it was an ordinary naked-eye object, not the spectacle the press had promised."},{id:"west-1976",designation:"C/1975 V1",name:{en:"Comet West",fr:"comète West"},orbit:{eccentricity:1.000017859625611,perihelionAu:.1966006188461085,inclinationDeg:43.07319920579427,ascendingNodeDeg:118.9189245655447,argumentOfPerihelionDeg:358.4315101259072,perihelionJd:2442833721841768e-9},peakMagnitude:-3,peakOn:"1976-02-25",absoluteMagnitude:4.41,activityExponent:4,tailLengthDeg:30,tailLengthAu:.4325,note:"Broke into four pieces at perihelion. Barely reported at the time — the press had been burned by Kohoutek two years earlier."},{id:"iras-araki-alcock-1983",designation:"C/1983 H1",name:{en:"Comet IRAS-Araki-Alcock",fr:"comète IRAS-Araki-Alcock"},orbit:{eccentricity:.9898409731606003,perihelionAu:.9913412593828502,inclinationDeg:73.25000846947029,ascendingNodeDeg:49.10235754476374,argumentOfPerihelionDeg:192.8506176754439,perihelionJd:2.4454757545235856e6},peakMagnitude:1.7,peakOn:"1983-05-11",absoluteMagnitude:9.04,activityExponent:4,note:"Passed 0.031 au from Earth on 11 May 1983, one of the closest cometary approaches on record: it crossed a quarter of the sky in a night, which no other comet in this list did."},{id:"halley-1986",designation:"1P/Halley",name:{en:"Halley's Comet",fr:"comète de Halley"},orbit:{eccentricity:.9672792271749998,perihelionAu:.5871034488173393,inclinationDeg:162.2422242700916,ascendingNodeDeg:58.85993640671803,argumentOfPerihelionDeg:111.8655480539208,perihelionJd:2.4464709589610207e6},peakMagnitude:2.1,peakOn:"1986-03-10",absoluteMagnitude:2.71,activityExponent:4,note:"The worst-placed return in two thousand years — famous, expected, and for most observers a faint smudge."},{id:"hyakutake-1996",designation:"C/1996 B2",name:{en:"Comet Hyakutake",fr:"comète Hyakutake"},orbit:{eccentricity:.9997295133739305,perihelionAu:.2302272039470452,inclinationDeg:124.923592343765,ascendingNodeDeg:188.0454295899424,argumentOfPerihelionDeg:130.1724036582639,perihelionJd:2.4502048946148166e6},peakMagnitude:0,peakOn:"1996-03-25",absoluteMagnitude:4.75,activityExponent:4,tailLengthDeg:80,tailLengthAu:1,note:"Passed 0.10 au from Earth in March 1996, five weeks BEFORE perihelion, with a tail measured at some 80 degrees — the longest of the modern era."},{id:"hale-bopp-1997",designation:"C/1995 O1",name:{en:"Comet Hale-Bopp",fr:"comète Hale-Bopp"},orbit:{eccentricity:.9951314746156615,perihelionAu:.9141695067003724,inclinationDeg:89.43017155012492,ascendingNodeDeg:282.470602866853,argumentOfPerihelionDeg:130.5872524854533,perihelionJd:2450539633099368e-9},peakMagnitude:-.8,peakOn:"1997-04-01",absoluteMagnitude:-1.06,activityExponent:4,tailLengthDeg:20,tailLengthAu:.9938,note:"Visible to the naked eye for about eighteen months, longer than any comet on record."},{id:"mcnaught-2007",designation:"C/2006 P1",name:{en:"Comet McNaught",fr:"comète McNaught"},orbit:{eccentricity:1.00001811603225,perihelionAu:.1707325614080681,inclinationDeg:77.83726446452654,ascendingNodeDeg:267.4149080498975,argumentOfPerihelionDeg:155.9756130642756,perihelionJd:2454113298753579e-9},peakMagnitude:-5.5,peakOn:"2007-01-13",absoluteMagnitude:2.53,activityExponent:4,tailLengthDeg:35,tailLengthAu:.5009,note:"The brightest comet since Ikeya-Seki, seen in daylight beside the Sun in January 2007."},{id:"lovejoy-2011",designation:"C/2011 W3",name:{en:"Comet Lovejoy",fr:"comète Lovejoy"},orbit:{eccentricity:.999915056276912,perihelionAu:.005553783989325053,inclinationDeg:134.3558712062691,ascendingNodeDeg:326.3693517957772,argumentOfPerihelionDeg:53.50991655176601,perihelionJd:2455911511809431e-9},peakMagnitude:-3,peakOn:"2011-12-16",alsoRecordedMagnitude:1.5,alsoRecordedOn:"2011-12-22",absoluteMagnitude:3.51,activityExponent:1.194,note:"A sungrazer that was expected to be destroyed at perihelion and came out the other side, to stand in the southern dawn sky for the rest of December — which is the second magnitude recorded here."},{id:"panstarrs-2013",designation:"C/2011 L4",name:{en:"Comet PANSTARRS",fr:"comète PANSTARRS"},orbit:{eccentricity:1.000032542889696,perihelionAu:.301544229714915,inclinationDeg:84.2081978367921,ascendingNodeDeg:65.66588626213694,argumentOfPerihelionDeg:333.6516444379993,perihelionJd:2456361669960698e-9},peakMagnitude:1,peakOn:"2013-03-10",absoluteMagnitude:5.98,activityExponent:4},{id:"neowise-2020",designation:"C/2020 F3",name:{en:"Comet NEOWISE",fr:"comète NEOWISE"},orbit:{eccentricity:.9991782081129224,perihelionAu:.2946512466331692,inclinationDeg:128.9375043020912,ascendingNodeDeg:61.01042991771634,argumentOfPerihelionDeg:37.2786526292898,perihelionJd:2.4590341788972816e6},peakMagnitude:.9,peakOn:"2020-07-08",absoluteMagnitude:5.79,activityExponent:4,tailLengthDeg:10,tailLengthAu:.1808,note:"The first comet since Hale-Bopp that ordinary observers in the northern hemisphere saw without being told where to look."},{id:"tsuchinshan-atlas-2024",designation:"C/2023 A3",name:{en:"Comet Tsuchinshan-ATLAS",fr:"comète Tsuchinshan-ATLAS"},orbit:{eccentricity:1.000020192843226,perihelionAu:.3914228969475176,inclinationDeg:139.1105462619479,ascendingNodeDeg:21.55945689078845,argumentOfPerihelionDeg:308.4913086299446,perihelionJd:2460581242087108e-9},peakMagnitude:0,peakOn:"2024-10-14",absoluteMagnitude:3.97,activityExponent:4,tailLengthDeg:20,tailLengthAu:.1902,note:"Briefly reported far brighter around 9 October 2024, when it stood almost between the observer and the Sun and forward-scattered the light through its own dust — a geometry this catalog's brightness model does not attempt, so what is stored is the ordinary evening-sky peak a few days later."}];class ql{static WINDOW_DAYS=200;static TWILIGHT_ELONGATION_DEG=15;static LIGHT_SPEED_AU_PER_DAY=173.144632674;static orbits=new Map;static aroundDate(e){const t=this.julianDayOf(e);return Rv.filter(n=>Math.abs(t-n.orbit.perihelionJd)<=this.WINDOW_DAYS)}static brightestAt(e,t){return this.aroundDate(e).map(n=>this.appearanceOf(n,e,t)).sort((n,i)=>n.magnitude-i.magnitude)[0]}static appearanceOf(e,t,n){const i=Xt(t),s=this.earthPositionAt(i),a=this.apparentPositionOf(e,2451545+i.tt,s),o=this.subtract(a,s),l=this.length(a),c=this.length(o),h=this.tailEndAt(e,a,s,l,i,t,n),d=this.horizontalOf(o,i,t,n);return{apparition:e,position:d,...h,heliocentricDistanceAu:l,earthDistanceAu:c,elongationDeg:this.angleBetween(o,this.subtract({x:0,y:0,z:0},s)),magnitude:this.magnitudeAt(e,l,c)}}static magnitudeAt(e,t,n){const i=e.absoluteMagnitude+5*Math.log10(n)+2.5*e.activityExponent*Math.log10(t);return Math.max(i,e.peakMagnitude)}static tailEndAt(e,t,n,i,s,a,o){if(e.tailLengthAu===void 0)return{};const l=1+e.tailLengthAu/i,c=this.subtract({x:t.x*l,y:t.y*l,z:t.z*l},n),h=this.subtract(t,n);return{tailEnd:this.horizontalOf(c,s,a,o),tailLengthDeg:this.angleBetween(h,c)}}static apparentPositionOf(e,t,n){const i=this.orbitOf(e);let s=i.positionAt(t);for(let a=0;a<2;a++){const o=this.length(this.subtract(s,n))/this.LIGHT_SPEED_AU_PER_DAY;s=i.positionAt(t-o)}return s}static horizontalOf(e,t,n,i){const s=Vl(XE(),new Mt(e.x,e.y,e.z,t)),a=Vl(qE(t),s),o=SE(t,new uf(i.lat,i.lng,i.elevationM)),l=new Mt(a.x-o.x,a.y-o.y,a.z-o.z,t),c=mv(l);return Rc(c.ra,c.dec,n,i)}static earthPositionAt(e){return Vl(VE(),Rs(Me.Earth,e))}static julianDayOf(e){return 2451545+Xt(e).tt}static orbitOf(e){const t=this.orbits.get(e.id);if(t)return t;const n=new Ki(e.orbit);return this.orbits.set(e.id,n),n}static subtract(e,t){return{x:e.x-t.x,y:e.y-t.y,z:e.z-t.z}}static length(e){return Math.hypot(e.x,e.y,e.z)}static angleBetween(e,t){const n=(e.x*t.x+e.y*t.y+e.z*t.z)/(this.length(e)*this.length(t)||1);return Math.acos(Math.min(1,Math.max(-1,n)))*180/Math.PI}}const zT=[{id:"quadrantids",code:"QUA",name:{en:"Quadrantids",fr:"Quadrantides"},radiantRaHours:15.33,radiantDecDeg:49.7,start:{month:12,day:28},peak:{month:1,day:3},end:{month:1,day:12},peakZhr:110,velocityKmS:41,populationIndex:2.1},{id:"lyrids",code:"LYR",name:{en:"April Lyrids",fr:"Lyrides d'avril"},radiantRaHours:18.13,radiantDecDeg:33.3,start:{month:4,day:16},peak:{month:4,day:22},end:{month:4,day:25},peakZhr:18,velocityKmS:49,populationIndex:2.1},{id:"eta-aquariids",code:"ETA",name:{en:"eta Aquariids",fr:"Êta Aquarides"},radiantRaHours:22.53,radiantDecDeg:-1,start:{month:4,day:19},peak:{month:5,day:6},end:{month:5,day:28},peakZhr:50,velocityKmS:66,populationIndex:2.4},{id:"alpha-capricornids",code:"CAP",name:{en:"alpha Capricornids",fr:"Alpha Capricornides"},radiantRaHours:20.47,radiantDecDeg:-9.2,start:{month:7,day:3},peak:{month:7,day:30},end:{month:8,day:15},peakZhr:5,velocityKmS:23,populationIndex:2.5},{id:"southern-delta-aquariids",code:"SDA",name:{en:"Southern delta Aquariids",fr:"Delta Aquarides du Sud"},radiantRaHours:22.67,radiantDecDeg:-16.4,start:{month:7,day:12},peak:{month:7,day:30},end:{month:8,day:23},peakZhr:25,velocityKmS:41,populationIndex:3.2},{id:"perseids",code:"PER",name:{en:"Perseids",fr:"Perséides"},radiantRaHours:3.22,radiantDecDeg:58,start:{month:7,day:17},peak:{month:8,day:12},end:{month:8,day:24},peakZhr:100,velocityKmS:59,populationIndex:2.2},{id:"southern-taurids",code:"STA",name:{en:"Southern Taurids",fr:"Taurides du Sud"},radiantRaHours:3.47,radiantDecDeg:13,start:{month:9,day:10},peak:{month:10,day:10},end:{month:11,day:20},peakZhr:5,velocityKmS:27,populationIndex:2.3},{id:"draconids",code:"DRA",name:{en:"October Draconids",fr:"Draconides d'octobre"},radiantRaHours:17.47,radiantDecDeg:54,start:{month:10,day:6},peak:{month:10,day:8},end:{month:10,day:10},peakZhr:10,velocityKmS:20,populationIndex:2.6},{id:"orionids",code:"ORI",name:{en:"Orionids",fr:"Orionides"},radiantRaHours:6.35,radiantDecDeg:15.6,start:{month:10,day:2},peak:{month:10,day:21},end:{month:11,day:7},peakZhr:20,velocityKmS:66,populationIndex:2.5},{id:"northern-taurids",code:"NTA",name:{en:"Northern Taurids",fr:"Taurides du Nord"},radiantRaHours:3.87,radiantDecDeg:22,start:{month:10,day:20},peak:{month:11,day:12},end:{month:12,day:10},peakZhr:5,velocityKmS:29,populationIndex:2.3},{id:"leonids",code:"LEO",name:{en:"Leonids",fr:"Léonides"},radiantRaHours:10.13,radiantDecDeg:21.6,start:{month:11,day:6},peak:{month:11,day:17},end:{month:11,day:30},peakZhr:15,velocityKmS:71,populationIndex:2.5},{id:"geminids",code:"GEM",name:{en:"Geminids",fr:"Géminides"},radiantRaHours:7.47,radiantDecDeg:32.3,start:{month:12,day:4},peak:{month:12,day:14},end:{month:12,day:17},peakZhr:150,velocityKmS:35,populationIndex:2.6},{id:"ursids",code:"URS",name:{en:"Ursids",fr:"Ursides"},radiantRaHours:14.47,radiantDecDeg:75.3,start:{month:12,day:17},peak:{month:12,day:22},end:{month:12,day:26},peakZhr:10,velocityKmS:33,populationIndex:3}],xo=6.5;class da{static activeAt(e){return zT.flatMap(t=>{const n=this.nearness(t,e);return n<=0?[]:[{shower:t,zhr:t.peakZhr*n,nearness:n}]})}static nearness(e,t){const n=this.dayOfYear(t),i=this.dayOfYear(this.asDate(e.start)),s=this.dayOfYear(this.asDate(e.peak)),a=this.dayOfYear(this.asDate(e.end)),o=this.wrappedDelta(n,s),l=this.wrappedDelta(s,i),c=this.wrappedDelta(a,s);return o<0?o<-l?0:1+o/l:o>0?o>c?0:1-o/c:1}static observedRatePerHour(e,t,n,i=xo){if(t<=0)return 0;const s=xo-i;return e*Math.sin(t*Math.PI/180)/Math.pow(n,s)}static radiantPosition(e,t,n){return Rc(e.radiantRaHours,e.radiantDecDeg,t,n)}static dayOfYear(e){const t=Date.UTC(e.getUTCFullYear(),0,1);return Math.floor((Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())-t)/864e5)+1}static asDate(e){return new Date(Date.UTC(2001,e.month-1,e.day))}static wrappedDelta(e,t){const n=e-t;return n>182?n-365:n<-182?n+365:n}}class Dt{static QUIET_RATE_PER_HOUR=2;static APEX_RATE_PER_HOUR=8;static POPULATION_INDEX=3;static apexPosition(e,t){const n=Xt(e),i=new hf(0,xE(e).elon-90,1),s=Vl(YE(n),pv(i,n)),a=mv(s);return Rc(a.ra,a.dec,e,t)}static observedRatePerHour(e,t=xo){const n=Dt.APEX_RATE_PER_HOUR*Math.max(0,Math.sin(e*Math.PI/180)),i=xo-t;return(Dt.QUIET_RATE_PER_HOUR+n)/Math.pow(Dt.POPULATION_INDEX,i)}static schedule(e){const t=new yv(e.seed^1542469173);return rr.schedule(e).map(n=>{const i=Dt.toCartesian({altitudeDeg:Math.asin(t.next())*180/Math.PI,azimuthDeg:t.between(0,360)}),s=n.fromRadiantDeg*Math.PI/180,a=Dt.turnAround(i,t.between(0,360)),o={x:i.x*Math.cos(s)+a.x*Math.sin(s),y:i.y*Math.cos(s)+a.y*Math.sin(s),z:i.z*Math.cos(s)+a.z*Math.sin(s)};return{...n,radiant:Dt.toHorizontal(o),bearingDeg:Dt.bearingFrom(o,i)}})}static turnAround(e,t){const[n,i]=Dt.basisAround(e),s=t*Math.PI/180;return{x:n.x*Math.cos(s)+i.x*Math.sin(s),y:n.y*Math.cos(s)+i.y*Math.sin(s),z:n.z*Math.cos(s)+i.z*Math.sin(s)}}static bearingFrom(e,t){const[n,i]=Dt.basisAround(e),s=e.x*t.x+e.y*t.y+e.z*t.z,a=Dt.normalise({x:t.x-e.x*s,y:t.y-e.y*s,z:t.z-e.z*s});return(Math.atan2(a.x*i.x+a.y*i.y+a.z*i.z,a.x*n.x+a.y*n.y+a.z*n.z)*180/Math.PI%360+360)%360}static basisAround(e){const t=Math.abs(e.y)<.9?{x:0,y:1,z:0}:{x:1,y:0,z:0},n=Dt.normalise(Dt.cross(e,t));return[n,Dt.normalise(Dt.cross(e,n))]}static toHorizontal(e){const t=Math.hypot(e.x,e.y,e.z)||1;return{altitudeDeg:Math.asin(Math.min(1,Math.max(-1,e.y/t)))*180/Math.PI,azimuthDeg:(Math.atan2(e.x,-e.z)*180/Math.PI%360+360)%360}}static appearanceOf(e){const t=Dt.toCartesian(e.radiant??{altitudeDeg:90,azimuthDeg:0}),n=Dt.turnAround(t,e.bearingDeg),i=e.fromRadiantDeg*Math.PI/180;return Dt.toHorizontal({x:t.x*Math.cos(i)+n.x*Math.sin(i),y:t.y*Math.cos(i)+n.y*Math.sin(i),z:t.z*Math.cos(i)+n.z*Math.sin(i)})}static toCartesian(e){const t=e.altitudeDeg*Math.PI/180,n=e.azimuthDeg*Math.PI/180,i=Math.cos(t);return{x:i*Math.sin(n),y:Math.sin(t),z:-i*Math.cos(n)}}static cross(e,t){return{x:e.y*t.z-e.z*t.y,y:e.z*t.x-e.x*t.z,z:e.x*t.y-e.y*t.x}}static normalise(e){const t=Math.hypot(e.x,e.y,e.z)||1;return{x:e.x/t,y:e.y/t,z:e.z/t}}static TYPICAL_VELOCITY_KM_S=40}const Tm="https://ufoathome.org/tle/index.json";class pn{static MAX_ELEMENT_AGE_DAYS=7;static DAY_MS=864e5;fetchImpl;indexUrls;index;files=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??pn.defaultIndexUrls()}static defaultIndexUrls(){const e=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&e.push(new URL("/tle/index.json",location.href).href),e.includes(Tm)||e.push(Tm),e}static FIRST_SNAPSHOT="2021-02-22";async covers(e){const t=Date.parse(`${pn.FIRST_SNAPSHOT}T00:00:00Z`)-pn.MAX_ELEMENT_AGE_DAYS*pn.DAY_MS;if(e.getTime()<t)return!1;const n=await this.loadIndex();return n?Object.values(n.index.kinds).some(i=>e.getTime()>=Date.parse(i.from)-pn.MAX_ELEMENT_AGE_DAYS*pn.DAY_MS&&e.getTime()<=Date.parse(i.to)+pn.MAX_ELEMENT_AGE_DAYS*pn.DAY_MS):!1}async at(e){const t=await this.loadIndex();if(!t)return;const{index:n,base:i}=t,s=[],a=[];for(const o of Object.keys(n.kinds)){const l=await this.kindAt(o,e,n,i);s.push(...l),a.push(this.coverageOf(o,e,n,l.length>0))}return{objects:s,coverage:a,credit:n.credit,creditUrl:n.source}}async kindAt(e,t,n,i){const s=t.getTime(),a=n.binDays*pn.DAY_MS,o=Math.floor(s/a),l=s-o*a<a/2?o-1:o+1,c=new Set(n.kinds[e].bins),h=[o,l].map(v=>new Date(v*a).toISOString().slice(0,10)).filter(v=>c.has(v));if(h.length===0)return[];const[d,...u]=await Promise.all([this.json(new URL(`objects-${e}.json`,i).href),...h.map(v=>this.binary(new URL(`${e}/${v}.bin`,i).href))]),f=new Map;for(const v of u)for(const m of pn.decode(v,n.recordBytes)){const g=f.get(m.norad);(!g||Math.abs(m.epochMs-s)<Math.abs(g.epochMs-s))&&f.set(m.norad,m)}const p=[];for(const v of f.values()){const m=Math.abs(v.epochMs-s)/pn.DAY_MS;if(m>pn.MAX_ELEMENT_AGE_DAYS)continue;const g=d[v.norad]??{name:String(v.norad)};g.launch&&Date.parse(`${g.launch}T00:00:00Z`)>s||p.push({norad:v.norad,name:g.name,kind:e,launch:g.launch,stdMag:g.stdMag,elements:v,ageDays:m})}return p}coverageOf(e,t,n,i){const{from:s,to:a}=n.kinds[e],o=t.getTime(),l=pn.MAX_ELEMENT_AGE_DAYS*pn.DAY_MS,c=i?"covered":o<Date.parse(s)-l?"before":o>Date.parse(a)+l?"after":"gap";return{kind:e,status:c,from:s,to:a}}static decode(e,t){const n=new DataView(e),i=[];for(let s=0;s+t<=e.byteLength;s+=t)i.push({norad:n.getUint32(s,!0),epochMs:n.getFloat64(s+4,!0),bstar:n.getFloat32(s+12,!0),inclinationDeg:n.getFloat32(s+16,!0),raanDeg:n.getFloat32(s+20,!0),eccentricity:n.getFloat32(s+24,!0),argOfPerigeeDeg:n.getFloat32(s+28,!0),meanAnomalyDeg:n.getFloat32(s+32,!0),meanMotion:n.getFloat64(s+36,!0)});return i}loadIndex(){return this.index??=(async()=>{for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;return{index:await t.json(),base:e}}catch{}})(),this.index}json(e){return this.cached(e,async t=>t.json())}binary(e){return this.cached(e,async t=>t.arrayBuffer())}cached(e,t){let n=this.files.get(e);return n||(n=this.fetchImpl(e).then(i=>{if(!i.ok)throw new Error(`${e}: ${i.status}`);return t(i)}),n.catch(()=>this.files.delete(e)),this.files.set(e,n)),n}}class HT{lowerM;upperM;add(e,t){if(!(e<=0)){if(t.behindM!==void 0){const n=et.sizeMAt(t.behindM,e);this.lowerM=this.lowerM===void 0?n:Math.max(this.lowerM,n)}if(t.inFrontM!==void 0){const n=et.sizeMAt(t.inFrontM,e);this.upperM=this.upperM===void 0?n:Math.min(this.upperM,n)}}}get sizeRange(){return{minM:this.lowerM,maxM:this.upperM}}get empty(){return this.lowerM===void 0&&this.upperM===void 0}get contradictory(){return this.lowerM!==void 0&&this.upperM!==void 0&&this.lowerM>this.upperM}distanceRangeAt(e){return e<=0?{}:{minM:this.lowerM===void 0?void 0:et.distanceMAt(this.lowerM,e),maxM:this.upperM===void 0?void 0:et.distanceMAt(this.upperM,e)}}clear(){this.lowerM=void 0,this.upperM=void 0}}class ar{static DEG_PER_SECOND=360/86164.0905;static degOver(e){return Math.max(0,e)*ar.DEG_PER_SECOND}static instants(e,t){if(!(t>0))return 1;const n=ar.degOver(e)/t;return n<1?1:Math.min(ar.MAX_INSTANTS,Math.max(2,Math.ceil(n)))}static MAX_INSTANTS=64}class mn{static EYE={apertureMm:7,exposureSeconds:.1,resolutionArcsec:60};static WAVELENGTH_M=55e-8;static ARCSEC_PER_RADIAN=180*3600/Math.PI;static UNKNOWN_CAMERA_FOCAL_MM=50;static UNKNOWN_CAMERA_DETAIL_UM=20;static get skyDriftArcsecPerSecond(){return ar.DEG_PER_SECOND*3600}static graspOf(e,t={}){const n=t.exposureSeconds??e.exposureSeconds,i=t.fNumber??e.fNumber;if(n===void 0||i===void 0||!(n>0)||!(i>0))return mn.EYE;const s=t.focalLengthMm??e.frame?.focalLengthMm??mn.UNKNOWN_CAMERA_FOCAL_MM,a=s/i,o=mn.resolutionArcsec(e,s,a);return{apertureMm:a,exposureSeconds:Math.min(n,mn.trailLimitedSeconds(o)),resolutionArcsec:o}}static resolutionArcsec(e,t,n){const s=(e.detailUm??mn.UNKNOWN_CAMERA_DETAIL_UM)/1e3/t*mn.ARCSEC_PER_RADIAN,a=1.22*mn.WAVELENGTH_M/(n/1e3)*mn.ARCSEC_PER_RADIAN;return Math.max(s,a)}static trailLimitedSeconds(e){return e/mn.skyDriftArcsecPerSecond}static gainOverEye(e,t={}){const n=mn.graspOf(e,t),i=mn.EYE,s=(n.apertureMm/i.apertureMm)**2,a=n.exposureSeconds/i.exposureSeconds,o=(i.resolutionArcsec/n.resolutionArcsec)**2;return 1.25*Math.log10(s*a*o)}static gainFor(e,t){const n=t.fieldOfViewDeg===void 0?void 0:rt.focalLengthMmFor(e,t.fieldOfViewDeg);return mn.gainOverEye(e,{fNumber:t.fNumber,focalLengthMm:n,exposureSeconds:t.exposureSeconds})}}const Am=111320,Wa=Math.PI/180,GT=1.02,WT=1;class oo{static of(e,t){const n=oo.sightings(e,t);if(n.length<2)return;const i=oo.baseline(n);if(!i)return;const{near:s,far:a,closedM:o}=i,l=Math.tan(a.widthDeg/2*Wa)===0?0:Math.tan(s.widthDeg/2*Wa)/Math.tan(a.widthDeg/2*Wa);if(l<GT)return;const c=o/(l-1),h=et.sizeMAt(c,s.widthDeg),d=n.map(u=>({t:u.t,m:et.distanceMAt(h,u.widthDeg)}));return{widthM:h,distanceM:d,nearestM:Math.min(...d.map(u=>u.m)),fromT:a.t,toT:s.t,closedM:o}}static sightings(e,t){return e.timeline.allKeyframes.flatMap(n=>{const i=n.shapes.find(o=>o.sourceId===t)?.shape,s=i?.angular?.widthDeg,a=tt(e,n.t);return s===void 0||s<=0||a?.lat===void 0||a.lng===void 0?[]:[{t:n.t,widthDeg:s,lat:a.lat,lng:a.lng,sightAzimuthDeg:i?.aim?.azimuthDeg??a.headingDeg}]}).sort((n,i)=>n.t-i.t)}static baseline(e){let t;for(const n of e)for(const i of e){if(n.t>=i.t)continue;const s=oo.closedAlongSight(n,i),[a,o,l]=s>=0?[i,n,s]:[n,i,-s];l<WT||a.widthDeg<=o.widthDeg||(!t||l>t.closedM)&&(t={near:a,far:o,closedM:l})}return t}static closedAlongSight(e,t){const n=(t.lat-e.lat)*Am,i=(t.lng-e.lng)*Am*Math.cos(e.lat*Wa),s=(e.sightAzimuthDeg??0)*Wa;return n*Math.cos(s)+i*Math.sin(s)}}class xn{static CONVENTIONAL_M=5;static NEAREST_M=.2;static MARGIN=1.1;static resolve(e){if(e.statedM!==void 0&&e.statedM>0)return{distanceM:xn.atLeastNearest(e.statedM),basis:"stated"};if(e.hypothesisM!==void 0&&e.hypothesisM>0)return{distanceM:xn.atLeastNearest(e.hypothesisM),basis:"hypothesis"};if(e.derivedM!==void 0&&e.derivedM>0)return{distanceM:xn.atLeastNearest(e.derivedM),basis:"derived"};const t=xn.largest(e.range?.minM,e.crossing?.behindM),n=xn.smallest(e.range?.maxM,e.crossing?.inFrontM),i=t===void 0?void 0:t*xn.MARGIN,s=n===void 0?void 0:n/xn.MARGIN;return i!==void 0&&s!==void 0?{distanceM:xn.atLeastNearest(i<=s?Math.sqrt(i*s):i),basis:"bounded"}:i!==void 0?{distanceM:xn.atLeastNearest(i),basis:"bounded"}:s!==void 0&&s<xn.CONVENTIONAL_M?{distanceM:xn.atLeastNearest(s),basis:"bounded"}:{distanceM:xn.CONVENTIONAL_M,basis:"conventional"}}static atLeastNearest(e){return Math.max(xn.NEAREST_M,e)}static largest(...e){const t=e.filter(n=>n!==void 0&&n>0);return t.length===0?void 0:Math.max(...t)}static smallest(...e){const t=e.filter(n=>n!==void 0&&n>0);return t.length===0?void 0:Math.min(...t)}}xc();const VT={sun:{en:"Sun",fr:"Soleil"},moon:{en:"Moon",fr:"Lune"},Venus:{en:"Venus",fr:"Vénus"},Mars:{en:"Mars",fr:"Mars"},Jupiter:{en:"Jupiter",fr:"Jupiter"},Saturn:{en:"Saturn",fr:"Saturne"}},XT=["en","fr"],qT={en:"{name} — mag {mag}, {alt}° above the horizon",fr:"{name} — mag {mag}, {alt}° au-dessus de l'horizon"},YT={en:"{name} — satellite, mag {mag}, {height} km up",fr:"{name} — satellite, mag {mag}, à {height} km d'altitude"},Pv="satellites-change",$T={en:"{name} — mag {mag}, {alt}° below the horizontal",fr:"{name} — mag {mag}, {alt}° sous l'horizontale"},Im="comet:",KT={building:{en:"Building",fr:"Bâtiment"},tree:{en:"Tree",fr:"Arbre"},crop:{en:"Crop row",fr:"Rang de culture"},mound:{en:"Stone heap",fr:"Tas de pierres"},streetlight:{en:"Streetlight",fr:"Lampadaire"},vehicle:{en:"Vehicle",fr:"Véhicule"},witness:{en:"Witness",fr:"Témoin"},aircraft:{en:"Aircraft",fr:"Aéronef"},entity:{en:"Being",fr:"Être"}},ZT=new URL(""+new URL("stars-mag7.5-B43R6Wvg.bin",import.meta.url).href,import.meta.url).href,jT=new URL(""+new URL("stars-mag7.5-9-BLV2tFmZ.bin",import.meta.url).href,import.meta.url).href,JT=-18,QT={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},qh={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class ff extends HTMLElement{static get observedAttributes(){return["src","star-catalog-src","deep-star-catalog-src","show-compass","max-pixel-ratio",sr,ia]}shadow;stageElement;frameElement;sceneCanvas;ufoElement;sceneRenderer;hoverTooltip;resizeObserver;sizeEstimates=new Map;sizeEstimatesFor;distanceHypotheses=new Map;depths=new Map;directionScratch=new P;meteorScheduleFor;lastTimeMs=0;lastSkyKey;starCatalog;starCatalogRequest=0;static tleArchive=new pn;satellitesFor;satelliteRequest=0;satelliteStatus="none";satellites;satellitePassesMemo;starCatalogDepth=0;weatherAudio=new BT;animateWhilePausedValue=!1;set animateWhilePaused(e){e!==this.animateWhilePausedValue&&(this.animateWhilePausedValue=e,this.syncAnimationsToPlayback())}get animateWhilePaused(){return this.animateWhilePausedValue}thunderTimeoutId;handleFullscreenChange=()=>this.resizeToStage();handlePointerMove=e=>{this.sceneRenderer.setCompassHovered(!0);const t=this.ufoElement.canvasElement,n=t.getBoundingClientRect();if(n.width===0||n.height===0)return;const i=(e.clientX-n.left)/n.width*t.width,s=(e.clientY-n.top)/n.height*t.height;if(this.ufoElement.hasVisibleShapeAt(i,s)){this.hoverTooltip.hidden=!0;return}const a=(e.clientX-n.left)/n.width*2-1,o=-((e.clientY-n.top)/n.height*2-1),l=na(Ts.preferencesFor(this),XT),c=this.sceneRenderer.pickBodyAt(a,o);if(c){this.showHoverTooltip(e,this.bodyName(c,l));return}const h=this.sceneRenderer.pickDecorAt(a,o),d=h?this.ufoElement.sighting.decor.find(p=>p.id===h):void 0;if(d){this.showHoverTooltip(e,this.said.read(d.title)||KT[d.kind][l]);return}const u=this.sceneRenderer.pickSatelliteAt(a,o);if(u){this.showHoverTooltip(e,YT[l].replace("{name}",u.name).replace("{mag}",u.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(u.heightKm).toLocaleString()));return}const f=this.sceneRenderer.pickStarAt(a,o);if(f){const p=f.star.mag,v=f.altitudeDeg,m=(v<0?$T:qT)[l];this.showHoverTooltip(e,m.replace("{name}",f.star.name[l]).replace("{mag}",p.toLocaleString(void 0,{maximumFractionDigits:Math.abs(p)<1?2:1})).replace("{alt}",String(Math.round(Math.abs(v)))));return}this.hoverTooltip.hidden=!0};bodyName(e,t){const n=e.startsWith(Im)?e.slice(Im.length):void 0;return(n?Rv.find(s=>s.id===n):void 0)?.name[t]??VT[e]?.[t]??e}showHoverTooltip(e,t){this.hoverTooltip.textContent=t,this.hoverTooltip.hidden=!1;const n=this.stageElement.getBoundingClientRect();this.hoverTooltip.style.left=`${e.clientX-n.left+12}px`,this.hoverTooltip.style.top=`${e.clientY-n.top+12}px`}handlePointerLeave=()=>{this.hoverTooltip.hidden=!0,this.sceneRenderer.setCompassHovered(!1)};handleLightningFlash=()=>{clearTimeout(this.thunderTimeoutId);const e=(.5+Math.random()*3.5)*1e3;this.thunderTimeoutId=window.setTimeout(()=>this.weatherAudio.playThunder(),e)};handleFirstInteraction=()=>{this.weatherAudio.resume(),this.setWeather(Ut(this.ufoElement.sighting,this.lastTimeMs))};handleTimeUpdate=e=>{this.lastTimeMs=e.detail.time,this.syncAnimationsToPlayback(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.playbackState==="playing"&&this.sceneRenderer.frame(performance.now())};syncAnimationsToPlayback(){const e=this.ufoElement.playbackState==="playing",t=e||this.animateWhilePaused;this.sceneRenderer.setAnimationsRunning(t,e),this.weatherAudio.setPaused(!t),t||clearTimeout(this.thunderTimeoutId)}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${ry}</style>${sy}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.frameElement=this.shadow.getElementById("frame"),this.sceneCanvas=this.shadow.getElementById("scene-canvas"),this.sceneRenderer=new $n(this.sceneCanvas,void 0,this.handleLightningFlash),this.hoverTooltip=this.shadow.getElementById("hover-tooltip"),this.ufoElement=document.createElement(ld),this.ufoElement.classList.add("ufo-overlay"),this.ufoElement.paintsShapes=!1,this.forwardPlayerAttributes(),this.ufoElement.addEventListener("lookat",t=>this.lookToward(t.detail)),this.ufoElement.style.setProperty("--ufo-canvas-background","transparent"),this.ufoElement.style.setProperty("--ufo-canvas-border","none"),this.ufoElement.fullscreenTarget=this.stageElement,this.shadow.getElementById("ufo-slot").replaceWith(this.ufoElement),this.sceneRenderer.onMapSubjectBounds=t=>this.ufoElement.setMapSubjectBounds(t),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),this.ufoElement.addEventListener("referenceview",t=>this.applyReferenceView(t.detail)),this.ufoElement.canvasElement.addEventListener("pointermove",this.handlePointerMove),this.ufoElement.canvasElement.addEventListener("pointerleave",this.handlePointerLeave),this.ufoElement.canvasElement.addEventListener("pointerdown",this.handleFirstInteraction,{once:!0})}get said(){return this.saidTexts??=new Zi(Ts.preferencesFor(this))}saidTexts;connectedCallback(){this.saidTexts=void 0,this.sceneRenderer.restoreContext(),this.resizeToStage(),this.updateAstronomy(this.lastTimeMs),this.loadStars(),this.resizeObserver=new ResizeObserver(()=>this.resizeToStage()),this.resizeObserver.observe(this.frameElement),document.addEventListener("fullscreenchange",this.handleFullscreenChange);const e=this.getAttribute("src");e&&this.loadFromSrc(e)}disconnectedCallback(){this.resizeObserver?.disconnect(),document.removeEventListener("fullscreenchange",this.handleFullscreenChange),this.sceneRenderer.stopTwinkle(),clearTimeout(this.thunderTimeoutId),this.weatherAudio.dispose(),queueMicrotask(()=>{this.isConnected||this.sceneRenderer.releaseContext()})}attributeChangedCallback(e,t,n){if(e==="src"&&n&&n!==t&&this.isConnected&&this.loadFromSrc(n),(e==="star-catalog-src"||e==="deep-star-catalog-src")&&n!==t&&this.isConnected&&this.loadStars(),e==="show-compass"&&n!==t&&this.sceneRenderer.setShowCompass(this.hasAttribute("show-compass")),e==="max-pixel-ratio"&&n!==t){const i=Number(n);this.sceneRenderer.setMaxPixelRatio(Number.isFinite(i)&&i>0?i:Math.min(window.devicePixelRatio||1,2))}(e===sr||e===ia)&&n!==t&&this.forwardPlayerAttributes()}forwardPlayerAttributes(){for(const e of[sr,ia])this.ufoElement.toggleAttribute(e,this.hasAttribute(e))}setCompassForced(e){this.sceneRenderer.setCompassForced(e)}lookToward(e){const t=tt(this.ufoElement.sighting,this.lastTimeMs);if(e.kind==="witness"||t?.lat===void 0||t.lng===void 0||t.headingDeg===void 0){this.setLookOffset(0,0);return}const{x:n,z:i}=on(e.lat,e.lng,t.lat,t.lng);if(Math.hypot(n,i)<1)return this.setLookOffset(0,0);const s=(Math.atan2(n,-i)*180/Math.PI+360)%360;this.setLookOffset(((s-t.headingDeg)%360+540)%360-180,-t.pitchDeg)}setLookOffset(e,t){this.sceneRenderer.setLookOffset(e,t),this.ufoElement.setLookOffset(e,t),this.updateAstronomy(this.lastTimeMs)}setIndoorLook(e,t){this.sceneRenderer.setIndoorLook(e,t)}setCloudRendering(e){this.sceneRenderer.setCloudRendering(e)}setWeather(e){this.sceneRenderer.setWeather(e),this.weatherAudio.setAmbient(e.precipitationType,e.precipitationIntensity,e.windSpeed)}pickCloudAt(e,t){return this.sceneRenderer.pickCloudAt(e,t)}cloudDirectionAt(e,t){return this.sceneRenderer.cloudDirectionAt(e,t)}pickDecorAt(e,t){return this.sceneRenderer.pickDecorAt(e,t)}resumeWeatherAudio(){this.weatherAudio.resume()}async loadFromSrc(e){this.sightingData=await Lu.json(e)}get sightingData(){return this.ufoElement.sightingData}set sightingData(e){this.ufoElement.sightingData=e,this.applyFrameFormat(),this.lastTimeMs=0,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(0)}referenceAspect(e){return this.sceneRenderer.referenceAspect(e)}screenPointOf(e){return this.sceneRenderer.screenPointOf(e)}directionAt(e,t){return this.sceneRenderer.directionAt(e,t)}referenceFailedToLoad(e){return this.sceneRenderer.referenceFailedToLoad(e)}applyReferenceView(e){this.sceneRenderer.setReferencesShown(e.shown);for(const t of this.ufoElement.sighting.references)this.sceneRenderer.setReferenceView(t.id,{opacity:e.opacity})}get currentTerrainAttribution(){return this.sceneRenderer.currentTerrainAttribution}setTerrainProviders(e){this.sceneRenderer.setTerrainProviders(e)}setDecorModelProvider(e){this.sceneRenderer.setDecorModelProvider(e)}get decorModelCredits(){return this.sceneRenderer.currentDecorModelCredits}applyFrameFormat(){const e=this.ufoElement.sighting.instrument,t=et.CANVAS_HEIGHT_PX,n=rt.frameWidthPx(e,t);this.frameElement.style.setProperty("--frame-aspect",`${n} / ${t}`)}resizeToStage(){const e=this.frameElement.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height));this.sceneCanvas.width=t,this.sceneCanvas.height=n,this.sceneRenderer.resize(t,n)}async loadStars(){const e=[{magnitudeLimit:Xh,url:this.getAttribute("star-catalog-src")??ZT},{magnitudeLimit:ao,url:this.getAttribute("deep-star-catalog-src")??jT}],t=this.instrumentReach(),n=++this.starCatalogRequest;this.starCatalogDepth=t>Xh?ao:Xh;const i=await xi.upTo(e,t);n===this.starCatalogRequest&&(this.starCatalog=i,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(this.lastTimeMs))}ensureStarsDeepEnough(){!this.starCatalog||this.starCatalogDepth>=ao||this.instrumentReach()<=this.starCatalogDepth||this.loadStars()}instrumentReach(){const e=this.ufoElement.sighting,t=mn.gainFor(e.instrument,{fNumber:tt(e,0)?.fNumber,fieldOfViewDeg:ln.fovOf(e,0),exposureSeconds:e.exposure});return nr(JT,t)}updateAstronomy(e){this.ensureStarsDeepEnough(),this.applySceneAt(e);const t=ii.windowEndingAt(e,this.exposureSeconds()),n=t.seconds,i=this.degreesPerPixelAt(e),s=ar.instants(n,i),a=Math.max(s,this.ufoElement.exposureTimes(e).length,ii.instants(this.ufoElement.sighting.decor,tt(this.ufoElement.sighting,e)?.elevationM??0,t.fromMs,n,i));if(a<=1){this.sceneRenderer.setExposure(1);return}this.sceneRenderer.setExposure(a,o=>this.applySceneAt(t.fromMs+t.ms*o/(a-1),{sky:Math.floor(o*s/a)!==Math.floor((o-1)*s/a),stepMs:t.ms/a}))}exposureSeconds(){return this.ufoElement.sighting.exposure??0}degreesPerPixelAt(e){const t=this.sceneCanvas.height;return t<=0?0:ln.fovOf(this.ufoElement.sighting,e)/t}applySceneAt(e,t){const n=this.ufoElement.sighting;this.setWeather(Ut(n,e)),this.sceneRenderer.setInstrument(n.instrument),this.updateMeteorShower(n,e),this.sceneRenderer.setDecor(n.decor),this.sceneRenderer.setReferences(n.references);const i=tt(n,e),s=tt(n,0),a=Ut(n,0),o=Object.fromEntries(Di(Ut(n,e)).map(x=>[x.id,$l(e,n.weatherTrack,a,s,i,x.id)]));this.sceneRenderer.setCloudOffset($l(e,n.weatherTrack,a,s,i),o),this.sceneRenderer.setObserverPose(i??qh),this.sceneRenderer.setLensOptics(this.lensOpticsAt(e)),this.sceneRenderer.setInstrumentGain(mn.gainFor(n.instrument,{fNumber:i?.fNumber,fieldOfViewDeg:ln.fovOf(n,e),exposureSeconds:n.exposure})),this.sceneRenderer.setGait($t.of(n)?.offsetAt(e)??$t.STILL),this.sceneRenderer.updateDecorAnchoring(tt(n,0),i,e),this.sceneRenderer.updateDecorLitState(e,t?.stepMs??0),this.sceneRenderer.setTerrainOrigin(i?.lat,i?.lng),this.pushPhenomenaAt(e);const l=i?.lat??qh.lat,c=i?.lng??qh.lng,h=Ds(n.event.time??{},c,n.event.utcOffsetHours),d={lat:l,lng:c,elevationM:i?.elevationM??0};if(this.pushSatellitesAt(h,e,d),t&&!t.sky)return;if(!h){this.sceneRenderer.setAstronomy(QT);return}const u=new Date(h.getTime()+e),f=Math.max(1,Math.round(.25*this.degreesPerPixelAt(e)/ar.DEG_PER_SECOND*1e3)),p=Math.max(1e-8,this.degreesPerPixelAt(e)*.1),v=`${Math.floor(u.getTime()/f)}|${Math.round(l/p)}|${Math.round(c/p)}|${Math.round(d.elevationM)}|${this.starCatalog?this.starCatalogDepth:0}`;if(v===this.lastSkyKey){this.sceneRenderer.render();return}this.lastSkyKey=v;const m={...Cn("Sun",u,d),magnitude:Ah("Sun",u)},g={...Cn("Moon",u,d),phase:vc(u),magnitude:Ah("Moon",u)},M=$E.map(x=>({body:x,position:Cn(x,u,d),magnitude:Ah(x,u)}));this.sceneRenderer.setAstronomy({sun:m,moon:g,planets:M,comet:this.cometAt(u,d),stars:this.starCatalog?{catalog:this.starCatalog,date:u,observer:d}:void 0,frame:{date:u,observer:d}}),this.ufoElement.setSunAltitude(m.altitudeDeg)}pushSatellitesAt(e,t,n){if(this.ensureSatellites(e),!e||!this.satellites){this.sceneRenderer.setSatellites([]);return}const i=new Date(e.getTime()+t),s=[];for(const a of this.satellites.passes.positionsAt(i,n,-1))a.magnitude!==void 0&&s.push({norad:a.object.norad,name:a.object.name,position:{altitudeDeg:a.altitudeDeg,azimuthDeg:a.azimuthDeg},magnitude:a.magnitude,heightKm:a.heightKm});this.sceneRenderer.setSatellites(s)}ensureSatellites(e){const t=e?String(e.getTime()):"";if(t===this.satellitesFor)return;this.satellitesFor=t,this.satellites=void 0,this.satellitePassesMemo=void 0;const n=++this.satelliteRequest;if(!e){this.satelliteStatus="none";return}this.satelliteStatus="loading";const i=a=>{n===this.satelliteRequest&&(this.satelliteStatus=a,this.dispatchEvent(new CustomEvent(Pv)))},s=ff.tleArchive;(async()=>{if(!await s.covers(e))return i("outside");const[a,o]=await Promise.all([s.at(e),jn(()=>import("./SatellitePasses-Pfro2-0Z.js"),[],import.meta.url)]);if(n===this.satelliteRequest){if(!a)return i("unavailable");this.satellites={snapshot:a,passes:new o.SatellitePasses(a.objects)},i("ready"),this.updateAstronomy(this.lastTimeMs)}})().catch(()=>i("unavailable"))}get satelliteState(){const e=this.satellites?.snapshot;return{status:this.satelliteStatus,coverage:e?.coverage,credit:e?.credit,creditUrl:e?.creditUrl}}satellitePassesDuring(e){const t=this.satellites,n=this.ufoElement.sighting,i=tt(n,0),s=n.event.place?.[0],a=i?.lat??s?.lat,o=i?.lng??s?.lng;if(!t||a===void 0||o===void 0)return[];const l=Ds(n.event.time??{},o,n.event.utcOffsetHours);if(!l)return[];const c=Math.min(Math.max(e,0),4*36e5),h={lat:a,lng:o,elevationM:i?.elevationM??0},d=JSON.stringify([this.satellitesFor,l.getTime(),a,o,h.elevationM,c]);if(this.satellitePassesMemo?.key===d)return this.satellitePassesMemo.passes;const u=Math.max(10,Math.ceil(c/1e3/600)),f=t.passes.passesDuring(l,new Date(l.getTime()+c),h,u);return this.satellitePassesMemo={key:d,passes:f},f}cometAt(e,t){const n=ql.brightestAt(e,t);if(n)return{id:n.apparition.id,position:n.position,tailEnd:n.tailEnd,magnitude:n.magnitude}}pushPhenomenaAt(e){const t=this.ufoElement.sighting;t!==this.sizeEstimatesFor&&(this.sizeEstimates.clear(),this.distanceHypotheses.clear(),this.sizeEstimatesFor=t);const n=t.timeline,i=this.ufoElement.canvasElement,s=this.ufoElement.frameShiftPx,a=this.projectionAt(e),o=new Map,l=new Map,c=new Set;for(const p of n.sourceIds){const v=n.getInterpolatedShapeAt(e,p);if(!v)continue;const m={...v,bounds:{...v.bounds,x:v.bounds.x+s.x,y:v.bounds.y+s.y}};o.set(p,m);const g=v.aim?this.sceneRenderer.screenPointOf(ni.directionOf(v.aim,this.directionScratch)):{ndcX:(m.bounds.x+m.bounds.width/2)/i.width*2-1,ndcY:-((m.bounds.y+m.bounds.height/2)/i.height*2-1)},M=g!==void 0&&Math.abs(g.ndcX)<=1&&Math.abs(g.ndcY)<=1,x=M?this.sceneRenderer.decorDistancesAt(g.ndcX,g.ndcY,p):{};c.add(p),(M||v.aim)&&c.delete(p);const w=v.angular?.widthDeg??a.pxToDeg(v.bounds.width),S=this.sizeEstimateOf(p);S.add(w,x);const E=oo.of(t,p);l.set(p,xn.resolve({hypothesisM:this.distanceHypotheses.get(p),derivedM:E&&w>0?et.distanceMAt(E.widthM,w):void 0,range:S.distanceRangeAt(w),crossing:x}))}for(const[p,v]of o)for(const[m,g]of o){if(m===p||g.transparency>=1||g.bounds.width*g.bounds.height<=v.bounds.width*v.bounds.height||!(v.bounds.x>=g.bounds.x&&v.bounds.y>=g.bounds.y&&v.bounds.x+v.bounds.width<=g.bounds.x+g.bounds.width&&v.bounds.y+v.bounds.height<=g.bounds.y+g.bounds.height))continue;const x=l.get(m);x&&l.set(p,{distanceM:x.distanceM*.999,basis:x.basis});break}this.depths=l;const h=n.sourceIds,d=[];for(const[p,v]of o)d.push({sourceId:p,shape:v,distanceM:l.get(p).distanceM,renderOrder:h.indexOf(p),aim:v.aim,hidden:c.has(p)});const f=(tt(t,e)?.rollDeg??0)+($t.of(t)?.offsetAt(e)??$t.STILL).rollDeg;this.sceneRenderer.setPhenomena(d,{projection:a,canvasWidthPx:i.width,canvasHeightPx:i.height,scale:Math.max(1,this.sceneCanvas.height/Math.max(1,i.height)),starPoints:rt.starPointsOf(t.instrument),rollRad:f*Math.PI/180})}setDistanceHypothesis(e,t){t===void 0||!(t>0)?this.distanceHypotheses.delete(e):this.distanceHypotheses.set(e,t),this.updateAstronomy(this.lastTimeMs)}depthOf(e){return this.depths.get(e)}sizeRangeOf(e){return this.sizeEstimateOf(e).sizeRange}distanceRangeAt(e,t){const n=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,e);if(!n)return{};const i=n.angular?.widthDeg??this.projectionAt(t).pxToDeg(n.bounds.width);return this.sizeEstimateOf(e).distanceRangeAt(i)}sizeContradictory(e){return this.sizeEstimateOf(e).contradictory}updateMeteorShower(e,t){this.ensureMeteorSchedule(e),this.sceneRenderer.updateMeteors(t)}ensureMeteorSchedule(e){const t=this.meteorInputsOf(e);t!==this.meteorScheduleFor&&(this.meteorScheduleFor=t,this.scheduleMeteors(e))}meteorInputsOf(e){const t=e.event.place?.[0],n=e.event.time;return JSON.stringify([t?.lat,t?.lng,n?.year,n?.month,n?.day,n?.hour,n?.minute,e.event.utcOffsetHours,e.event.durationSeconds,e.timeline.duration])}scheduleMeteors(e){const t=e.event.place?.[0],n=e.event.time,i=t?.lat!==void 0&&t.lng!==void 0&&n?.year!==void 0?Ds(n,t.lng,e.event.utcOffsetHours):void 0;if(!i||t?.lat===void 0||t.lng===void 0){this.sceneRenderer.setMeteorShower([],0,0);return}const s={lat:t.lat,lng:t.lng,elevationM:0},a=(e.event.durationSeconds??0)*1e3||e.timeline.duration||2e4,o=Math.round(i.getTime()/1e3)+Math.round(t.lat*1e3),l=Dt.schedule({ratePerHour:Dt.observedRatePerHour(Dt.apexPosition(i,s).altitudeDeg),durationMs:a,velocityKmS:Dt.TYPICAL_VELOCITY_KM_S,seed:o}),c=da.activeAt(i).map(d=>{const u=da.radiantPosition(d.shower,i,s);return{entry:d,position:u,rate:da.observedRatePerHour(d.zhr,u.altitudeDeg,d.shower.populationIndex)}}).sort((d,u)=>u.rate-d.rate)[0];if(!c||c.rate<=0){this.sceneRenderer.setMeteorShower(l,0,0);return}const h=rr.schedule({ratePerHour:c.rate,durationMs:a,velocityKmS:c.entry.shower.velocityKmS,seed:o+1});this.sceneRenderer.setMeteorShower([...h,...l],c.position.altitudeDeg,c.position.azimuthDeg)}meteorByRank(e){this.ensureMeteorSchedule(this.ufoElement.sighting);const t=[...this.sceneRenderer.meteorSchedule].filter(s=>s.t+s.durationMs<=this.ufoElement.seekableDuration).sort((s,a)=>a.brightness-s.brightness);if(t.length===0)return;const n=t[e%t.length],i=this.sceneRenderer.meteorMidpoint(n);if(i)return{t:Math.round(n.t+n.durationMs*.45),...i}}lensOpticsAt(e){const t=this.ufoElement.sighting,n=t.instrument,i=n.frame,s=tt(t,e),a=s?.fNumber??n.fNumber;if(!i||a===void 0)return;const o=rt.focalLengthMmFor(n,ln.fovOf(t,e));if(o!==void 0)return{focalLengthMm:o,fNumber:a,focusDistance:s?.focusDistanceM??0,frameHeightMm:i.heightMm}}projectionAt(e){const t=this.ufoElement.sighting;return oi.of(t.instrument,et.CANVAS_HEIGHT_PX,ln.fovOf(t,e))}sizeEstimateOf(e){let t=this.sizeEstimates.get(e);return t||(t=new HT,this.sizeEstimates.set(e,t)),t}}const Cu="rr0-scene";function eA(){xc(),customElements.get(Cu)||customElements.define(Cu,ff)}class tA{constructor(e,t){this.timeline=e,this.clock=t}currentPointer=null;shapePrototype=null;sourceId="";start(e,t){this.sourceId=e,this.shapePrototype=t,this.currentPointer=null,this.clock.start(n=>this.recordSample(n))}onPointerMove(e,t){this.currentPointer={x:e,y:t}}stop(){this.clock.stop()}recordSample(e){if(!this.currentPointer||!this.shapePrototype)return;const t=$m(this.shapePrototype,this.currentPointer.x,this.currentPointer.y);this.timeline.addKeyframe(e,[{sourceId:this.sourceId,shape:t}])}}class nA{constructor(e){this.intervalMs=e}rafId=null;startTime=0;lastTick=0;start(e){this.startTime=performance.now(),this.lastTick=0;const t=()=>{const n=performance.now()-this.startTime;n-this.lastTick>=this.intervalMs&&(this.lastTick=n,e(n)),this.rafId=requestAnimationFrame(t)};this.rafId=requestAnimationFrame(t)}stop(){this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}}const iA=[{id:"echo",name:{en:"the Echo balloons",fr:"les ballons Echo"},from:"1960-08-12",to:"1969-06-07",peakMagnitude:-1,note:"Echo 1 and 2 were 30- and 40-metre reflective balloons, as bright as the brightest stars and moving slowly enough to be watched — deliberately visible, widely announced in newspapers, and the first objects most people ever saw crossing the night sky. They fall squarely inside the sighting waves this project reconstructs."},{id:"iridium-flares",name:{en:"the Iridium flares",fr:"les flashes d'Iridium"},from:"1997-05-05",to:"2019-12-27",peakMagnitude:-8,note:"The original Iridium satellites carried flat, mirror-finish antennas that threw a sunbeam a few kilometres wide across the ground: a still point of sky flaring to magnitude -8 over five seconds and vanishing again. Nothing else in the sky does that."},{id:"iss",name:{en:"the International Space Station",fr:"la Station spatiale internationale"},from:"1998-11-20",peakMagnitude:-5.9,note:"Since its first module, and much brighter as it grew: at its best it outshines everything in the sky but the Sun and the Moon, crossing in a straight silent line in about four minutes."},{id:"starlink-trains",name:{en:"the Starlink trains",fr:"les trains de Starlink"},from:"2019-05-24",peakMagnitude:1,note:"In the days after a launch, satellites still bunched in their deployment string cross as an evenly spaced line of lights — the most reported 'formation of UFOs' of the era. They spread out within weeks, so a train is a fact about the days after a launch rather than about the year."}],sA=23493,Dm=[2,3,2,1,2,5,4,6,5,6,6,6,6,6,6,6,9,9,9,9,9,9,14,14,15,16,16,16,16,16,18,22,25,24,29,28,29,33,34,35,40,40,42,42,43,46,48,48,49,53,53,54,58,61,70,70,74,78,79,83,92,92,99,97,101,102,109,115,126,125,123,125,127,130,139,153,157,156,161,156,165,174,193,193,201,203,212,215,224,244,255,263,262,281,293,307,312,327,339,336,343,353,359,369,386,396,405,410,421,419,424,434,443,450,460,480,492,504,509,516,519,524,527,530,527,535,543,549,564,571,573,576,582,584,600,600,608,618,625,632,637,642,648,654,661,667,669,667,671,671,697,692,703,697,710,714,724,731,747,755,764,770,782,802,801,815,819,837,846,856,878,881,877,900,906,907,917,932,932,936,954,973,989,986,991,990,1002,1009,1021,1024,1040,1038,1058,1078,1098,1092,1094,1099,1122,1132,1140,1151,1154,1161,1176,1185,1202,1206,1227,1228,1243,1265,1281,1288,1296,1325,1328,1336,1354,1373,1375,1393,1398,1411,1432,1457,1462,1476,1487,1485,1506,1509,1521,1524,1537,1543,1563,1586,1598,1614,1621,1620,1640,1658,1660,1673,1670,1686,1708,1715,1726,1726,1745,1749,1767,1774,1790,1798,1803,1805,1815,1818,1819,1820,1833,1822,1821,1819,1838,1835,1845,1841,1851,1869,1865,1868,1871,1870,1879,1882,1886,1900,1899,1908,1921,1928,1954,1966,1976,1986,1999,2007,2015,2030,2036,2057,2067,2072,2077,2088,2101,2106,2112,2119,2127,2142,2171,2176,2203,2226,2242,2241,2244,2254,2263,2284,2300,2320,2327,2345,2364,2367,2402,2423,2425,2434,2443,2461,2476,2495,2505,2520,2531,2535,2556,2567,2599,2608,2625,2639,2660,2663,2668,2681,2695,2702,2709,2719,2720,2738,2746,2763,2778,2788,2796,2807,2822,2831,2831,2853,2863,2866,2883,2892,2895,2921,2919,2937,2941,2947,2964,2987,2992,2987,2995,3002,3021,3025,3026,3036,3052,3049,3059,3077,3075,3083,3086,3107,3123,3124,3146,3155,3168,3179,3204,3205,3211,3233,3252,3253,3276,3287,3294,3293,3297,3314,3326,3335,3338,3355,3362,3358,3365,3364,3376,3375,3382,3418,3429,3432,3455,3463,3483,3490,3502,3509,3521,3532,3542,3544,3553,3571,3580,3588,3596,3603,3633,3639,3649,3655,3660,3670,3699,3699,3707,3723,3747,3752,3754,3766,3772,3778,3781,3798,3815,3814,3824,3832,3853,3859,3879,3885,3899,3912,3910,3924,3937,3951,3951,3961,3963,3961,3976,3977,3988,4004,4018,4025,4047,4074,4086,4108,4133,4136,4159,4168,4182,4192,4200,4215,4230,4239,4257,4678,4698,4694,4713,4719,4739,4750,4756,4764,4771,4788,4792,4790,4809,4821,4829,4834,4836,4843,4853,4863,4872,4881,4890,4898,4901,4897,4895,4884,4886,4886,4894,4897,4905,4905,4909,4907,4925,4918,4920,4929,4925,4928,4936,4943,4944,4951,4955,4952,4974,4976,4975,4981,4994,4997,5022,5023,5032,5043,5048,5051,5066,5062,5068,5075,5082,5082,5098,5102,5110,5113,5119,5123,5138,5138,5145,5149,5157,5165,5166,5169,5178,5183,5190,5192,5203,5204,5207,5214,5228,5234,5245,5249,5256,5262,5275,5278,5305,5303,5315,5321,5348,5358,5369,5369,5372,5385,5402,5409,5427,5429,5429,5439,5456,5464,5481,5485,5494,5509,5520,5526,5543,5555,5568,5575,5585,5596,5602,5620,5627,5644,5647,5660,5678,5680,5684,5692,5700,5711,5727,5733,5736,5756,5776,5797,5805,5804,5807,5800,5808,5814,5822,5839,5856,5869,5889,5902,5919,5921,5936,5937,5936,5957,5961,5975,5981,6002,6015,6027,6035,6042,6059,6062,6080,6081,6092,6097,6106,6127,6129,6198,6227,6231,6243,6249,6262,6255,6279,6304,6315,6326,6330,6334,6361,6358,6359,6379,6381,6389,6388,6404,6404,6443,6465,6473,6497,6500,6513,6524,6532,6538,6578,6572,6576,6584,6582,6608,6639,6656,6761,6764,6768,6772,6836,6905,6916,6925,6951,6984,7009,7072,7092,7110,7122,7140,7148,7170,7168,7180,7194,7247,7374,7391,7393,7382,7425,7485,7530,7568,7587,7602,7602,7715,7771,7900,8004,8103,8153,8162,8296,8319,8437,8566,8746,8860,8913,9128,9275,9585,9739,10014,10123,10167,10203,10288,10323,10398,10544,10721,10883,11044,11157,11442,11515,11787,12070,12269,12468,12484,12619,12883,13008,13264,13317,13549,13859,14049,14175,14360,14498,14687,14843,14984,15093,15279,15431,15623,15741,15788,15966,16025,16132,16419,16568,16791,16892,17060,17269,17598,17959,18194,18482,18804,19136,19564,19990,20249,20509,20943,21248,21539,21845,22196,22412];class Mi{static FIRST_ORBIT="1957-10-04";static EARTH_RADIUS_KM=6371;static LOW_ORBIT_KM=500;static shadowHeightKm(e){if(e>=0)return 0;const t=-e*Math.PI/180;return Mi.EARTH_RADIUS_KM*(1/Math.cos(t)-1)}static isLitOverhead(e,t){return e>Mi.shadowHeightKm(t)}static classesAt(e){const t=e.getTime();return iA.filter(n=>{const i=Date.parse(`${n.from}T00:00:00Z`),s=n.to===void 0?1/0:Date.parse(`${n.to}T23:59:59Z`);return t>=i&&t<=s})}static trackedInOrbitAt(e){const t=e.getUTCFullYear()*12+e.getUTCMonth()-sA;if(!(t<0))return Dm[Math.min(t,Dm.length-1)]}static visibilityAt(e,t){const n=Cn("Sun",e,t).altitudeDeg;return{sunAltitudeDeg:n,shadowHeightKm:Mi.shadowHeightKm(n),lowOrbitLit:Mi.isLitOverhead(Mi.LOW_ORBIT_KM,n),classes:Mi.classesAt(e),trackedObjects:Mi.trackedInOrbitAt(e),anythingInOrbit:e.getTime()>=Date.parse(`${Mi.FIRST_ORBIT}T00:00:00Z`)}}}const rA={en:["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"],fr:["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSO","SO","OSO","O","ONO","NO","NNO"]};class _s{static POINT_DEG=360/16;static point(e,t){const n=(e%360+360)%360,i=Math.round(n/_s.POINT_DEG)%16;return rA[t][i]}static towards(e,t){const n=_s.point(e,t);return t==="en"?`to the ${n}`:aA.test(n)?`à l'${n}`:`au ${n}`}}const aA=/^[EO]/;class it{static COARSE_STEP_DEG=10;static FINE_STEP_DEG=2;static FINE_SPAN_DEG=10;static LOWEST_DEG=5;static THRESHOLD_CONTRAST=.5;static CONE_SEPARATION_DEG=60;galaxy=new je;dust=new It;assess(e,t){const n=Cn("Sun",e,t),i=Cn("Moon",e,t),s={altitudeDeg:i.altitudeDeg,phaseAngleDeg:Xe.phaseAngleOf(vc(e).illuminatedFraction)},a=Gn.galactic(e,t),o=it.unit(a.centre),l=it.unit(a.rotation),c=it.unit(a.pole),h=it.unit(Gn.eclipticPole(e,t)),d=it.unit(n),u=it.unit(i),f=it.normalize(it.reject(d,h));let p,v,m=0;const g=(M,x)=>{const w=it.unit({altitudeDeg:M,azimuthDeg:x}),S=it.between(w,d),E=Xe.magPerArcsec2({altitudeDeg:n.altitudeDeg,separationDeg:S},{...s,separationDeg:it.between(w,u)},M);E>m&&(m=E);const D=ns.fromMagPerArcsec2(E),y=10**(-.4*Xe.EXTINCTION_PER_AIR_MASS*(Xe.airMass(M)-1)),T=this.galaxy.surfaceBrightnessS10(Math.atan2(it.dot(w,l),it.dot(w,o))*180/Math.PI,Math.asin(Math.max(-1,Math.min(1,it.dot(w,c))))*180/Math.PI)*y;p=it.better(p,T,D,E,M,x,S);const A=Math.max(-1,Math.min(1,it.dot(w,h))),I=it.normalize(it.reject(w,h)),R=this.dust.surfaceBrightnessS10(it.between(I,f),Math.asin(A)*180/Math.PI)*y;v=it.better(v,R,D,E,M,x,S)};for(let M=it.LOWEST_DEG;M<=90;M+=it.COARSE_STEP_DEG)for(let x=0;x<360;x+=it.COARSE_STEP_DEG)g(M,x);for(const M of[p,v]){if(!M)continue;const x=it.FINE_SPAN_DEG,w=it.FINE_STEP_DEG;for(let S=M.altitudeDeg-x;S<=M.altitudeDeg+x;S+=w)if(!(S<it.LOWEST_DEG||S>90))for(let E=M.azimuthDeg-x;E<=M.azimuthDeg+x;E+=w)g(S,(E+360)%360)}return{milkyWay:p&&p.contrast>=it.THRESHOLD_CONTRAST?p:void 0,zodiacal:v&&v.contrast>=it.THRESHOLD_CONTRAST?v:void 0,darkestSkyMagPerArcsec2:m}}static better(e,t,n,i,s,a,o){const l=t/n;return e&&e.contrast>=l?e:{contrast:l,altitudeDeg:s,azimuthDeg:a,magPerArcsec2:ns.toMagPerArcsec2(t),skyMagPerArcsec2:i,sunSeparationDeg:o}}static unit(e){const t=e.altitudeDeg*Math.PI/180,n=e.azimuthDeg*Math.PI/180,i=Math.cos(t);return[i*Math.sin(n),Math.sin(t),-i*Math.cos(n)]}static dot(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}static between(e,t){return Math.acos(Math.max(-1,Math.min(1,it.dot(e,t))))*180/Math.PI}static reject(e,t){const n=it.dot(e,t);return[e[0]-n*t[0],e[1]-n*t[1],e[2]-n*t[2]]}static normalize(e){const t=Math.hypot(...e)||1;return[e[0]/t,e[1]/t,e[2]/t]}}const oA=.5,Pl=40,lA=4e5,Ws=Math.PI/180,Gr=180/Math.PI;class Fn{static localDirection(e,t,n,i=new P){const s=Math.tan(t/2*Ws);return i.set((e.u*2-1)*s*n,(1-e.v*2)*s,-1).normalize()}static picturePoint(e,t,n){if(e.z>=0)return;const i=Math.tan(t/2*Ws),s=e.x/-e.z/(i*n),a=e.y/-e.z/i;return{u:(s+1)/2,v:(1-a)/2}}static worldDirection(e,t=new P){const n=e.azimuthDeg*Ws,i=e.altitudeDeg*Ws;return t.set(Math.sin(n)*Math.cos(i),Math.sin(i),-Math.cos(n)*Math.cos(i))}static aimOf(e){const t=Math.hypot(e.x,e.z);return{azimuthDeg:(Math.atan2(e.x,-e.z)*Gr+360)%360,altitudeDeg:Math.atan2(e.y,t)*Gr}}static rotationOf(e){const t=new xt;return t.rotation.set(e.pitchDeg*Ws,-e.headingDeg*Ws,-(e.rollDeg??0)*Ws,"YXZ"),t.quaternion.clone()}static anglesOf(e){const t=new Fi().setFromQuaternion(e,"YXZ"),n=(-t.y*Gr%360+360)%360,i=-t.z*Gr;return{headingDeg:n,pitchDeg:t.x*Gr,rollDeg:Math.abs(i)<1e-9?0:i}}static worldDirectionOf(e,t,n,i=new P){return this.localDirection(e,t.fovDeg,n,i).applyQuaternion(this.rotationOf(t))}static picturePointOf(e,t,n){const i=e.clone().applyQuaternion(this.rotationOf(t).invert()),s=this.picturePoint(i,t.fovDeg,n);if(!(!s||s.u<0||s.u>1||s.v<0||s.v>1))return s}static solve(e,t,n,i=e.length>=3){if(e.length<2)return;if(!i)return this.solveAtField(e,t,n);let s=1,a=179;const o=(Math.sqrt(5)-1)/2;let l=a-o*(a-s),c=s+o*(a-s),h=this.solveAtField(e,t,l),d=this.solveAtField(e,t,c);for(let f=0;f<60&&a-s>1e-4;f++){if(!h||!d)return;h.residualDeg<d.residualDeg?(a=c,c=l,d=h,l=a-o*(a-s),h=this.solveAtField(e,t,l)):(s=l,l=c,h=d,c=s+o*(a-s),d=this.solveAtField(e,t,c))}return h&&d?h.residualDeg<d.residualDeg?h:d:h??d}static solveAtField(e,t,n){const i=e.map(c=>this.localDirection(c.picture,n,t)),s=e.map(c=>this.worldDirection(c.scene)),a=this.triad(i,s);if(!a)return;const o=this.refine(a,i,s);return{registration:{...this.anglesOf(o),fovDeg:n},residualDeg:this.residualDeg(o,i,s)}}static triad(e,t){let n=0,i=1,s=-1;for(let h=0;h<e.length;h++)for(let d=h+1;d<e.length;d++){const u=e[h].clone().cross(e[d]).lengthSq();u>s&&(s=u,n=h,i=d)}if(s<1e-12)return;const a=(h,d)=>{const u=h.clone().normalize(),f=h.clone().cross(d).normalize(),p=f.clone().cross(u);return new Be().set(u.x,p.x,f.x,u.y,p.y,f.y,u.z,p.z,f.z)},o=a(e[n],e[i]),c=a(t[n],t[i]).multiply(o.transpose());return new Oi().setFromRotationMatrix(new Ve().setFromMatrix3(c))}static refine(e,t,n){const i=e.clone(),s=new P;for(let a=0;a<20;a++){const o=new Be().set(0,0,0,0,0,0,0,0,0),l=o.elements,c=new P;for(let f=0;f<t.length;f++){s.copy(t[f]).applyQuaternion(i);const p=s,v=[[0,p.z,-p.y],[-p.z,0,p.x],[p.y,-p.x,0]],m=[n[f].x-p.x,n[f].y-p.y,n[f].z-p.z];for(let g=0;g<3;g++){for(let M=0;M<3;M++)for(let x=0;x<3;x++)l[M*3+g]+=v[x][g]*v[x][M];c.setComponent(g,c.getComponent(g)+v[0][g]*m[0]+v[1][g]*m[1]+v[2][g]*m[2])}}for(let f=0;f<3;f++)l[f*3+f]+=1e-9;const h=c.applyMatrix3(o.invert()),d=h.length();if(d<1e-12)break;const u=new Oi().setFromAxisAngle(h.normalize(),d);if(i.premultiply(u).normalize(),d<1e-10)break}return i}static residualDeg(e,t,n){let i=0;const s=new P;for(let a=0;a<t.length;a++){s.copy(t[a]).applyQuaternion(e);const o=s.angleTo(n[a])*Gr;i+=o*o}return Math.sqrt(i/t.length)}}const Cm=6371e3,Va=Math.PI/180;class ea{constructor(e=t=>fetch(t).then(n=>{if(!n.ok)throw new Error(`${t}: HTTP ${n.status}`);return n.json()})){this.fetchJson=e}static API="https://api.panoramax.xyz/api";static CREDIT="Panoramax";static CREDIT_URL="https://panoramax.fr/";async nearby(e,t,n=300,i=50){const s=n/111320,a=n/(111320*Math.cos(e*Va)),o=[t-a,e-s,t+a,e+s].map(h=>h.toFixed(6)).join(",");return((await this.fetchJson(`${ea.API}/search?bbox=${o}&limit=${i}`)).features??[]).map(h=>this.picture(h,e,t)).filter(h=>h!==void 0&&h.distanceM<=n).sort((h,d)=>h.distanceM-d.distanceM)}picture(e,t,n){const[i,s]=e.geometry.coordinates,a=e.assets.sd?.href??e.assets.hd?.href;if(!a)return;const{distanceM:o,bearingDeg:l}=ea.offset(t,n,s,i),c=e.properties,h=c["pers:interior_orientation"]?.field_of_view,d=(c.providers??[]).map(f=>f.name).filter(f=>!!f),u=c.license??"CC-BY-SA-4.0";return{id:e.id,lat:s,lng:i,distanceM:o,bearingDeg:l,azimuthDeg:c["view:azimuth"],panorama:h!==void 0&&h>=360,takenAt:c.datetime??"",src:a,srcFull:e.assets.hd?.href,credit:`${ea.CREDIT}${d.length?` — ${d.join(", ")}`:""} (${u})`,creditUrl:`${ea.API.replace(/\/api$/,"")}/#focus=pic&pic=${e.id}`}}static offset(e,t,n,i){const s=(n-e)*Va*Cm,a=(i-t)*Va*Cm*Math.cos((e+n)/2*Va);return{distanceM:Math.hypot(a,s),bearingDeg:(Math.atan2(a,s)/Va+360)%360}}}const Ll=36e5,Rm=25;class Yh{constructor(e){this.provider=e}async infer(e){const t=this.questionOf(e);if(!t)return{status:"incomplete"};const{origin:n,start:i}=t,s=ua(e.event)??0,a=this.sampleTimings(e,i,s);let o;try{o=await this.provider.getWeather({points:a.map(l=>this.pointAt(e,l,n))})}catch{return{status:"failed",at:i}}return o?{status:"inferred",at:i,source:o.source,keyframes:o.samples.map((l,c)=>({t:a[c].t,weather:l.weather}))}:{status:"unavailable",at:i}}applyTo(e,t){if(!(t.status!=="inferred"||!t.keyframes||!t.source)){e.weatherTrack.clear();for(const n of t.keyframes)e.weatherTrack.addKeyframe(n.t,n.weather);e.weatherSource=t.source}}sampleTimes(e,t){const n=[e],i=e.getTime()+t;let s=Math.floor(e.getTime()/Ll)*Ll+Ll;for(;s<=i&&n.length<Rm;)n.push(new Date(s)),s+=Ll;return t>0&&n[n.length-1].getTime()!==i&&n.length<Rm&&n.push(new Date(i)),n}sampleTimings(e,t,n){const i=e.timeline.duration>0?e.timeline.duration:n;return n<=0||i<=0?[{time:t,t:0}]:this.sampleTimes(t,n).map(s=>{const a=(s.getTime()-t.getTime())/n;return{time:s,t:Math.round(i*Math.max(0,Math.min(1,a)))}})}canInfer(e){return this.questionOf(e)!==void 0}questionOf(e){const t=this.originOf(e);if(!t)return;const n=e.event.time;if(n?.year===void 0||n.month===void 0||n.day===void 0)return;const i=Ds(n,t.lng,e.event.utcOffsetHours);return i?{origin:t,start:i}:void 0}originOf(e){const t=tt(e,0),n=e.event.place?.[0],i=t?.lat??n?.lat,s=t?.lng??n?.lng;return i===void 0||s===void 0?void 0:{lat:i,lng:s}}pointAt(e,t,n){const i=tt(e,t.t);return{lat:i?.lat??n.lat,lng:i?.lng??n.lng,time:t.time}}}const cA=Date.UTC(1940,0,1),Pm=36e5,Lm=.25,hA=.7,dA=.45,uA=.1,fA=2,pA=.3,mA=.2,gA=8,$h=.125,vA=.05,km=125,Nm=100,Om=2500,Kh=3500,Zh=8e3,yA=95,bA=99,wA=[96,99],xA=["cloud_cover","cloud_cover_low","cloud_cover_mid","cloud_cover_high","precipitation","snowfall","weather_code","wind_speed_10m","wind_direction_10m","temperature_2m","dew_point_2m"];class Lv{fetchImpl;baseUrl;cache=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.baseUrl=e.baseUrl??"https://archive-api.open-meteo.com/v1/archive"}async getWeather(e){if(e.points.length===0)return;const t=e.points.map(f=>f.time.getTime()),n=Math.min(...t);if(n<cA)return;const i=new Map;for(const f of e.points){const p=this.cellKey(f);i.has(p)||i.set(p,{lat:f.lat,lng:f.lng,index:i.size})}const s=this.requestUrl([...i.values()],new Date(n),new Date(Math.max(...t))),a=this.cache.get(s);if(a)return a;const o=await this.fetchImpl(s);if(!o.ok)throw new Error(`Open-Meteo HTTP ${o.status}`);const l=await o.json(),c=Array.isArray(l)?l:[l];if(c.length<i.size||c.some(f=>f.error||!f.hourly))return;const h={id:"era5",name:"ERA5 (Open-Meteo)",url:s},d=e.points.map(f=>this.sampleAt(c[i.get(this.cellKey(f)).index].hourly,f.time));if(d.some(f=>f===void 0))return;const u={samples:d,source:h};return this.cache.set(s,u),u}cellKey(e){return`${Math.round(e.lat/Lm)},${Math.round(e.lng/Lm)}`}requestUrl(e,t,n){const i=new URLSearchParams({latitude:e.map(s=>s.lat).join(","),longitude:e.map(s=>s.lng).join(","),start_date:this.isoDate(t),end_date:this.isoDate(n),hourly:xA.join(","),wind_speed_unit:"ms",timezone:"UTC"});return`${this.baseUrl}?${i}`}isoDate(e){return e.toISOString().slice(0,10)}sampleAt(e,t){const n=this.recordAt(e,t);return n&&{time:t,weather:this.toWeather(n)}}recordAt(e,t){const n=e.time.map(o=>Date.parse(`${o}Z`)),i=t.getTime();if(n.length===0||i<n[0]-Pm||i>n[n.length-1]+Pm)return;if(i<=n[0])return this.recordFrom(e,0);if(i>=n[n.length-1])return this.recordFrom(e,n.length-1);let s=0;for(;s+1<n.length&&n[s+1]<=i;)s++;const a=n[s+1]-n[s];return this.blendRecords(this.recordFrom(e,s),this.recordFrom(e,s+1),a>0?(i-n[s])/a:0)}recordFrom(e,t){const n={cloudCover:e.cloud_cover[t]/100,cloudCoverLow:e.cloud_cover_low[t]/100,cloudCoverMid:e.cloud_cover_mid[t]/100,cloudCoverHigh:e.cloud_cover_high[t]/100,precipitationMm:e.precipitation[t],snowfallCm:e.snowfall[t],weatherCode:e.weather_code[t],windSpeedMs:e.wind_speed_10m[t],windFromDeg:e.wind_direction_10m[t],temperatureC:e.temperature_2m[t],dewPointC:e.dew_point_2m[t]};return Object.values(n).some(i=>i===void 0||Number.isNaN(i))?void 0:n}blendRecords(e,t,n){if(!e||!t)return e??t;const i=(a,o)=>a+(o-a)*n,s=((t.windFromDeg-e.windFromDeg)%360+540)%360-180;return{cloudCover:i(e.cloudCover,t.cloudCover),cloudCoverLow:i(e.cloudCoverLow,t.cloudCoverLow),cloudCoverMid:i(e.cloudCoverMid,t.cloudCoverMid),cloudCoverHigh:i(e.cloudCoverHigh,t.cloudCoverHigh),precipitationMm:i(e.precipitationMm,t.precipitationMm),snowfallCm:i(e.snowfallCm,t.snowfallCm),weatherCode:n<.5?e.weatherCode:t.weatherCode,windSpeedMs:i(e.windSpeedMs,t.windSpeedMs),windFromDeg:((e.windFromDeg+s*n)%360+360)%360,temperatureC:i(e.temperatureC,t.temperatureC),dewPointC:i(e.dewPointC,t.dewPointC)}}cloudLayersFrom(e){return[{id:"record-low",type:"unknown",baseM:Math.round(this.clamp(km*(e.temperatureC-e.dewPointC),Nm,Om)),thicknessM:650,coverage:this.clamp(e.cloudCoverLow,0,1),sizeM:1400,density:1},{id:"record-mid",type:"unknown",baseM:Kh,thicknessM:800,coverage:this.clamp(e.cloudCoverMid,0,1),sizeM:2500,density:1},{id:"record-high",type:"cirrus",baseM:Zh,thicknessM:400,coverage:this.clamp(e.cloudCoverHigh,0,1),sizeM:2200,density:.35}]}toWeather(e){const t=e.weatherCode>=yA&&e.weatherCode<=bA,n=this.precipitationTypeFrom(e);return{cloudLayers:this.cloudLayersFrom(e),cloudCover:this.clamp(e.cloudCover,0,1),cloudDarkness:this.cloudDarknessFrom(e,t),cloudBaseM:this.cloudBaseFrom(e),highCloudCover:e.cloudCoverHigh,lowerCloudCover:Math.max(e.cloudCoverLow,e.cloudCoverMid),precipitationType:n,precipitationIntensity:n==="none"?0:this.clamp(Math.sqrt(e.precipitationMm/gA),0,1),windDirectionDeg:(e.windFromDeg+180)%360,windSpeed:e.windSpeedMs,storm:t}}precipitationTypeFrom(e){return e.snowfallCm>0?"snow":wA.includes(e.weatherCode)?"hail":e.precipitationMm>0?"rain":"none"}cloudDarknessFrom(e,t){const n=e.cloudCoverLow+e.cloudCoverMid+e.cloudCoverHigh;if(n<=0)return 0;const i=(hA*e.cloudCoverLow+dA*e.cloudCoverMid+uA*e.cloudCoverHigh)/n,s=Math.min(1,e.precipitationMm/fA);return this.clamp(i+pA*s+(t?mA:0),0,1)}cloudBaseFrom(e){if(e.cloudCover<vA)return;const t=this.clamp(km*(e.temperatureC-e.dewPointC),Nm,Om);if(e.cloudCoverLow>=$h)return Math.round(t);if(e.cloudCoverMid>=$h)return Kh;if(e.cloudCoverHigh>=$h)return Zh;const n=Math.max(e.cloudCoverLow,e.cloudCoverMid,e.cloudCoverHigh);if(!(n<=0))return n===e.cloudCoverLow?Math.round(t):n===e.cloudCoverMid?Kh:Zh}clamp(e,t,n){return Math.max(t,Math.min(n,e))}}function MA(){return new Lv}const SA=5;class kv{attribution={text:"© OpenStreetMap",url:"https://osm.org/copyright"};fetchImpl;baseUrl;reverseUrl;cache=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.baseUrl=e.baseUrl??"https://nominatim.openstreetmap.org/search",this.reverseUrl=e.reverseUrl??"https://nominatim.openstreetmap.org/reverse"}async reverse(e,t,n={}){const i=new URLSearchParams({lat:String(e),lon:String(t),format:"jsonv2"});n.language&&i.set("accept-language",n.language);const s=`${this.reverseUrl}?${i}`,a=this.cache.get(s);if(a)return a[0];const o=await this.fetchImpl(s,{signal:n.signal});if(!o.ok)throw new Error(`Nominatim HTTP ${o.status}`);const l=await o.json(),c=l.error?void 0:this.toMatch(l);return this.cache.set(s,c?[c]:[]),c}async search(e,t={}){const n=e.trim();if(n==="")return[];const i=this.requestUrl(n,t),s=this.cache.get(i);if(s)return s;const a=await this.fetchImpl(i,{signal:t.signal});if(!a.ok)throw new Error(`Nominatim HTTP ${a.status}`);const o=await a.json(),l=(Array.isArray(o)?o:[]).map(c=>this.toMatch(c)).filter(c=>c!==void 0);return this.cache.set(i,l),l}requestUrl(e,t){const n=new URLSearchParams({q:e,format:"jsonv2",limit:String(t.limit??SA)});return t.language&&n.set("accept-language",t.language),`${this.baseUrl}?${n}`}toMatch(e){const t=e.display_name??e.name,n=this.coordinate(e.lat),i=this.coordinate(e.lon);return t&&n!==void 0&&i!==void 0?{name:t,lat:n,lng:i}:void 0}coordinate(e){if(e===void 0||e.trim()==="")return;const t=Number(e);return Number.isFinite(t)?t:void 0}}function _A(){return new kv}const EA=[{id:"nominatim",name:"Nominatim",credit:"© OpenStreetMap",creditUrl:"https://osm.org/copyright",create:()=>new kv}],TA=[{id:"era5",name:"ERA5 (Open-Meteo)",credit:"© Copernicus/ECMWF",creditUrl:"https://open-meteo.com/en/docs/historical-weather-api",create:()=>new Lv}];class AA{attribution;fetchImpl;tileUrlTemplate;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis);const t=e.year??2024;this.tileUrlTemplate=`https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-${t}_3857/default/g/{z}/{y}/{x}.jpg`,this.attribution=`EOxCloudless https://cloudless.eox.at by EOX IT Services GmbH (Contains modified Copernicus Sentinel data ${t})`}async getImageryTexture(e,t){return ag(e,t,n=>this.tileUrlTemplate.replace("{z}",String(n.z)).replace("{y}",String(n.y)).replace("{x}",String(n.x)),this.fetchImpl)}}const jh=[{id:"aws-terrarium",name:"AWS Terrain Tiles",credit:"© AWS Open Data (SRTM, ETOPO1)",creditUrl:"https://registry.opendata.aws/terrain-tiles/",create:()=>new rg}],Fm=[{id:"esri-world",name:"Esri World Imagery",credit:"Imagery © Esri, Maxar, Earthstar Geographics, and the GIS User Community",creditUrl:"https://www.arcgis.com/home/item.html?id=10df2279f9684e4a9f6a7f08febac2a9",create:()=>new og},{id:"eox-s2cloudless",name:"EOX Sentinel-2 cloudless",credit:"EOxCloudless by EOX IT Services GmbH (contains modified Copernicus Sentinel data)",creditUrl:"https://cloudless.eox.at",create:()=>new AA}];class pf{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const n=pf.SPAN_DEG;try{const s=(await this.provider.getElevationGrid({south:e-n,north:e+n,west:t-n,east:t+n},{width:2,height:2})).heights[0];return Number.isFinite(s)?s:void 0}catch{return}}}class IA{available(){const e=Intl.supportedValuesOf;return e?[...e.call(Intl,"timeZone")].sort():[]}offsetHoursAt(e,t){if(t.year===void 0)return;const n=Date.UTC(t.year,(t.month??1)-1,t.day??1,t.hour??12,t.minute??0,t.second??0),i=this.zoneOffsetHours(e,new Date(n));if(i!==void 0)return this.zoneOffsetHours(e,new Date(n-i*36e5))??i}zoneOffsetHours(e,t){let n;try{n=new Intl.DateTimeFormat("en-US",{timeZone:e,timeZoneName:"longOffset"}).formatToParts(t).find(s=>s.type==="timeZoneName")?.value??""}catch{return}const i=/^GMT(?:([+-])(\d{2}):(\d{2}))?$/.exec(n);if(i)return i[1]?(i[1]==="-"?-1:1)*(Number(i[2])+Number(i[3])/60):0}}function Wr(r,e){return r.find(t=>t.id===e)??r[0]}class DA{constructor(e="https://api.open-meteo.com/v1/forecast"){this.endpoint=e}async zoneAt(e,t){const n=new URL(this.endpoint);n.searchParams.set("latitude",String(e)),n.searchParams.set("longitude",String(t)),n.searchParams.set("timezone","auto"),n.searchParams.set("forecast_days","1");try{const i=await fetch(n.toString());if(!i.ok)return;const s=await i.json();return s.timezone&&s.timezone!=="GMT"?s.timezone:void 0}catch{return}}}const CA=[{id:"open-meteo",name:"Open-Meteo",credit:"© Open-Meteo",creditUrl:"https://open-meteo.com/en/docs",create:()=>new DA}],RA={color:"Color",transparency:"Transparency",halo:"Halo",blur:"Blur",brightness:"Brilliance",shapeTitle:"Name",utcOffset:"Time zone",cloudBase:"Cloud base",elevation:"Altitude",heightAboveGround:"Height above ground",duration:"Duration",placeName:"Place",latitude:"Latitude",longitude:"Longitude",heading:"Heading",pitch:"Tilt",roll:"Roll",observationTime:"Observation start",observationEndTime:"Observation end",assessmentGroup:"Assessment",assessmentNames:{coverage:"Witness info"},assessmentVerdicts:{"hynek.nl":"NL — nocturnal light","hynek.dd":"DD — daylight disc","hynek.rv":"RV — radar-visual","hynek.ce1":"CE1 — close encounter","hynek.ce2":"CE2 — with a physical trace","hynek.ce3":"CE3 — with entities"},witnessGroup:"Witness",witnessId:"ID",witnessTitle:"Title",witnessLastName:"Last name",witnessFirstNames:"First names",caseId:"Case ID",tags:"Tags",cloudCover:"Cloud cover",highCloudCover:"Ice cloud (cirrus)",focalLength:"Focal length",fieldOfView:"Field of view",aperture:"Aperture",exposure:"Exposure",focusDistance:"Focused at",iceCrystalAlignment:"Crystal alignment",cloudDarkness:"Cloud darkness",precipitationType:"Precipitation",precipitationNone:"None",precipitationRain:"Rain",precipitationSnow:"Snow",precipitationHail:"Hail",precipitationIntensity:"Intensity",windDirection:"Wind direction",windSpeed:"Wind speed",storm:"Storm",cloudsGroup:"Clouds",precipitationGroup:"Precipitation",windGroup:"Wind",soundKind:"Sound",soundNone:"None (silent)",soundHum:"Hum",soundWhistle:"Whistle",soundRumble:"Rumble",soundCrackle:"Crackle",soundVolume:"Loudness",soundPitch:"Pitch",soundSrc:"Recording",instrument:"Observed through",decorAircraft:"Aircraft",decorEntity:"Being",decorAltitude:"Altitude",decorLights:"Lights",decorLightsNone:"none",decor:"Environment",decorBuilding:"Building",decorTree:"Tree",decorCrop:"Crop row",decorMound:"Stone heap",decorStreetlight:"Streetlight",decorVehicle:"Vehicle",decorWitness:"Other witness",decorEast:"Distance east",decorNorth:"Distance north",decorHeading:"Heading",decorColor:"Colour",decorLit:"Lit",decorTitle:"Name",milestones:"Moments",milestoneLabel:"Label",milestoneNote:"What happens",addMilestone:"Name this moment",deleteMilestone:"Delete moment",confirmAccept:"Delete",confirmDecline:"Cancel",decorWidth:"Width",decorLength:"Length",decorHeight:"Height",decorModel:"3D model",decorModelNone:"Built-in shape",decorModelAdvanced:"Model from an address",decorModelUrl:"glTF/GLB address",decorModelTitle:"Model name",decorModelAuthor:"Author",decorModelLicense:"Licence",decorModelSource:"Where it came from",decorFloors:"Floors",decorOccupiedFloor:"Occupied floor",decorWitnessSide:"Witness location",decorWitnessSideNone:"Not present",decorWindows:"Windows",decorSideFront:"Front",decorSideBehind:"Behind",decorSideLeft:"Left",decorSideRight:"Right",decorSideFrontLeft:"Front-left",decorSideFrontRight:"Front-right",decorSideBehindLeft:"Behind-left",decorSideBehindRight:"Behind-right"},Nv={...RA,oval:"Oval",polygon:"Polygon",addVertex:"Add vertex",deleteVertex:"Delete vertex",notAPolygon:"Select a single polygon shape",tooFewVertices:"A shape needs at least 3 points",shape:"Shape",apparentWidth:"Apparent width",realWidth:"Real width",distance:"Distance",sizeLock:"Hold",lockNone:"nothing",lockApparent:"the apparent width",lockReal:"the real width",lockDistance:"the distance",apparentSize:"{moons}× the Moon",utcOffsetPlaceholder:"from longitude",realSizeBetween:"The scene bounds that width: between {min} and {max} m, from what it crosses",realSizeAtLeast:"The scene bounds that width: at least {min} m, from what it passes behind",realSizeAtMost:"The scene bounds that width: at most {max} m, from what it passes in front of",realSizeUnknown:"Nothing in the scene bounds that width: it is only what the distance implies",realSizeOutside:" — the width above is outside that",blurBound:"Blurred through this lens: nearer than {max} m",blurBoundNoInstrument:"Blur through the naked eye bounds no distance — an eye has no aperture to be out of focus with",blurBoundNotAtInfinity:"Blur bounds a distance only for a lens focused at infinity: this one is focused at {focus} m, which blurs on both sides of it",realSizeContradiction:"Contradiction: the declared crossings cannot all be true",realDistanceHere:" — i.e. between {min} and {max} m here",clearDistanceHypothesis:"Withdraw the distance hypothesis",clearDistanceHypothesisTitle:"Back to what the recording establishes",depthStated:"Drawn at {m} m, as the recording states",depthHypothesis:"Drawn at {m} m: your hypothesis — what the decor hides of it is what a thing that far would lose",depthDerived:"Drawn at {m} m, from the witness's own walk",depthBounded:"Drawn at {m} m, from what it passes behind and in front of",depthConventional:"Drawn at {m} m by convention: nothing in the recording establishes a distance",addShape:"Add shape",deleteShape:"Delete shape",play:"Play",pause:"Pause",noDuration:"No observation duration",autoReplay:"Auto-replay",group:"Group",ungroup:"Ungroup",bringToFront:"Bring to front",sendToBack:"Send to back",contextMenuDelete:"Delete",confirmDeleteShape:"Delete {name}? This can't be undone.",confirmDeleteShapes:"Delete {count} shapes? This can't be undone.",confirmDeleteMilestone:"Stop naming moment {name}? The recording itself is unchanged.",onlyOneShape:"There is only one shape",alreadyAtFront:"This shape is already at the front",alreadyAtBack:"This shape is already at the back",needTwoShapesToGroup:"Select at least two shapes to group them",notGrouped:"This shape isn't part of a group",multipleShapesSelected:"Multiple shapes selected — select just one to edit this",samplingRate:"Sampling rate",currentPosition:"Current position",switchToElapsed:"click to show elapsed time",switchToClockTime:"click to show the time of day",durationPlaceholder:"observation length",durationImprecise:"These dates don't precisely enough determine a duration — enter it manually.",export:"Export",importFile:"Load JSON file",importUrl:"Or load from URL",importUrlPlaceholder:"https://…/sighting.json",importButton:"Load",importError:"Couldn't load that recording — check the file or URL and try again.",importErrorCors:'That address answers, but the browser is not allowed to read it from this page. The file itself is fine — its server needs to send the header "Access-Control-Allow-Origin: *" with it. If it is not your server, that is what to ask its administrator for.',importErrorMixedContent:"A secure page cannot load an address starting with http://. Use https:// if that server offers it.",importErrorUnreachable:"Nothing answered at that address. Check the spelling, and that you are online.",importErrorStatus:"That server answered with an error ({status}). The address is probably wrong, or the file has moved.",importErrorMalformed:"That address answered, but what came back is not a recording.",record:"Record",stop:"Stop",according:"according to",sourceElevation:"Relief",sourceImagery:"Imagery",placeNamePlaceholder:"Valensole, France",searchPlace:"Locate",placeMatch:"Matches",placeSearching:"Looking up the place…",placeMatchFound:"place found",placeMatchesFound:"places found",placeNotFound:"No place by that name",placeSearchFailed:"Place search temporarily unavailable",utcOffsetImplausible:"This time zone doesn't match the longitude entered, whose own solar time is UTC{solar} — yet the scene and the weather record both obey what is declared here. Clear the field to derive it from the longitude.",timeZoneManual:"offset entered",altitudeAboveSeaLevel:"The witness's altitude above sea level — the ground at the location entered sets its floor: a witness in the Alps is not at 0 m.",groundAt:"ground at {m} m",headingPlaceholder:"unknown",edtfInvalid:"Not a valid EDTF date/time (e.g. 1965-07-01T05:00, 2025-06?, 2025~).",edtfPlaceholder:"YYYY-MM-DDThh:mm[?~%] or hh:mm",observationTimeHint:"EDTF — e.g. 1965-07-01T05:00, 2025-06? (uncertain), 2025~ (approximate), or just 05:00 if the date isn't known",observationEndTimeHint:"EDTF — e.g. 1965-07-01T05:10, 2025-06? (uncertain), 2025~ (approximate), or just 05:10 if the date isn't known",presetsGroupLabel:"UFO shape",witnessDirName:"Dir name",description:"Description",tagsPlaceholder:"comma-separated",weather:"Weather",shapeGroup:"Phenomenon",soundGroup:"Sound",temporalGroup:"Moment",timeQualifierExact:"Exact",timeQualifierApproximate:"Approximate",timeQualifierUncertain:"Uncertain",timeQualifierBoth:"Uncertain and approximate",edtfModeTitle:"Type an imprecise date instead: a year alone, a month, a time with no date",locationGroup:"Location",observationGroup:"Observation",weatherWhilePlaying:"Pause the recording to state the weather — while it plays, the instant these would be written at is moving",weatherInferred:"From weather records",weatherInferredTitle:"Weather isn't testimony: it's a measurable fact, on record for the observation's own date, time and place. Uncheck to state the conditions the witness reported, which then override the record.",weatherLookingUp:"Looking up the record…",weatherNeedsDateAndPlace:"A full date and a place are needed to look up the record",weatherNoRecord:"No record for this date and place",weatherLookupFailed:"Weather records temporarily unreachable",instrumentOutOfPeriod:"{name} — not of this date",unitMillimetres:"mm",unitDegrees:"°",soundSrcPlaceholder:"URL of a real recording",referenceGroup:"Pictures",reference:"Picture",referenceTitle:"Name",referenceSrc:"Address",referenceSrcPlaceholder:"https://…/photo.jpg",referenceKind:"Kind",referencePhoto:"Photo",referencePanorama:"Panorama (360°)",referenceCredit:"Credit",referenceCreditUrl:"Credit link",referenceT:"Taken at",referenceDrawing:"Drawn on",referenceOpacity:"Opacity",referenceHeading:"Heading",referencePitch:"Pitch",referenceRoll:"Roll",referenceFov:"Vertical field",referenceUsePose:"Use the witness's pose",addReferenceUrl:"Add from an address",addReferenceFile:"Add a file",deleteReference:"Delete picture",referenceEmbedded:"{kb} kB embedded in the recording — an address would keep it light",referenceUnreachable:"The picture could not be loaded: check the address, and that its site allows other sites to read it",referenceRegisterHint:"Drag to turn the picture, wheel to change its field; “Add a landmark” to point at a detail on the picture, then at the same one in the render",referenceLandmarkPicture:"Landmark {n}: click the point on the picture",referenceLandmarkScene:"Landmark {n}: click the same point in the render",referenceLandmarkOffPicture:"That click is not on the picture",referenceNotLoaded:"The picture has not arrived yet",referenceLandmarksFit:"{n} landmarks — {deg}° off on average",referenceLandmarks:"Landmarks",addReferenceLandmark:"Add a landmark",deleteReferenceLandmark:"Delete landmark",referenceLandmarkLabel:"Name",referenceLandmarkLabelPlaceholder:"Masking tree, fence…",referenceAdoptPose:"Adopt as the witness's pose",referenceAdoptRationale:"Measured on the picture “{title}”: {n} landmarks lined up, {deg}° of residual",referenceStreetSearch:"Street-level pictures nearby",referenceStreetSearching:"Looking for pictures taken nearby…",referenceStreetNone:"No street-level picture within {m} m (Panoramax)",referenceStreetFailed:"Panoramax could not be reached",referenceStreetAdd:"Add",referenceStreetItem:"{distance} m at {bearing}°, {date}{panorama}",referenceStreetPanorama:" — 360°",referenceStreetTitle:"Street-level picture {distance} m away at {bearing}°, {date}",skyLine:"Sky: {parts}",skyStarsEye:"stars down to magnitude {limit}, which is as faint as an eye went under this sky",skyStarsDeeper:"stars down to magnitude {limit} through a {device} — {gain} magnitudes past the {eye} the witness's own eyes reached",skyStarsShallower:"stars down to magnitude {limit} through a {device} — {gain} magnitudes short of the {eye} the witness's own eyes reached",skyStarsCatalogue:", drawn to {catalogue}, where this project's catalogue stops",skyStarsNone:"no star could be picked out of a sky this bright",skyDetails:"Show the records in full",skyDetailsHide:"Hide the records",skyShowerActive:"{name} — radiant {altitude}° above the horizon, {bearing} — about {rate}/h under this sky, over a sporadic background of {sporadic}/h",skyShowerBelowHorizon:"{name} is active, but its radiant is below the horizon — it can have produced nothing",skyNothingActive:"no meteor shower active on this date — a sporadic background of about {sporadic}/h",showMeteor:"Show me one",skyComet:"{name}, magnitude {magnitude}, {altitude}° above the horizon {bearing}, tail {tail}° long",skyCometNoTail:"{name}, magnitude {magnitude}, {altitude}° above the horizon {bearing}",skyCometBelowHorizon:"{name} was there at magnitude {magnitude}, but below the horizon — nobody here saw it",skyCometInDaylight:"{name}, magnitude {magnitude}, {altitude}° above the horizon {bearing} — but only {elongation}° from the Sun",showComet:"Show me the comet",skySatellitePasses:"{count} satellites crossed this sky bright enough to be seen, the brightest {name}, magnitude {magnitude}, {altitude}° above the horizon {bearing} at {time}",skySatellitePassesOne:"one satellite crossed this sky bright enough to be seen: {name}, magnitude {magnitude}, {altitude}° above the horizon {bearing} at {time}",skySatelliteTrain:"among them a train of {count} Starlinks launched on {date}",skySatellitePassesNone:"by the orbital elements archived for that date, no lit satellite crossed this sky brightly enough to be seen",skySatelliteElementsGap:"no orbital elements archived near that date",showSatellite:"Show me a satellite",skyOpticsPossible:"ice cloud enough, around the {source}, for {forms}",skyOpticsAlignment:" — everything but the rings needs crystals falling level, stated here at {alignment}% since no record holds it",skyOpticsHalo22:"a {angle}° ring",skyOpticsHalo46:"a {angle}° ring",skyOpticsParhelia:"sundogs {angle}° to either side",skyOpticsTangentArc:"an arc tangent on top of it",skyOpticsParhelicCircle:"a white circle right round the sky at its own height",skyOpticsCircumzenithal:"a circumzenithal arc {angle}° up",skyOpticsCircumhorizontal:"a circumhorizontal arc far below it",skyOpticsPillar:"a pillar standing over it",skyOpticsNoIce:"no ice cloud: no halo and no sundogs",skyOpticsHidden:"ice cloud above, but a lower deck between it and the witness",skyOpticsSun:"Sun",skyOpticsMoon:"Moon",skyBowPossible:"rain and sunlight enough for {forms}",skyBowMoon:"rain under a Moon {lit}% lit, enough for {forms} — a moonbow, which the eye sees as a white arc",skyGlowBand:"the Milky Way {contrast}× the sky behind it, {altitude}° up {bearing}",skyGlowCone:"the zodiacal light {contrast}× the sky behind it, {altitude}° up {bearing}, {elongation}° from the Sun — a leaning cone with no edge, gone within the hour",skyGlowZodiacalBand:"the zodiacal band {contrast}× the sky behind it, {altitude}° up {bearing} — the whole ecliptic faintly alight, which is not the sight people report",skyGlowMoon:"no Milky Way and no zodiacal light: a Moon {lit}% lit held the sky at {sky} magnitudes a square arcsecond, where they need 22",skyGlowTwilight:"no Milky Way and no zodiacal light: twilight still held the sky at {sky} magnitudes a square arcsecond, where they need 22",skyGlowNothingUp:"sky dark enough ({sky} magnitudes a square arcsecond) but neither the galactic plane nor the ecliptic stood high enough in it",skyBowPrimary:"a bow {radius}° across, its top {top}° up",skyBowSecondary:"a second, fainter one at {radius}° with its colours reversed",skyBowSourceTooHigh:"rain, but with the source {altitude}° up no bow could clear the horizon: they stand {radius}° from the point opposite it",skyBowHidden:"rain, but an unbroken deck between it and the light: no bow",skyBowNoSource:"rain, and nothing lit to make a bow of it",skySatellitesLit:"the Earth's shadow stood {height} km above the witness, so low orbit was still in sunlight — {count} tracked objects were in orbit that month",skySatellitesLitWith:"the Earth's shadow stood {height} km above the witness, so low orbit was still in sunlight — {count} tracked objects were in orbit that month, among them {eras}",skySatellitesShadowed:"the Earth's shadow stood {height} km above the witness: of the {count} tracked objects in orbit that month, nothing in low orbit was lit",skySatellitesNotYet:"nothing had been put in orbit yet",skySatellitesDaylight:"everything in orbit was sunlit, as it always is by day, and {eras} could outshine even this sky",skySatellitesDaylightOne:"everything in orbit was sunlit, as it always is by day, and {eras} could outshine even this sky",skyUnknown:"cannot be worked out without a date and a place",lookAtDecor:"Look at it",addDecor:"Add",deleteDecor:"Delete decor",decorSightingUrl:"Their own recording URL",viewTestimony:"View testimony",noWitnessRecording:"No recording URL set for this witness",masks:"Masks",addWitness:"Add witness",narrativePlaceholder:"What the witness reported, in their own words",narrativeKey:"{source} API key",narrativeNeedsKey:"Enter your own {source} API key to generate a reconstruction from the account",narrativeKeyUnlikely:"This does not look like a Claude API key: they begin with sk-ant-",narrativeWorkspace:"Workspace ID",narrativeWorkspacePlaceholder:"only if your key spans several",narrativeWorkspaceHint:"Only for a key whose scope is the whole organisation. Simpler: leave this empty and create a key scoped to one workspace instead.",narrativeNeedsAsk:"Nothing to send yet",narrativeRemember:"Remember on this device",narrativeDraft:"Generate reconstruction",narrativeStop:"Stop",narrativeWorking:"Reading the account…",narrativeApplied:"{count} fields written into the editor",narrativeUnchanged:"The account states nothing the recording can hold yet",narrativeStated:"What the witness said",narrativeDerived:"Worked out from the account",narrativeAssumed:"Guessed, so the reconstruction runs — check these",narrativeGaps:"What nothing could settle",narrativeErrorCredential:"No key, or one that was refused — check it at console.anthropic.com",narrativeErrorRateLimited:"Too many requests on your account: wait a moment and ask again",narrativeErrorRefused:"The account was not answered. Rephrasing may help; asking again will not",narrativeErrorMalformed:"The answer was not a usable draft — worth asking once more",narrativeErrorUnreachable:"Nothing answered: check the connection",narrativeErrorRejected:"Refused: {detail}",witnessAge:"Age then",witnessOccupation:"Occupation",testimonySource:"Account obtained",testimonySourceUnknown:"unknown",testimonySourceOnSite:"on-site investigation",testimonySourceInterview:"interview in person",testimonySourceTelephone:"by telephone",testimonySourceQuestionnaire:"questionnaire",testimonySourceLetter:"the witness wrote it",testimonySourcePress:"press or broadcast",testimonyFollowedUp:"Followed up",testimonyUnknown:"unknown",testimonyYes:"yes",testimonyNo:"no",questionUnanswered:"Nothing in this recording answers one of the questions a reconstruction needs settled",durationRequired:"The observation needs a length to be replayed at all — state one, or an end time, which may be approximate",questionsUnanswered:"{count} of the questions a full reconstruction answers are unanswered here"},PA=Object.freeze(Object.defineProperty({__proto__:null,sightingEditorMessages_en:Nv},Symbol.toStringTag,{value:"Module"})),Um=new Set;xc();eA();const Vr={width:48,height:28},LA=2500,kA=600,Bm=900,Xr=2e-4,NA=900,OA=-1.46,FA=3,zm=.2,UA=.01,BA=1.6,Jh=2e3,zA=250,Hm=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),vs=4,kl="ufo-1",Gm=["oval","polygon"],HA={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5,blur:0,brightness:0};function GA(r){return r.kind==="oval"?"oval":"polygon"}const WA=-6,VA=21;class Tt extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;presetButtons;presetsGroup;colorInput;transparencyInput;haloScaleInput;blurInput;brightnessInput;blurBoundOutput;sourceSelect;shapeTitleInput;utcOffsetInput;timeZoneSelect;timeZoneProvider=CA[0].create();timeZoneLookupTimer;timeZoneLookedUpAt;autoFilledTimeZone;timeZones=new IA;apparentWidthInput;realWidthInput;objectDistanceInput;sizeLockSelect;apparentSizeOutput;realSizeOutput;clearDistanceHypothesisButton;depthBasisOutput;addShapeButton;deleteShapeButton;contextMenu;contextGroupButton;contextUngroupButton;contextBringToFrontButton;contextSendToBackButton;contextDeleteButton;contextAddVertexButton;contextDeleteVertexButton;decorContextMenu;contextViewTestimonyButton;contextMasksSubmenu;labelContextMasks;playPauseButton;seekInput;timeStartLabel;timeEndLabel;loopButton;durationInput;exportButton;importFileInput;importUrlInput;importUrlButton;narrativeKeyInput;narrativeWorkspaceInput;narrativeRememberInput;narrativeDraftButton;narrativeStopButton;narrativeCreditLink;narrativeStatus;narrativeReport;placeNameInput;searchPlaceButton;placeMatchRow;placeMatchSelect;placeStatusText;placeProvider=_A();placeMatches=[];placeSearchToken=0;placeReverseTimer;namedCoordinates;latInput;lngInput;headingInput;pitchInput;rollInput;elevationInput;groundElevationOutput;weatherFromRecords=!0;groundElevationM;groundElevationFor;groundElevationTimer;groundElevationToken=0;obsTimeInput;obsTimeNativeInput;obsEndTimeNativeInput;obsTimeQualifier;obsEndTimeQualifier;edtfModeButton;edtfMode=!1;obsEndTimeInput;witnessIdInput;witnessDirNameInput;witnessTitleInput;witnessLastNameInput;witnessFirstNamesInput;witnessAgeInput;witnessOccupationInput;testimonySourceSelect;testimonyFollowedUpSelect;caseIdInput;descriptionInput;tagsInput;cloudEditor;cloudCoverInput;cloudDarknessInput;cloudBaseInput;precipitationTypeSelect;precipitationIntensityInput;windDirectionInput;windSpeedInput;stormInput;weatherInferredInput;weatherSourceText;skyCandidatesOutput;showMeteorButton;showCometButton;showSatelliteButton;weatherSourceLink;weatherFields;weatherInference=new Yh(MA());weatherLookupTimer;weatherLookupToken=0;weatherLookupPending=!1;weatherLookupResult;weatherTrackSpan;soundKindSelect;soundVolumeInput;soundPitchInput;soundPitchValue;soundSrcInput;soundFields;soundKindOptions=new Map;soundPreviewTimer;instrumentSelect;focalLengthInput;labelFocalLength;unitFocalLength;labelFNumber;labelExposure;labelFocusDistance;fNumberInput;exposureInput;focusDistanceInput;labelColor;labelTransparency;labelHalo;labelBlur;labelBrightness;labelShape;labelShapeTitle;labelUtcOffset;labelApparentWidth;labelRealWidth;labelObjectDistance;labelSizeLock;labelSamplingRate;labelDuration;placeSourceRow;weatherSourceRow;terrainSourceRows;chosenSourceId=new Map;labelPlaceName;labelPlaceMatch;labelLatitude;labelLongitude;labelHeading;labelPitch;labelRoll;labelElevation;labelObservationTime;labelObservationEndTime;labelWitnessId;labelWitnessDirName;labelWitnessTitle;labelWitnessLastName;labelWitnessFirstNames;labelWitnessAge;labelWitnessOccupation;labelTestimonySource;labelTestimonyFollowedUp;labelCaseId;labelDescription;labelTags;labelImportFile;labelImportUrl;labelNarrativeKey;labelNarrativeWorkspace;labelNarrativeRemember;groupTabs;groupPanels;paramSummary;paramSummaryBuilder;paramSummarySignature="";labelShapeGroup;labelTemporalGroup;labelLocationGroup;labelObservationGroup;labelWitnessGroup;skyDetailsButton;clampedLines;labelWeatherGroup;labelCloudCover;labelHighCloud;labelIceAlignment;highCloudCoverInput;iceCrystalAlignmentInput;labelCloudDarkness;labelCloudBase;labelPrecipitationType;labelPrecipitationIntensity;labelWindDirection;labelWindSpeed;labelStorm;labelCloudsGroup;labelPrecipitationGroup;labelWindGroup;subgroupTabs;labelWeatherInferred;labelSoundGroup;labelSoundKind;labelSoundVolume;labelSoundPitch;labelSoundSrc;labelInstrument;optionPrecipitationNone;optionPrecipitationRain;optionPrecipitationSnow;optionPrecipitationHail;decorKindSelect;addDecorWitnessButton;addDecorBuildingButton;deleteDecorButton;decorSelect;decorTitleInput;decorEastInput;decorNorthInput;decorHeadingInput;decorColorInput;decorLitInput;decorLightRigSelect;lookAtDecorButton;decorAltitudeInput;labelDecorAltitude;decorSightingUrlInput;decorModelProvider=Xl[0].create();confirmOverlay;confirmMessage;confirmAcceptButton;confirmDeclineButton;confirmAnswer;milestoneSelect;milestoneLabelInput;milestoneNoteInput;addMilestoneButton;deleteMilestoneButton;currentMilestoneT;decorWidthInput;decorLengthInput;decorHeightInput;decorModelSelect;decorModelAdvanced;decorModelUrlInput;decorModelTitleInput;decorModelAuthorInput;decorModelLicenseInput;decorModelSourceInput;decorFloorsInput;decorOccupiedFloorInput;decorWitnessSideSelect;decorWindowInputs;labelDecorSide;optionWitnessSide;labelDecor;labelDecorGroup;labelDecorTitle;labelDecorEast;labelDecorNorth;labelDecorHeading;labelDecorColor;labelDecorLit;labelDecorSightingUrl;labelMilestones;labelMilestoneLabel;labelMilestoneNote;labelDecorWidth;labelDecorLength;labelDecorHeight;labelDecorModel;labelDecorModelAdvanced;labelDecorModelUrl;labelDecorModelTitle;labelDecorModelAuthor;labelDecorModelLicense;labelDecorModelSource;labelDecorFloors;labelDecorOccupiedFloor;labelDecorWitnessSide;labelDecorWindows;optionWitnessSideNone;optionDecorBuilding;optionDecorTree;optionDecorCrop;optionDecorMound;optionDecorStreetlight;optionDecorVehicle;optionDecorAircraft;optionDecorEntity;labelDecorLights;optionDecorWitness;recorder;isRecording=!1;messages=Nv;currentAppearance={...HA};currentSourceId=kl;selectedSourceIds=new Set([kl]);currentDecorId;currentReferenceId;referenceSelect;deleteReferenceButton;referenceTitleInput;referenceSrcInput;referenceKindSelect;referenceCreditInput;referenceCreditUrlInput;referenceTInput;referenceDrawingInput;referenceOpacityInput;referenceHeadingInput;referencePitchInput;referenceRollInput;referenceFovInput;referenceUsePoseButton;referenceStatus;addReferenceUrlButton;addReferenceFileInput;referenceLandmarksSelect;addReferenceLandmarkButton;deleteReferenceLandmarkButton;referenceLandmarkLabelInput;labelReferenceLandmarks;labelReferenceLandmarkLabel;referenceAdoptPoseButton;referenceStreetSearchButton;referenceStreetSelect;referenceStreetAddButton;lastCanvasMode="shape";referenceDragState;armingLandmark=!1;pendingLandmark;currentLandmarkId;referenceFit;streetPictures=[];streetPictures$=new ea;referenceFields;labelReferenceGroup;labelReference;labelReferenceTitle;labelReferenceSrc;labelReferenceKind;labelReferenceCredit;labelReferenceCreditUrl;labelReferenceT;labelReferenceDrawing;labelReferenceOpacity;labelReferenceHeading;labelReferencePitch;labelReferenceRoll;labelReferenceFov;labelAddReferenceFile;contextMenuDecorId;contextMenuPoint;dragState;cameraDragState;hoverCursor;indoorLookYawDeg=0;indoorLookPitchDeg=0;lastInhabitedKey;handleKeyDown=e=>{if(e.key==="Escape"&&(this.isRecording&&this.toggleRecording(),this.confirmOverlay.hidden||this.answerConfirm(!1),(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark(),this.contextMenu.hidden||this.hideContextMenu(),this.decorContextMenu.hidden||this.hideDecorContextMenu()),Hm.has(e.key)||e.key==="Delete"||e.key==="Backspace"){const t=e.composedPath()[0];if(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement)return;Hm.has(e.key)?this.moveOrResizeSelectedShapes(e):this.deleteShape()}};handleDragPointerMove=e=>this.onDragPointerMove(e);handleDragPointerUp=()=>this.endDrag();constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${R1}</style>${C1}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.sceneElement=document.createElement(Cu),this.sceneElement.setAttribute("show-compass",""),this.sceneElement.setAttribute(sr,""),this.sceneElement.animateWhilePaused=!0,this.ufoElement=this.sceneElement.ufoElement,this.ufoElement.enableClickToPlay=!1,this.ufoElement.showToolbar=!1,this.shadow.getElementById("ufo-slot").replaceWith(this.sceneElement),this.ufoElement.hostControls(this.shadow.getElementById("scene-controls")),this.recordButton=this.shadow.getElementById("record"),this.samplingRateInput=this.shadow.getElementById("samplingRate"),this.presetsGroup=this.shadow.getElementById("presets-group"),this.presetButtons={oval:this.shadow.getElementById("preset-oval"),polygon:this.shadow.getElementById("preset-polygon")},this.colorInput=this.shadow.getElementById("color"),this.transparencyInput=this.shadow.getElementById("transparency"),this.haloScaleInput=this.shadow.getElementById("haloScale"),this.blurInput=this.shadow.getElementById("blur"),this.brightnessInput=this.shadow.getElementById("brightness"),this.blurBoundOutput=this.shadow.getElementById("blur-bound"),this.sourceSelect=this.shadow.getElementById("source"),this.shapeTitleInput=this.shadow.getElementById("shapeTitle"),this.utcOffsetInput=this.shadow.getElementById("utcOffsetHours"),this.timeZoneSelect=this.shadow.getElementById("timeZone"),this.apparentWidthInput=this.shadow.getElementById("apparentWidth"),this.realWidthInput=this.shadow.getElementById("realWidth"),this.objectDistanceInput=this.shadow.getElementById("objectDistance"),this.sizeLockSelect=this.shadow.getElementById("sizeLock"),this.apparentSizeOutput=this.shadow.getElementById("apparent-size"),this.realSizeOutput=this.shadow.getElementById("real-size"),this.clearDistanceHypothesisButton=this.shadow.getElementById("clear-distance-hypothesis"),this.depthBasisOutput=this.shadow.getElementById("depth-basis"),this.addShapeButton=this.shadow.getElementById("add-shape"),this.deleteShapeButton=this.shadow.getElementById("delete-shape"),this.contextMenu=this.shadow.getElementById("context-menu"),this.contextGroupButton=this.shadow.getElementById("context-group"),this.contextUngroupButton=this.shadow.getElementById("context-ungroup"),this.contextBringToFrontButton=this.shadow.getElementById("context-bring-to-front"),this.contextSendToBackButton=this.shadow.getElementById("context-send-to-back"),this.contextDeleteButton=this.shadow.getElementById("context-delete"),this.contextAddVertexButton=this.shadow.getElementById("context-add-vertex"),this.contextDeleteVertexButton=this.shadow.getElementById("context-delete-vertex"),this.decorContextMenu=this.shadow.getElementById("decor-context-menu"),this.contextViewTestimonyButton=this.shadow.getElementById("context-view-testimony"),this.contextMasksSubmenu=this.shadow.getElementById("context-masks-submenu"),this.labelContextMasks=this.shadow.getElementById("label-context-masks"),this.playPauseButton=this.shadow.getElementById("play-pause"),this.seekInput=this.shadow.getElementById("seek"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end");for(const t of[this.timeStartLabel,this.timeEndLabel])t.addEventListener("click",()=>this.switchTimeDisplay()),t.addEventListener("keydown",n=>{n.key!=="Enter"&&n.key!==" "||(n.preventDefault(),this.switchTimeDisplay())});this.loopButton=this.shadow.getElementById("loop"),this.durationInput=this.shadow.getElementById("durationSeconds"),this.exportButton=this.shadow.getElementById("export"),this.importFileInput=this.shadow.getElementById("import-file"),this.importUrlInput=this.shadow.getElementById("import-url"),this.importUrlButton=this.shadow.getElementById("import-url-button"),this.narrativeKeyInput=this.shadow.getElementById("narrativeKey"),this.narrativeWorkspaceInput=this.shadow.getElementById("narrativeWorkspace"),this.narrativeRememberInput=this.shadow.getElementById("narrativeRemember"),this.narrativeDraftButton=this.shadow.getElementById("narrative-draft"),this.narrativeStopButton=this.shadow.getElementById("narrative-stop"),this.narrativeCreditLink=this.shadow.getElementById("narrative-credit"),this.narrativeStatus=this.shadow.getElementById("narrative-status"),this.narrativeReport=this.shadow.getElementById("narrative-report"),this.placeNameInput=this.shadow.getElementById("placeName"),this.searchPlaceButton=this.shadow.getElementById("search-place"),this.placeMatchRow=this.shadow.getElementById("place-match-row"),this.placeMatchSelect=this.shadow.getElementById("placeMatch"),this.placeStatusText=this.shadow.getElementById("place-status-text"),this.latInput=this.shadow.getElementById("lat"),this.lngInput=this.shadow.getElementById("lng"),this.headingInput=this.shadow.getElementById("heading"),this.pitchInput=this.shadow.getElementById("pitch"),this.rollInput=this.shadow.getElementById("roll"),this.elevationInput=this.shadow.getElementById("elevation"),this.groundElevationOutput=this.shadow.getElementById("ground-elevation"),this.obsTimeInput=this.shadow.getElementById("obs-time"),this.obsEndTimeInput=this.shadow.getElementById("obs-end-time"),this.obsTimeNativeInput=this.shadow.getElementById("obs-time-native"),this.obsEndTimeNativeInput=this.shadow.getElementById("obs-end-time-native"),this.obsTimeQualifier=this.shadow.getElementById("obs-time-qualifier"),this.obsEndTimeQualifier=this.shadow.getElementById("obs-end-time-qualifier"),this.edtfModeButton=this.shadow.getElementById("edtf-mode"),this.witnessIdInput=this.shadow.getElementById("witnessId"),this.witnessDirNameInput=this.shadow.getElementById("witnessDirName"),this.witnessTitleInput=this.shadow.getElementById("witnessTitle"),this.witnessLastNameInput=this.shadow.getElementById("witnessLastName"),this.witnessFirstNamesInput=this.shadow.getElementById("witnessFirstNames"),this.witnessAgeInput=this.shadow.getElementById("witnessAge"),this.witnessOccupationInput=this.shadow.getElementById("witnessOccupation"),this.testimonySourceSelect=this.shadow.getElementById("testimonySource"),this.testimonyFollowedUpSelect=this.shadow.getElementById("testimonyFollowedUp"),this.caseIdInput=this.shadow.getElementById("caseId"),this.descriptionInput=this.shadow.getElementById("description"),this.tagsInput=this.shadow.getElementById("tags"),this.cloudCoverInput=this.shadow.getElementById("cloudCover"),this.highCloudCoverInput=this.shadow.getElementById("highCloudCover"),this.iceCrystalAlignmentInput=this.shadow.getElementById("iceCrystalAlignment"),this.cloudDarknessInput=this.shadow.getElementById("cloudDarkness"),this.cloudBaseInput=this.shadow.getElementById("cloudBase"),this.precipitationTypeSelect=this.shadow.getElementById("precipitationType"),this.precipitationIntensityInput=this.shadow.getElementById("precipitationIntensity"),this.windDirectionInput=this.shadow.getElementById("windDirection"),this.windSpeedInput=this.shadow.getElementById("windSpeed"),this.stormInput=this.shadow.getElementById("storm"),this.weatherInferredInput=this.shadow.getElementById("weatherInferred"),this.weatherSourceText=this.shadow.getElementById("weather-source-text"),this.skyCandidatesOutput=this.shadow.getElementById("sky-candidates"),this.showMeteorButton=this.shadow.getElementById("show-meteor"),this.showCometButton=this.shadow.getElementById("show-comet"),this.showSatelliteButton=this.shadow.getElementById("show-satellite"),this.weatherSourceLink=this.shadow.getElementById("weather-source-link"),this.weatherFields=[this.cloudCoverInput,this.highCloudCoverInput,this.iceCrystalAlignmentInput,this.cloudDarknessInput,this.cloudBaseInput,this.precipitationTypeSelect,this.precipitationIntensityInput,this.windDirectionInput,this.windSpeedInput,this.stormInput],this.soundKindSelect=this.shadow.getElementById("soundKind"),this.soundVolumeInput=this.shadow.getElementById("soundVolume"),this.soundPitchInput=this.shadow.getElementById("soundPitch"),this.soundPitchValue=this.shadow.getElementById("sound-pitch-value"),this.soundSrcInput=this.shadow.getElementById("soundSrc"),this.soundFields=[this.soundKindSelect,this.soundVolumeInput,this.soundPitchInput,this.soundSrcInput],this.buildSoundKindOptions(),this.instrumentSelect=this.shadow.getElementById("instrument"),this.focalLengthInput=this.shadow.getElementById("focalLength"),this.labelFocalLength=this.shadow.getElementById("label-focal-length"),this.unitFocalLength=this.shadow.getElementById("unit-focal-length"),this.labelFNumber=this.shadow.getElementById("label-f-number"),this.labelExposure=this.shadow.getElementById("label-exposure"),this.fNumberInput=this.shadow.getElementById("fNumber"),this.exposureInput=this.shadow.getElementById("exposureSeconds"),this.focusDistanceInput=this.shadow.getElementById("focusDistance"),this.labelFocusDistance=this.shadow.getElementById("label-focus-distance"),this.refreshInstrumentOptions(),this.labelColor=this.shadow.getElementById("label-color"),this.labelTransparency=this.shadow.getElementById("label-transparency"),this.labelHalo=this.shadow.getElementById("label-halo"),this.labelBlur=this.shadow.getElementById("label-blur"),this.labelBrightness=this.shadow.getElementById("label-brightness"),this.labelShape=this.shadow.getElementById("label-shape"),this.labelShapeTitle=this.shadow.getElementById("label-shape-title"),this.labelUtcOffset=this.shadow.getElementById("label-utc-offset"),this.labelApparentWidth=this.shadow.getElementById("label-apparent-width"),this.labelRealWidth=this.shadow.getElementById("label-real-width"),this.labelObjectDistance=this.shadow.getElementById("label-object-distance"),this.labelSizeLock=this.shadow.getElementById("label-size-lock"),this.labelSamplingRate=this.shadow.getElementById("label-sampling-rate"),this.labelSoundGroup=this.shadow.getElementById("label-sound-group"),this.labelSoundKind=this.shadow.getElementById("label-sound-kind"),this.labelSoundVolume=this.shadow.getElementById("label-sound-volume"),this.labelSoundPitch=this.shadow.getElementById("label-sound-pitch"),this.labelSoundSrc=this.shadow.getElementById("label-sound-src"),this.labelReferenceGroup=this.shadow.getElementById("label-reference-group"),this.labelReference=this.shadow.getElementById("label-reference"),this.labelReferenceTitle=this.shadow.getElementById("label-reference-title"),this.labelReferenceSrc=this.shadow.getElementById("label-reference-src"),this.labelReferenceKind=this.shadow.getElementById("label-reference-kind"),this.labelReferenceCredit=this.shadow.getElementById("label-reference-credit"),this.labelReferenceCreditUrl=this.shadow.getElementById("label-reference-credit-url"),this.labelReferenceT=this.shadow.getElementById("label-reference-t"),this.labelReferenceDrawing=this.shadow.getElementById("label-reference-drawing"),this.labelReferenceOpacity=this.shadow.getElementById("label-reference-opacity"),this.labelReferenceHeading=this.shadow.getElementById("label-reference-heading"),this.labelReferencePitch=this.shadow.getElementById("label-reference-pitch"),this.labelReferenceRoll=this.shadow.getElementById("label-reference-roll"),this.labelReferenceFov=this.shadow.getElementById("label-reference-fov"),this.labelAddReferenceFile=this.shadow.getElementById("label-add-reference-file"),this.labelDuration=this.shadow.getElementById("label-duration"),this.placeSourceRow=this.shadow.getElementById("place-source-row"),this.weatherSourceRow=this.shadow.getElementById("weather-source-row"),this.terrainSourceRows=this.shadow.getElementById("terrain-source-rows"),this.labelPlaceName=this.shadow.getElementById("label-place-name"),this.labelPlaceMatch=this.shadow.getElementById("label-place-match"),this.labelLatitude=this.shadow.getElementById("label-lat"),this.labelLongitude=this.shadow.getElementById("label-lng"),this.labelHeading=this.shadow.getElementById("label-heading"),this.labelPitch=this.shadow.getElementById("label-pitch"),this.labelRoll=this.shadow.getElementById("label-roll"),this.labelElevation=this.shadow.getElementById("label-elevation"),this.labelObservationTime=this.shadow.getElementById("label-observation-time"),this.labelObservationEndTime=this.shadow.getElementById("label-observation-end-time"),this.labelWitnessId=this.shadow.getElementById("label-witness-id"),this.labelWitnessDirName=this.shadow.getElementById("label-witness-dir-name"),this.labelWitnessTitle=this.shadow.getElementById("label-witness-title"),this.labelWitnessLastName=this.shadow.getElementById("label-witness-last-name"),this.labelWitnessFirstNames=this.shadow.getElementById("label-witness-first-names"),this.labelWitnessAge=this.shadow.getElementById("label-witness-age"),this.labelWitnessOccupation=this.shadow.getElementById("label-witness-occupation"),this.labelTestimonySource=this.shadow.getElementById("label-testimony-source"),this.labelTestimonyFollowedUp=this.shadow.getElementById("label-testimony-followed-up"),this.labelCaseId=this.shadow.getElementById("label-case-id"),this.labelDescription=this.shadow.getElementById("label-description"),this.labelTags=this.shadow.getElementById("label-tags"),this.labelImportFile=this.shadow.getElementById("label-import-file"),this.labelImportUrl=this.shadow.getElementById("label-import-url"),this.labelNarrativeKey=this.shadow.getElementById("label-narrative-key"),this.labelNarrativeWorkspace=this.shadow.getElementById("label-narrative-workspace"),this.labelNarrativeRemember=this.shadow.getElementById("label-narrative-remember"),this.labelShapeGroup=this.shadow.getElementById("label-shape-group"),this.labelTemporalGroup=this.shadow.getElementById("label-temporal-group"),this.labelLocationGroup=this.shadow.getElementById("label-location-group"),this.labelObservationGroup=this.shadow.getElementById("label-observation-group"),this.labelWitnessGroup=this.shadow.getElementById("label-witness-group"),this.labelWeatherGroup=this.shadow.getElementById("label-weather-group"),this.labelCloudCover=this.shadow.getElementById("label-cloud-cover"),this.labelHighCloud=this.shadow.getElementById("label-high-cloud"),this.labelIceAlignment=this.shadow.getElementById("label-ice-alignment"),this.labelCloudDarkness=this.shadow.getElementById("label-cloud-darkness"),this.labelCloudBase=this.shadow.getElementById("label-cloud-base"),this.labelPrecipitationType=this.shadow.getElementById("label-precipitation-type"),this.labelPrecipitationIntensity=this.shadow.getElementById("label-precipitation-intensity"),this.labelWindDirection=this.shadow.getElementById("label-wind-direction"),this.labelWindSpeed=this.shadow.getElementById("label-wind-speed"),this.labelStorm=this.shadow.getElementById("label-storm"),this.labelCloudsGroup=this.shadow.getElementById("label-clouds-group"),this.labelPrecipitationGroup=this.shadow.getElementById("label-precipitation-group"),this.labelWindGroup=this.shadow.getElementById("label-wind-group"),this.labelWeatherInferred=this.shadow.getElementById("label-weather-inferred"),this.labelInstrument=this.shadow.getElementById("label-instrument"),this.optionPrecipitationNone=this.shadow.getElementById("option-precipitation-none"),this.optionPrecipitationRain=this.shadow.getElementById("option-precipitation-rain"),this.optionPrecipitationSnow=this.shadow.getElementById("option-precipitation-snow"),this.optionPrecipitationHail=this.shadow.getElementById("option-precipitation-hail"),this.decorKindSelect=this.shadow.getElementById("decorKind"),this.addDecorWitnessButton=this.shadow.getElementById("add-decor-witness"),this.addDecorBuildingButton=this.shadow.getElementById("add-decor-building"),this.deleteDecorButton=this.shadow.getElementById("delete-decor"),this.decorSelect=this.shadow.getElementById("decor"),this.referenceSelect=this.shadow.getElementById("reference"),this.deleteReferenceButton=this.shadow.getElementById("delete-reference"),this.referenceTitleInput=this.shadow.getElementById("referenceTitle"),this.referenceSrcInput=this.shadow.getElementById("referenceSrc"),this.referenceKindSelect=this.shadow.getElementById("referenceKind"),this.referenceCreditInput=this.shadow.getElementById("referenceCredit"),this.referenceCreditUrlInput=this.shadow.getElementById("referenceCreditUrl"),this.referenceTInput=this.shadow.getElementById("referenceT"),this.referenceDrawingInput=this.shadow.getElementById("referenceDrawing"),this.referenceOpacityInput=this.shadow.getElementById("referenceOpacity"),this.referenceHeadingInput=this.shadow.getElementById("referenceHeading"),this.referencePitchInput=this.shadow.getElementById("referencePitch"),this.referenceRollInput=this.shadow.getElementById("referenceRoll"),this.referenceFovInput=this.shadow.getElementById("referenceFov"),this.referenceUsePoseButton=this.shadow.getElementById("reference-use-pose"),this.referenceStatus=this.shadow.getElementById("reference-status"),this.addReferenceUrlButton=this.shadow.getElementById("add-reference-url"),this.addReferenceFileInput=this.shadow.getElementById("add-reference-file"),this.referenceLandmarksSelect=this.shadow.getElementById("reference-landmarks"),this.addReferenceLandmarkButton=this.shadow.getElementById("add-reference-landmark"),this.deleteReferenceLandmarkButton=this.shadow.getElementById("delete-reference-landmark"),this.referenceLandmarkLabelInput=this.shadow.getElementById("referenceLandmarkLabel"),this.labelReferenceLandmarks=this.shadow.getElementById("label-reference-landmarks"),this.labelReferenceLandmarkLabel=this.shadow.getElementById("label-reference-landmark-label"),this.referenceAdoptPoseButton=this.shadow.getElementById("reference-adopt-pose"),this.referenceStreetSearchButton=this.shadow.getElementById("reference-street-search"),this.referenceStreetSelect=this.shadow.getElementById("reference-street"),this.referenceStreetAddButton=this.shadow.getElementById("reference-street-add"),this.referenceFields=[this.referenceTitleInput,this.referenceSrcInput,this.referenceKindSelect,this.referenceCreditInput,this.referenceCreditUrlInput,this.referenceTInput,this.referenceDrawingInput,this.referenceOpacityInput,this.referenceHeadingInput,this.referencePitchInput,this.referenceRollInput,this.referenceFovInput],this.decorTitleInput=this.shadow.getElementById("decorTitle"),this.decorEastInput=this.shadow.getElementById("decorEast"),this.decorNorthInput=this.shadow.getElementById("decorNorth"),this.decorHeadingInput=this.shadow.getElementById("decorHeading"),this.decorColorInput=this.shadow.getElementById("decorColor"),this.decorLitInput=this.shadow.getElementById("decorLit"),this.decorLightRigSelect=this.shadow.getElementById("decorLightRig"),this.lookAtDecorButton=this.shadow.getElementById("look-at-decor"),this.decorAltitudeInput=this.shadow.getElementById("decorAltitude"),this.labelDecorAltitude=this.shadow.getElementById("label-decor-altitude"),this.decorSightingUrlInput=this.shadow.getElementById("decorSightingUrl"),this.confirmOverlay=this.shadow.getElementById("confirm-overlay"),this.confirmMessage=this.shadow.getElementById("confirm-message"),this.confirmAcceptButton=this.shadow.getElementById("confirm-ok"),this.confirmDeclineButton=this.shadow.getElementById("confirm-cancel"),this.milestoneSelect=this.shadow.getElementById("milestone"),this.milestoneLabelInput=this.shadow.getElementById("milestoneLabel"),this.milestoneNoteInput=this.shadow.getElementById("milestoneNote"),this.addMilestoneButton=this.shadow.getElementById("add-milestone"),this.deleteMilestoneButton=this.shadow.getElementById("delete-milestone"),this.decorWidthInput=this.shadow.getElementById("decorWidth"),this.decorLengthInput=this.shadow.getElementById("decorLength"),this.decorHeightInput=this.shadow.getElementById("decorHeight"),this.decorModelSelect=this.shadow.getElementById("decorModel"),this.decorModelAdvanced=this.shadow.getElementById("decor-model-advanced"),this.decorModelUrlInput=this.shadow.getElementById("decorModelUrl"),this.decorModelTitleInput=this.shadow.getElementById("decorModelTitle"),this.decorModelAuthorInput=this.shadow.getElementById("decorModelAuthor"),this.decorModelLicenseInput=this.shadow.getElementById("decorModelLicense"),this.decorModelSourceInput=this.shadow.getElementById("decorModelSource"),this.decorFloorsInput=this.shadow.getElementById("decorFloors"),this.decorOccupiedFloorInput=this.shadow.getElementById("decorOccupiedFloor"),this.decorWitnessSideSelect=this.shadow.getElementById("decorWitnessSide"),this.decorWindowInputs={front:this.shadow.getElementById("decorWindowFront"),behind:this.shadow.getElementById("decorWindowBehind"),left:this.shadow.getElementById("decorWindowLeft"),right:this.shadow.getElementById("decorWindowRight"),"front-left":this.shadow.getElementById("decorWindowFrontLeft"),"front-right":this.shadow.getElementById("decorWindowFrontRight"),"behind-left":this.shadow.getElementById("decorWindowBehindLeft"),"behind-right":this.shadow.getElementById("decorWindowBehindRight")},this.labelDecorSide={front:this.shadow.getElementById("label-decor-window-front"),behind:this.shadow.getElementById("label-decor-window-behind"),left:this.shadow.getElementById("label-decor-window-left"),right:this.shadow.getElementById("label-decor-window-right"),"front-left":this.shadow.getElementById("label-decor-window-front-left"),"front-right":this.shadow.getElementById("label-decor-window-front-right"),"behind-left":this.shadow.getElementById("label-decor-window-behind-left"),"behind-right":this.shadow.getElementById("label-decor-window-behind-right")},this.optionWitnessSide={front:this.shadow.getElementById("option-witness-side-front"),behind:this.shadow.getElementById("option-witness-side-behind"),left:this.shadow.getElementById("option-witness-side-left"),right:this.shadow.getElementById("option-witness-side-right"),"front-left":this.shadow.getElementById("option-witness-side-front-left"),"front-right":this.shadow.getElementById("option-witness-side-front-right"),"behind-left":this.shadow.getElementById("option-witness-side-behind-left"),"behind-right":this.shadow.getElementById("option-witness-side-behind-right")},this.optionWitnessSideNone=this.shadow.getElementById("option-witness-side-none"),this.labelDecor=this.shadow.getElementById("label-decor"),this.labelDecorGroup=this.shadow.getElementById("label-decor-group"),this.labelDecorTitle=this.shadow.getElementById("label-decor-title"),this.labelDecorEast=this.shadow.getElementById("label-decor-east"),this.labelDecorNorth=this.shadow.getElementById("label-decor-north"),this.labelDecorHeading=this.shadow.getElementById("label-decor-heading"),this.labelDecorColor=this.shadow.getElementById("label-decor-color"),this.labelDecorLit=this.shadow.getElementById("label-decor-lit"),this.labelDecorSightingUrl=this.shadow.getElementById("label-decor-sighting-url"),this.labelMilestones=this.shadow.getElementById("label-milestones"),this.labelMilestoneLabel=this.shadow.getElementById("label-milestone-label"),this.labelMilestoneNote=this.shadow.getElementById("label-milestone-note"),this.labelDecorWidth=this.shadow.getElementById("label-decor-width"),this.labelDecorLength=this.shadow.getElementById("label-decor-length"),this.labelDecorHeight=this.shadow.getElementById("label-decor-height"),this.labelDecorModel=this.shadow.getElementById("label-decor-model"),this.labelDecorModelAdvanced=this.shadow.getElementById("label-decor-model-advanced"),this.labelDecorModelUrl=this.shadow.getElementById("label-decor-model-url"),this.labelDecorModelTitle=this.shadow.getElementById("label-decor-model-title"),this.labelDecorModelAuthor=this.shadow.getElementById("label-decor-model-author"),this.labelDecorModelLicense=this.shadow.getElementById("label-decor-model-license"),this.labelDecorModelSource=this.shadow.getElementById("label-decor-model-source"),this.labelDecorFloors=this.shadow.getElementById("label-decor-floors"),this.labelDecorOccupiedFloor=this.shadow.getElementById("label-decor-occupied-floor"),this.labelDecorWitnessSide=this.shadow.getElementById("label-decor-witness-side"),this.labelDecorWindows=this.shadow.getElementById("label-decor-windows"),this.optionDecorBuilding=this.shadow.getElementById("option-decor-building"),this.optionDecorTree=this.shadow.getElementById("option-decor-tree"),this.optionDecorCrop=this.shadow.getElementById("option-decor-crop"),this.optionDecorMound=this.shadow.getElementById("option-decor-mound"),this.optionDecorStreetlight=this.shadow.getElementById("option-decor-streetlight"),this.optionDecorVehicle=this.shadow.getElementById("option-decor-vehicle"),this.optionDecorAircraft=this.shadow.getElementById("option-decor-aircraft"),this.optionDecorEntity=this.shadow.getElementById("option-decor-entity"),this.labelDecorLights=this.shadow.getElementById("label-decor-lights"),this.optionDecorWitness=this.shadow.getElementById("option-decor-witness"),this.ufoElement.canvasElement.addEventListener("pointerdown",t=>{this.focus({preventScroll:!0}),this.onPointerDown(t)}),this.ufoElement.canvasElement.addEventListener("pointermove",t=>this.onPointerMove(t)),this.ufoElement.canvasElement.addEventListener("contextmenu",t=>this.onContextMenu(t)),this.contextGroupButton.addEventListener("click",()=>this.groupSelected()),this.contextUngroupButton.addEventListener("click",()=>this.ungroupSelected()),this.contextBringToFrontButton.addEventListener("click",()=>this.bringSelectedToFront()),this.contextSendToBackButton.addEventListener("click",()=>this.sendSelectedToBack()),this.contextDeleteButton.addEventListener("click",()=>{this.hideContextMenu(),this.deleteShape()}),this.contextAddVertexButton.addEventListener("click",()=>this.addVertexAtContextMenu()),this.contextDeleteVertexButton.addEventListener("click",()=>this.deleteVertexAtContextMenu()),this.contextViewTestimonyButton.addEventListener("click",()=>this.viewWitnessTestimony()),this.playPauseButton.addEventListener("click",()=>{this.ufoElement.togglePlayPause(),this.syncPlaybackControls()}),this.loopButton.addEventListener("click",()=>{this.ufoElement.toggleLoop(),this.syncPlaybackControls()}),this.seekInput.addEventListener("input",()=>this.ufoElement.currentTime=Number(this.seekInput.value)),this.recordButton.addEventListener("click",()=>this.toggleRecording()),this.addShapeButton.addEventListener("click",()=>this.addShape()),this.deleteShapeButton.addEventListener("click",()=>this.deleteShape()),this.exportButton.addEventListener("click",()=>this.exportJson()),this.importFileInput.addEventListener("change",()=>this.importFromFile()),this.importUrlButton.addEventListener("click",()=>this.importFromUrl()),this.testimonySourceSelect.addEventListener("change",()=>this.updateWitnessMetadata()),this.testimonyFollowedUpSelect.addEventListener("change",()=>this.updateWitnessMetadata()),this.narrativeDraftButton.addEventListener("click",()=>this.draftFromDescription()),this.narrativeStopButton.addEventListener("click",()=>this.narrativeAbort?.abort()),this.narrativeRememberInput.addEventListener("change",()=>this.rememberNarrativeKey()),this.narrativeWorkspaceInput.addEventListener("input",()=>this.rememberNarrativeKey()),this.narrativeKeyInput.addEventListener("input",()=>{this.rememberNarrativeKey(),this.syncNarrativeEnabled()}),this.narrativeCreditLink.textContent=`${Ns[0].name} — ${Ns[0].credit}`,this.narrativeCreditLink.href=Ns[0].creditUrl,this.labelNarrativeKey.textContent=this.messages.narrativeKey.replace("{source}",Ns[0].name),this.narrativeWorkspaceInput.title=this.messages.narrativeWorkspaceHint,this.restoreNarrativeKey(),this.syncNarrativeEnabled(),this.durationInput.addEventListener("input",()=>{this.ufoElement.durationSeconds=this.durationInput.value===""?void 0:Number(this.durationInput.value),this.ufoElement.refresh(),this.updateDurationValidity(),this.scheduleWeatherLookup()}),this.sourceSelect.addEventListener("change",()=>this.selectUnit(this.sourceSelect.value)),this.shapeTitleInput.addEventListener("input",()=>this.updateShapeTitle()),this.apparentWidthInput.addEventListener("input",()=>this.typing(this.apparentWidthInput,()=>this.onApparentWidthInput())),this.realWidthInput.addEventListener("input",()=>this.typing(this.realWidthInput,()=>this.onRealWidthInput())),this.objectDistanceInput.addEventListener("input",()=>this.typing(this.objectDistanceInput,()=>this.onDistanceInput())),this.sizeLockSelect.addEventListener("change",()=>this.applySizeLock()),this.clearDistanceHypothesisButton.addEventListener("click",()=>this.clearDistanceHypothesis()),this.addDecorWitnessButton.addEventListener("click",()=>this.addDecor("witness")),this.addDecorBuildingButton.addEventListener("click",()=>this.addDecor()),this.deleteDecorButton.addEventListener("click",()=>this.deleteDecor()),this.decorSelect.addEventListener("change",()=>this.selectDecor(this.decorSelect.value)),this.referenceSelect.addEventListener("change",()=>this.selectReference(this.referenceSelect.value)),this.deleteReferenceButton.addEventListener("click",()=>this.deleteReference());for(const t of this.referenceFields)t.addEventListener("input",()=>this.updateReference());this.referenceUsePoseButton.addEventListener("click",()=>this.useWitnessPoseForReference()),this.addReferenceUrlButton.addEventListener("click",()=>this.addReferenceFromAddress()),this.addReferenceFileInput.addEventListener("change",()=>void this.addReferenceFromFile()),this.addReferenceLandmarkButton.addEventListener("click",()=>this.armLandmark()),this.deleteReferenceLandmarkButton.addEventListener("click",()=>this.deleteLandmark()),this.referenceLandmarksSelect.addEventListener("change",()=>this.selectLandmark(this.referenceLandmarksSelect.value)),this.referenceLandmarkLabelInput.addEventListener("input",()=>this.updateLandmarkLabel()),this.referenceAdoptPoseButton.addEventListener("click",()=>this.adoptReferencePose()),this.referenceStreetSearchButton.addEventListener("click",()=>void this.searchStreetPictures()),this.referenceStreetAddButton.addEventListener("click",()=>this.addStreetPicture()),this.ufoElement.canvasElement.addEventListener("wheel",t=>this.onReferenceWheel(t),{passive:!1});for(const t of[this.decorTitleInput,this.decorEastInput,this.decorNorthInput,this.decorAltitudeInput,this.decorHeadingInput,this.decorColorInput,this.decorSightingUrlInput,this.decorWidthInput,this.decorLengthInput,this.decorHeightInput,this.decorModelUrlInput,this.decorModelTitleInput,this.decorModelAuthorInput,this.decorModelLicenseInput,this.decorModelSourceInput,this.decorFloorsInput,this.decorOccupiedFloorInput])t.addEventListener("input",()=>this.updateDecor());this.decorWitnessSideSelect.addEventListener("change",()=>this.updateDecor()),this.decorModelSelect.addEventListener("change",()=>this.updateDecorModelChoice()),this.addMilestoneButton.addEventListener("click",()=>this.addMilestone()),this.deleteMilestoneButton.addEventListener("click",()=>this.deleteMilestone()),this.milestoneSelect.addEventListener("change",()=>this.selectMilestone(Number(this.milestoneSelect.value)));for(const t of[this.milestoneLabelInput,this.milestoneNoteInput])t.addEventListener("input",()=>this.updateMilestone());this.confirmAcceptButton.addEventListener("click",()=>this.answerConfirm(!0)),this.confirmDeclineButton.addEventListener("click",()=>this.answerConfirm(!1)),this.confirmOverlay.addEventListener("click",t=>{t.target===this.confirmOverlay&&this.answerConfirm(!1)});for(const t of gr)this.decorWindowInputs[t].addEventListener("input",()=>this.updateDecorWindows());this.decorLitInput.addEventListener("input",()=>this.updateDecorLit()),this.decorLightRigSelect.addEventListener("change",()=>this.updateDecorLightRig()),this.lookAtDecorButton.addEventListener("click",()=>this.lookAtDecor()),this.showMeteorButton.addEventListener("click",()=>this.showNextMeteor()),this.showCometButton.addEventListener("click",()=>this.lookAtComet()),this.showSatelliteButton.addEventListener("click",()=>this.showNextSatellite()),this.sceneElement.addEventListener(Pv,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.ufoElement.addEventListener("timeupdate",()=>{this.onSelectionOrTimeChanged(),this.syncPlaybackControls(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.addEventListener("keydown",this.handleKeyDown);for(const t of Gm)this.presetButtons[t].addEventListener("click",()=>this.setAppearance({presetId:t}));this.colorInput.addEventListener("input",()=>this.setAppearance({color:this.colorInput.value})),this.transparencyInput.addEventListener("input",()=>this.setAppearance({transparency:Number(this.transparencyInput.value)})),this.brightnessInput.addEventListener("input",()=>this.setAppearance({brightness:Number(this.brightnessInput.value)})),this.blurInput.addEventListener("input",()=>{this.setAppearance({blur:Number(this.blurInput.value)}),this.refreshBlurDistanceBound()}),this.haloScaleInput.addEventListener("input",()=>this.setAppearance({haloScale:Number(this.haloScaleInput.value)}));for(const t of[this.latInput,this.lngInput,this.headingInput,this.pitchInput,this.rollInput,this.elevationInput])t.addEventListener("input",()=>this.updateObserver());for(const t of[this.focalLengthInput,this.fNumberInput,this.exposureInput,this.focusDistanceInput])t.addEventListener("input",()=>this.updateObserver());this.searchPlaceButton.addEventListener("click",()=>void this.searchPlace()),this.placeNameInput.addEventListener("keydown",t=>{t.key==="Enter"&&(t.preventDefault(),this.searchPlace())}),this.placeMatchSelect.addEventListener("change",()=>this.applyPlaceMatch(this.placeMatchSelect.selectedIndex)),this.placeNameInput.addEventListener("input",()=>this.updatePlaceName()),this.headingInput.addEventListener("focus",()=>this.sceneElement.setCompassForced(!0)),this.headingInput.addEventListener("blur",()=>this.sceneElement.setCompassForced(!1)),this.instrumentSelect.addEventListener("change",()=>{const t=this.ufoElement.sighting.instrument;this.ufoElement.sighting.instrumentId=this.instrumentSelect.value;const n=new Map(this.ufoElement.sighting.timeline.allKeyframes.map(i=>[i.t,ln.fovOf(this.ufoElement.sighting,i.t)]));this.retuneFieldOfView(t),this.retuneExposure(t),ln.reproject(this.ufoElement.sighting,t,n),this.sceneElement.applyFrameFormat(),this.syncOpticsFromInstrument(),this.ufoElement.refresh(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.utcOffsetInput.addEventListener("input",()=>this.updateUtcOffset()),this.timeZoneSelect.addEventListener("change",()=>{this.autoFilledTimeZone=void 0,this.updateTimeZone()}),this.obsTimeInput.addEventListener("input",()=>this.updateObservationTime()),this.obsEndTimeInput.addEventListener("input",()=>this.updateObservationEndTime()),this.obsTimeNativeInput.addEventListener("change",()=>this.writeFromPicker(this.obsTimeNativeInput,this.obsTimeQualifier,this.obsTimeInput,()=>this.updateObservationTime())),this.obsEndTimeNativeInput.addEventListener("change",()=>this.writeFromPicker(this.obsEndTimeNativeInput,this.obsEndTimeQualifier,this.obsEndTimeInput,()=>this.updateObservationEndTime())),this.obsTimeQualifier.addEventListener("change",()=>this.writeFromPicker(this.obsTimeNativeInput,this.obsTimeQualifier,this.obsTimeInput,()=>this.updateObservationTime())),this.obsEndTimeQualifier.addEventListener("change",()=>this.writeFromPicker(this.obsEndTimeNativeInput,this.obsEndTimeQualifier,this.obsEndTimeInput,()=>this.updateObservationEndTime())),this.edtfModeButton.addEventListener("click",()=>this.setEdtfMode(!this.edtfMode)),this.obsTimeInput.addEventListener("blur",()=>this.validateEdtfTimeInput(this.obsTimeInput)),this.obsEndTimeInput.addEventListener("blur",()=>this.validateEdtfTimeInput(this.obsEndTimeInput));for(const t of[this.witnessIdInput,this.witnessDirNameInput,this.witnessTitleInput,this.witnessLastNameInput,this.witnessFirstNamesInput,this.witnessAgeInput,this.witnessOccupationInput,this.caseIdInput])t.addEventListener("input",()=>this.updateWitnessMetadata());this.descriptionInput.addEventListener("input",()=>{this.updateDescription(),this.syncNarrativeEnabled()}),this.tagsInput.addEventListener("input",()=>this.updateTags());for(const t of this.weatherFields){if(t===this.iceCrystalAlignmentInput){t.addEventListener("input",()=>this.applyIceAlignmentAtPlayhead());continue}t.addEventListener("input",()=>this.applyWeatherAtPlayhead())}for(const t of this.soundFields)t.addEventListener("input",()=>this.applySoundAtPlayhead());this.weatherInferredInput.addEventListener("change",()=>this.onWeatherInferredToggled()),this.skyDetailsButton=this.shadow.getElementById("sky-details"),this.clampedLines=[this.shadow.getElementById("weather-source"),this.shadow.getElementById("sky-candidates")],this.skyDetailsButton.addEventListener("click",()=>this.toggleSkyDetails()),this.groupTabs=[...this.shadow.querySelectorAll(".group-tab")],this.groupPanels=this.groupTabs.map(t=>this.shadow.getElementById(t.getAttribute("aria-controls")));for(const t of this.groupTabs)t.addEventListener("click",()=>this.toggleGroup(t,!this.isGroupOpen(t)));this.subgroupTabs=[...this.shadow.querySelectorAll(".subgroup-tab")];for(const t of this.subgroupTabs)t.addEventListener("click",()=>this.openSubgroup(t));this.paramSummary=this.shadow.getElementById("param-summary"),this.paramSummaryBuilder=new Bf(this.messages,this.showerLanguage(),this.said,this.tagNames),this.paramSummary.addEventListener("click",t=>this.onParamSummaryClick(t)),this.toggleGroup(this.groupTabs[this.groupTabs.length-1],!0),this.updatePresetButtons(),this.setRecordButtonLabel(!1),this.applyAppearanceAtPlayhead(),this.shapeTitleInput.value=this.shapeLabel(this.currentSourceId),this.updateShapeTitle(),this.currentDecorId=this.ufoElement.sighting.decor[0]?.id,this.refreshDecorList(),this.currentReferenceId=this.ufoElement.sighting.references[0]?.id,this.refreshReferenceList(),this.sceneElement.setCloudRendering("volume"),this.cloudEditor=v1(this.shadow.getElementById("cloud-editor"),this.sceneElement,(t=!0)=>{t&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())},(t,n)=>{this.headingInput.value=String(this.rounded(t)),this.pitchInput.value=String(this.rounded(n)),this.updateObserver()},na(Ts.preferencesFor(this),od)),this.currentMilestoneT=this.ufoElement.sighting.milestones[0]?.t,this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncPlaybackControls(),this.refreshSourceRows(),this.refreshTimeQualifierOptions(),this.refreshTimeZoneOptions(),this.syncWeatherSourceState(),this.loadLocaleMessages()}static get observedAttributes(){return["src"]}connectedCallback(){this.hasAttribute("tabindex")||(this.tabIndex=-1);const e=this.getAttribute("src");e&&this.importFromUrl(e)}attributeChangedCallback(e,t,n){e==="src"&&n&&n!==t&&this.isConnected&&this.importFromUrl(n)}disconnectedCallback(){this.cloudEditor.stopManipulation(),document.removeEventListener("click",this.handleOutsideContextMenuClick),this.endDrag()}setCloudRendering(e){this.sceneElement.setCloudRendering(e)}showWeatherEditor(){const e=this.groupPanels.findIndex(t=>t.id==="group-weather");e>=0&&this.toggleGroup(this.groupTabs[e],!0)}get sightingData(){return this.ufoElement.sightingData}set sightingData(e){this.endDrag(),this.ufoElement.sightingData=e,this.cloudEditor.reset(),this.currentSourceId=this.ufoElement.sighting.timeline.sourceIds[0]??kl,this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.currentDecorId=this.ufoElement.sighting.decor[0]?.id,this.refreshDecorList(),this.currentReferenceId=this.ufoElement.sighting.references[0]?.id,this.refreshReferenceList(),this.currentMilestoneT=this.ufoElement.sighting.milestones[0]?.t,this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncObservationTimeFields(),this.syncObservationEndTimeFields(),this.chooseTimeInputMode(),this.syncWitnessMetadataFields(),this.refreshTimeZoneOptions(),this.utcOffsetInput.readOnly=this.ufoElement.sighting.event.timeZone!==void 0,this.syncUtcOffsetField(),this.syncPlaceNameField(),this.syncGroundElevationField(),this.syncWeatherOwnership()}exportJson(){const e=this.sightingData,t=`${e.witness?.id??"sighting"}-sighting.json`,n=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),i=URL.createObjectURL(n),s=document.createElement("a");s.href=i,s.download=t,s.click(),URL.revokeObjectURL(i)}async importFromFile(){const e=this.importFileInput.files?.[0];if(e)try{const t=await new Promise((n,i)=>{const s=new FileReader;s.onload=()=>n(s.result),s.onerror=()=>i(s.error),s.readAsText(e)});this.sightingData=JSON.parse(t),this.importUrlInput.value=""}catch{window.alert(this.messages.importError)}finally{this.importFileInput.value=""}}async importFromUrl(e=this.importUrlInput.value.trim()){if(e)try{this.sightingData=await Lu.json(e),this.importUrlInput.value=new URL(e,location.href).href}catch(t){window.alert(this.importErrorFor(t))}}importErrorFor(e){if(!(e instanceof Vs))return this.messages.importError;switch(e.kind){case"cors":return this.messages.importErrorCors;case"mixed-content":return this.messages.importErrorMixedContent;case"unreachable":return this.messages.importErrorUnreachable;case"status":return this.messages.importErrorStatus.replace("{status}",String(e.status??""));case"malformed":return this.messages.importErrorMalformed;default:return this.messages.importError}}static NARRATIVE_KEY_STORAGE="rr0-sighting-editor.narrative-key";static NARRATIVE_SCOPE_STORAGE="rr0-sighting-editor.narrative-workspace";narrativeProvider=Ns[0].create();narrativeAbort;async draftFromDescription(){const e=this.descriptionInput.value.trim();if(e===""||this.narrativeAbort)return;const t=this.narrativeAbort=new AbortController;this.setNarrativeBusy(!0);try{const n=await this.narrativeProvider.draft({ask:e,current:this.sightingData,language:this.showerLanguage()==="fr"?"French":"English",credential:this.narrativeKeyInput.value.trim()||void 0,credentialScope:this.narrativeWorkspaceInput.value.trim()||void 0},t.signal);this.applyNarrativeDraft(n)}catch(n){const i=n instanceof Un&&n.kind==="cancelled";this.narrativeStatus.textContent=i?"":this.narrativeErrorFor(n),this.narrativeStatus.classList.toggle("error",!i)}finally{this.narrativeAbort=void 0,this.setNarrativeBusy(!1)}}applyNarrativeDraft(e){const{description:t,...n}=e.recording,{utcOffsetHours:i,...s}=n,a=n.timeZone?s:n,o=Si.stated(a);if(o.length>0){const l=this.ufoElement.sighting.provenance,c=ad(this.ufoElement.sighting);this.sightingData=Si.apply(c,Jl.loadable(a),o),this.ufoElement.sighting.provenance=l,this.recordNarrativeProvenance(e,o),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset()}this.narrativeStatus.textContent=o.length>0?this.messages.narrativeApplied.replace("{count}",String(o.length)):this.messages.narrativeUnchanged,this.narrativeStatus.classList.remove("error"),this.showNarrativeReport(e),this.syncNarrativeEnabled()}recordNarrativeProvenance(e,t){const n=this.ufoElement.sighting,i=new Set(t);for(const s of e.claims)!i.has(s.path)&&!t.some(a=>s.path.startsWith(`${a}.`))||n.provenance.set(s.path,{basis:s.basis,rationale:s.rationale,of:Tt.valueAt(ad(this.ufoElement.sighting),s.path)})}static valueAt(e,t){let n=e;for(const i of t.split(".")){if(typeof n!="object"||n===null)return;n=n[i]}return n}showNarrativeReport(e){this.narrativeReport.replaceChildren();for(const t of["assumed","derived","stated"]){const n=e.claims.filter(i=>i.basis===t);if(n.length!==0){this.narrativeReport.append(this.narrativeHeading(this.messages[XA[t]]));for(const i of n){const s=document.createElement("div");s.className=`claim ${t}`;const a=document.createElement("code");a.textContent=i.path;const o=document.createElement(t==="stated"?"q":"span");o.textContent=i.rationale,s.append(a,o),this.narrativeReport.append(s)}}}if(e.gaps.length>0){this.narrativeReport.append(this.narrativeHeading(this.messages.narrativeGaps));const t=document.createElement("ul");t.className="gaps";for(const n of e.gaps){const i=document.createElement("li");i.textContent=n,t.append(i)}this.narrativeReport.append(t)}this.narrativeReport.hidden=this.narrativeReport.childElementCount===0}narrativeHeading(e){const t=document.createElement("h4");return t.textContent=e,t}setNarrativeBusy(e){this.descriptionInput.disabled=e,this.narrativeStopButton.hidden=!e,e&&(this.narrativeStatus.textContent=this.messages.narrativeWorking,this.narrativeStatus.classList.remove("error")),this.syncNarrativeEnabled()}syncNarrativeEnabled(){const e=Ns[0].name,t=this.narrativeProvider.needsCredential&&this.narrativeKeyInput.value.trim()==="",n=this.descriptionInput.value.trim()==="";this.narrativeDraftButton.disabled=!!this.narrativeAbort||t||n,this.narrativeDraftButton.title=t?this.messages.narrativeNeedsKey.replace("{source}",e):n?this.messages.narrativeNeedsAsk:"",this.narrativeKeyInput.parentElement.hidden=!this.narrativeProvider.needsCredential,this.narrativeRememberInput.parentElement.hidden=!this.narrativeProvider.needsCredential,this.narrativeWorkspaceInput.parentElement.hidden=!this.narrativeProvider.acceptsCredentialScope;const i=this.narrativeKeyInput.value.trim(),s=i!==""&&!i.startsWith("sk-ant-");this.narrativeKeyInput.classList.toggle("invalid",s),this.narrativeKeyInput.title=s?this.messages.narrativeKeyUnlikely:""}narrativeErrorFor(e){if(!(e instanceof Un))return this.messages.narrativeErrorMalformed;switch(e.kind){case"rejected":return this.messages.narrativeErrorRejected.replace("{detail}",e.detail??"");case"credential":return this.messages.narrativeErrorCredential;case"rate-limited":return this.messages.narrativeErrorRateLimited;case"refused":return this.messages.narrativeErrorRefused;case"unreachable":return this.messages.narrativeErrorUnreachable;default:return this.messages.narrativeErrorMalformed}}rememberNarrativeKey(){try{this.narrativeRememberInput.checked?(localStorage.setItem(Tt.NARRATIVE_KEY_STORAGE,this.narrativeKeyInput.value),localStorage.setItem(Tt.NARRATIVE_SCOPE_STORAGE,this.narrativeWorkspaceInput.value)):(localStorage.removeItem(Tt.NARRATIVE_KEY_STORAGE),localStorage.removeItem(Tt.NARRATIVE_SCOPE_STORAGE))}catch{}}restoreNarrativeKey(){let e=null;try{e=localStorage.getItem(Tt.NARRATIVE_KEY_STORAGE)}catch{return}e!==null&&(this.narrativeKeyInput.value=e,this.narrativeWorkspaceInput.value=localStorage.getItem(Tt.NARRATIVE_SCOPE_STORAGE)??"",this.narrativeRememberInput.checked=!0)}numberOrUndefined(e){return e===""?void 0:Number(e)}stringOrUndefined(e){return e===""?void 0:e}wrapDegrees(e,t){if(e===void 0)return;const n=(e%360+360)%360;return String(n)!==t.value&&(t.value=String(n)),n}refreshSourceRows(){this.placeSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),this.sourcePicker("place",EA,e=>{this.placeProvider=e.create()})),this.weatherSourceRow.replaceChildren(this.sourcePicker("weather",TA,e=>{this.weatherInference=new Yh(e.create()),this.scheduleWeatherLookup()})),this.terrainSourceRows.replaceChildren(this.labelledPicker("elevation",this.messages.sourceElevation,jh,()=>this.applyTerrainSources()),this.labelledPicker("imagery",this.messages.sourceImagery,Fm,()=>this.applyTerrainSources()),this.labelledPicker("decor-model",this.messages.decorModel,Xl,()=>this.applyDecorModelSource()))}sourcePicker(e,t,n){const i=document.createDocumentFragment(),s=document.createElement("select");s.id=`${e}Source`;for(const l of t){const c=document.createElement("option");c.value=l.id,c.textContent=l.name,c.title=l.credit,s.appendChild(c)}s.value=this.chosenSourceId.get(e)??t[0].id;const a=document.createElement("a");a.className="source-credit",a.target="_blank",a.rel="noopener noreferrer";const o=()=>{const l=Wr(t,s.value);s.title=l.credit,a.href=l.creditUrl,a.textContent=l.credit};return o(),s.addEventListener("change",()=>{this.chosenSourceId.set(e,s.value),o(),n(Wr(t,s.value))}),i.append(s,document.createTextNode(" "),a),i}labelledPicker(e,t,n,i){const s=document.createElement("label"),a=document.createElement("span");return a.textContent=t,s.append(a,this.sourcePicker(e,n,i)),s}applyTerrainSources(){this.sceneElement.setTerrainProviders({elevation:Wr(jh,this.chosenSourceId.get("elevation")).create(),imagery:Wr(Fm,this.chosenSourceId.get("imagery")).create()}),this.ufoElement.refresh()}applyDecorModelSource(){this.decorModelProvider=Wr(Xl,this.chosenSourceId.get("decor-model")).create(),this.sceneElement.setDecorModelProvider(this.decorModelProvider),this.refreshDecorModelOptions(),this.ufoElement.refresh()}get placeSearchLanguage(){return navigator.languages?.[0]}set placeSearchProvider(e){this.placeProvider=e}async searchPlace(){const e=this.placeNameInput.value.trim();if(e==="")return;const t=++this.placeSearchToken;this.placeStatusText.textContent=this.messages.placeSearching;let n;try{n=await this.placeProvider.search(e,{language:this.placeSearchLanguage})}catch{if(t!==this.placeSearchToken)return;this.placeStatusText.textContent=this.messages.placeSearchFailed;return}t===this.placeSearchToken&&(this.placeMatches=n,this.refreshPlaceMatches(),n.length>0&&this.applyPlaceMatch(0))}refreshPlaceMatches(){this.placeMatchSelect.replaceChildren(...this.placeMatches.map(t=>{const n=document.createElement("option");return n.textContent=t.name,n.title=t.name,n})),this.placeMatchRow.hidden=this.placeMatches.length===0;const e=this.placeMatches.length===1?this.messages.placeMatchFound:this.messages.placeMatchesFound;this.placeStatusText.textContent=this.placeMatches.length===0?this.messages.placeNotFound:`${this.placeMatches.length} ${e} `,this.placeSourceRow.hidden=this.placeMatches.length===0}applyPlaceMatch(e){const t=this.placeMatches[e];t&&(this.placeMatchSelect.selectedIndex=e,this.placeNameInput.value=t.name,this.placeNameInput.title=t.name,this.latInput.value=String(t.lat),this.lngInput.value=String(t.lng),this.namedCoordinates={lat:t.lat,lng:t.lng},this.updateObserver())}updatePlaceName(){this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent="",this.placeSourceRow.hidden=!0,this.placeNameInput.title=this.placeNameInput.value,this.namedCoordinates=void 0,this.updateObserver()}schedulePlaceReverse(){if(!this.namedCoordinates)return;const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);e===void 0||t===void 0||Math.abs(e-this.namedCoordinates.lat)<Xr&&Math.abs(t-this.namedCoordinates.lng)<Xr||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(e,t),Bm))}scheduleTimeZoneLookup(){const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);if(e===void 0||t===void 0)return;const n=this.ufoElement.sighting.event.timeZone;if(n&&n!==this.autoFilledTimeZone)return;const i=this.timeZoneLookedUpAt;i&&Math.abs(e-i.lat)<Xr&&Math.abs(t-i.lng)<Xr||(clearTimeout(this.timeZoneLookupTimer),this.timeZoneLookupTimer=setTimeout(()=>void this.lookUpTimeZone(e,t),Bm))}async lookUpTimeZone(e,t){this.timeZoneLookedUpAt={lat:e,lng:t};const n=await this.timeZoneProvider.zoneAt(e,t),i=this.ufoElement.sighting.event.timeZone;!n||i&&i!==this.autoFilledTimeZone||this.timeZones.available().includes(n)&&(this.autoFilledTimeZone=n,this.timeZoneSelect.value=n,this.updateTimeZone(),this.dispatchEvent(new CustomEvent("sightingchange")))}async reversePlace(e,t){const n=++this.placeSearchToken;let i;try{i=await this.placeProvider.reverse(e,t,{language:this.placeSearchLanguage})}catch{return}n===this.placeSearchToken&&(this.namedCoordinates={lat:e,lng:t},this.placeNameInput.value=i?.name??"",this.placeNameInput.title=i?.name??"",this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent=i?"":this.messages.placeNotFound,this.placeSourceRow.hidden=!i,this.updateObserver())}updateObserver(){if(this.ufoElement.playbackState==="playing")return;const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value),n=this.wrapDegrees(this.numberOrUndefined(this.headingInput.value),this.headingInput),i=this.numberOrUndefined(this.pitchInput.value)??0,s=this.numberOrUndefined(this.rollInput.value)??0,a=this.numberOrUndefined(this.elevationInput.value)??this.groundElevationM??0,o=Math.max(0,a-(this.groundElevationM??0)),l=this.ufoElement.sighting.event,c=this.ufoElement.sighting.witnessTrack,h=this.ufoElement.currentTime,d=this.stringOrUndefined(this.placeNameInput.value.trim());l.place=e!==void 0&&t!==void 0?[{lat:e,lng:t,name:d}]:void 0;const u=this.ufoElement.sighting.instrument,f=this.numberOrUndefined(this.focalLengthInput.value),p=(u.frame&&f!==void 0?rt.fieldOfViewDegAt(u,f):f)??this.currentFovDeg(),v=this.numberOrUndefined(this.fNumberInput.value),m=this.statedExposureSeconds(u);this.ufoElement.sighting.exposureSeconds=m===u.exposureSeconds?void 0:m;const g=this.numberOrUndefined(this.focusDistanceInput.value),M=Math.abs(p-rt.fieldOfViewDeg(u))>.01||v!==u.fNumber||g!==void 0;e===void 0&&t===void 0&&n===void 0&&i===0&&s===0&&o===0&&!M?c.removeKeyframeAt(h):c.addKeyframe(h,{lat:e,lng:t,elevationM:o,headingDeg:n,pitchDeg:i,rollDeg:s===0?void 0:s,fovDeg:p,fNumber:v,focusDistanceM:g}),this.ufoElement.refresh(),this.scheduleWeatherLookup(),this.schedulePlaceReverse(),this.scheduleTimeZoneLookup(),this.scheduleGroundElevation(),this.updateUtcOffsetValidity()}applyEdtfTimeInput(e,t){const n=e.value.trim();if(n==="")t(void 0);else{const i=Tf(n);if(!i)return;t(i)}e.setCustomValidity(""),e.classList.remove("invalid"),this.dropDurationOutrankedByDates(),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset(),this.ufoElement.refresh(),this.syncDurationField(),this.scheduleWeatherLookup()}dropDurationOutrankedByDates(){const e=this.ufoElement.sighting.event;e.durationSeconds!==void 0&&ua({...e,durationSeconds:void 0})!==void 0&&(this.ufoElement.durationSeconds=void 0)}validateEdtfTimeInput(e){const t=e.value.trim();t===""||Tf(t)||(e.setCustomValidity(this.messages.edtfInvalid),e.classList.add("invalid"))}refreshTimeZoneOptions(){const e=document.createElement("option");e.value="",e.textContent=this.messages.timeZoneManual,this.timeZoneSelect.replaceChildren(e,...this.timeZones.available().map(t=>{const n=document.createElement("option");return n.value=t,n.textContent=t,n})),this.timeZoneSelect.value=this.ufoElement.sighting.event.timeZone??""}updateTimeZone(){const e=this.stringOrUndefined(this.timeZoneSelect.value);this.ufoElement.sighting.event.timeZone=e,this.applyTimeZoneOffset()}applyTimeZoneOffset(){const e=this.ufoElement.sighting.event,t=e.timeZone&&e.time?this.timeZones.offsetHoursAt(e.timeZone,e.time):void 0;t!==void 0&&(e.utcOffsetHours=t),this.utcOffsetInput.readOnly=e.timeZone!==void 0,this.syncUtcOffsetField(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}updateUtcOffset(){this.ufoElement.sighting.event.utcOffsetHours=this.numberOrUndefined(this.utcOffsetInput.value),this.updateUtcOffsetValidity(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}updateObservationTime(){this.applyEdtfTimeInput(this.obsTimeInput,e=>{this.ufoElement.sighting.event.time=e})}updateObservationEndTime(){this.applyEdtfTimeInput(this.obsEndTimeInput,e=>{this.ufoElement.sighting.event.endTime=e})}updateWitnessMetadata(){const e=this.ufoElement.sighting,t=this.witnessFirstNamesInput.value.split(",").map(i=>i.trim()).filter(i=>i.length>0),n={id:this.stringOrUndefined(this.witnessIdInput.value),dirName:this.stringOrUndefined(this.witnessDirNameInput.value),title:this.stringOrUndefined(this.witnessTitleInput.value),lastName:this.stringOrUndefined(this.witnessLastNameInput.value),firstNames:t.length>0?t:void 0};e.witness=Object.values(n).some(i=>i!==void 0)?n:void 0,e.caseId=this.stringOrUndefined(this.caseIdInput.value),this.updateTestimony(),this.ufoElement.refresh()}updateTestimony(){const e=this.ufoElement.sighting,t=this.testimonyFollowedUpSelect.value,n={witnessAgeYears:this.numberOrUndefined(this.witnessAgeInput.value),witnessOccupation:this.witnessOccupationInput.value.trim()===""?void 0:this.said.write(e.testimony?.witnessOccupation,this.witnessOccupationInput.value,this.writingLanguage),source:this.stringOrUndefined(this.testimonySourceSelect.value),followedUp:t===""?void 0:t==="yes"};e.testimony=Object.values(n).some(i=>i!==void 0)?n:void 0}updateDescription(){this.ufoElement.sighting.event.description=this.said.write(this.ufoElement.sighting.event.description,this.descriptionInput.value,this.writingLanguage),this.ufoElement.refresh()}updateTags(){const e=this.tagsInput.value.split(",").map(t=>t.trim()).filter(t=>t.length>0).map(t=>this.tagNames.stored(t));this.ufoElement.sighting.event.tags=e.length>0?e:void 0,this.ufoElement.refresh()}applyWeatherAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;this.sceneElement.resumeWeatherAudio(),this.weatherFromRecords&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState());const e={...Ut(this.ufoElement.sighting,this.ufoElement.currentTime),cloudCover:Number(this.cloudCoverInput.value),highCloudCover:Number(this.highCloudCoverInput.value),lowerCloudCover:Number(this.cloudCoverInput.value),cloudDarkness:Number(this.cloudDarknessInput.value),cloudBaseM:this.numberOrUndefined(this.cloudBaseInput.value),precipitationType:this.precipitationTypeSelect.value,precipitationIntensity:Number(this.precipitationIntensityInput.value),windDirectionDeg:this.wrapDegrees(this.numberOrUndefined(this.windDirectionInput.value),this.windDirectionInput)??0,windSpeed:Number(this.windSpeedInput.value),storm:this.stormInput.checked};this.ufoElement.sighting.weatherTrack.addKeyframe(this.ufoElement.currentTime,e),this.ufoElement.refresh()}applyIceAlignmentAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;this.sceneElement.resumeWeatherAudio();const e={...Ut(this.ufoElement.sighting,this.ufoElement.currentTime),iceCrystalAlignment:Number(this.iceCrystalAlignmentInput.value)};this.ufoElement.sighting.weatherTrack.addKeyframe(this.ufoElement.currentTime,e),this.ufoElement.refresh()}referenceLabel(e){return this.said.read(e.title)||e.src.replace(/^data:.*$/,"…")||e.id}refreshReferenceList(){const e=this.ufoElement.sighting.references;this.referenceSelect.innerHTML="";for(const t of e){const n=document.createElement("option");n.value=t.id,n.textContent=this.referenceLabel(t),this.referenceSelect.appendChild(n)}this.currentReferenceId!==void 0&&(this.referenceSelect.value=this.currentReferenceId),this.syncReferenceFields()}selectReference(e){this.currentReferenceId=e,this.referenceSelect.value=e,this.disarmLandmark(),this.currentLandmarkId=void 0,this.referenceFit=void 0,this.syncReferenceFields()}syncReferenceFields(){const e=this.ufoElement.sighting.references.find(i=>i.id===this.currentReferenceId),t=e!==void 0;this.deleteReferenceButton.disabled=!t,this.referenceUsePoseButton.disabled=!t;for(const i of[this.referenceSelect,...this.referenceFields])i.disabled=!t,this.setRowVisible(i,t);this.setRowVisible(this.referenceUsePoseButton,t);for(const i of[this.referenceLandmarksSelect,this.addReferenceLandmarkButton,this.deleteReferenceLandmarkButton,this.referenceLandmarkLabelInput])this.setRowVisible(i,t);if(this.refreshLandmarkList(),this.setRowVisible(this.referenceAdoptPoseButton,t),this.syncCanvasMode(),!e){this.referenceStatus.textContent="";return}this.referenceTitleInput.value=this.said.read(e.title)??"";const n=e.src.startsWith("data:");this.referenceSrcInput.value=n?"":e.src,this.referenceSrcInput.disabled=n,this.referenceKindSelect.value=e.kind,this.referenceCreditInput.value=e.credit??"",this.referenceCreditUrlInput.value=e.creditUrl??"",this.referenceTInput.value=e.t===void 0?"":String(e.t/1e3),this.referenceDrawingInput.checked=e.drawing===!0,this.referenceOpacityInput.value=String(e.opacity),this.referenceHeadingInput.value=String(e.registration.headingDeg),this.referencePitchInput.value=String(e.registration.pitchDeg),this.referenceRollInput.value=String(e.registration.rollDeg??0),this.referenceFovInput.value=String(e.registration.fovDeg),this.syncReferenceStatus(e)}syncReferenceStatus(e){if(this.canvasMode()==="picture"){this.syncRegisterStatus();return}if(e.src.startsWith("data:")){const t=Math.round(e.src.length*3/4/1024);this.referenceStatus.textContent=e.src.length>lA?this.messages.referenceEmbedded.replace("{kb}",String(t)):"";return}this.referenceStatus.textContent=this.sceneElement.referenceFailedToLoad(e.src)?this.messages.referenceUnreachable:""}updateReference(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting,t=this.wrapDegrees(Number(this.referenceHeadingInput.value),this.referenceHeadingInput)??0,n=this.referenceTInput.value.trim()===""?void 0:Number(this.referenceTInput.value);e.references=e.references.map(s=>{if(s.id!==this.currentReferenceId)return s;const a=s.src.startsWith("data:")?s.src:this.referenceSrcInput.value.trim();return{...s,kind:this.referenceKindSelect.value,src:a,title:this.said.write(s.title,this.referenceTitleInput.value,this.writingLanguage),credit:this.stringOrUndefined(this.referenceCreditInput.value),creditUrl:this.stringOrUndefined(this.referenceCreditUrlInput.value),t:n===void 0||Number.isNaN(n)?void 0:Math.round(n*1e3),drawing:this.referenceDrawingInput.checked||void 0,opacity:Number(this.referenceOpacityInput.value),registration:{headingDeg:t,pitchDeg:Number(this.referencePitchInput.value)||0,rollDeg:Number(this.referenceRollInput.value)||void 0,fovDeg:Math.min(179,Math.max(1,Number(this.referenceFovInput.value)||Pl))}}});const i=e.references.find(s=>s.id===this.currentReferenceId);this.referenceSelect.options[this.referenceSelect.selectedIndex].textContent=this.referenceLabel(i),this.syncReferenceStatus(i),this.ufoElement.refresh()}useWitnessPoseForReference(){const e=tt(this.ufoElement.sighting,this.ufoElement.currentTime);e&&(this.referenceHeadingInput.value=String(this.rounded(e.headingDeg??0)),this.referencePitchInput.value=String(this.rounded(e.pitchDeg)),this.referenceRollInput.value=String(this.rounded(e.rollDeg??0)),this.referenceFovInput.value=String(this.rounded(e.fovDeg)),this.updateReference())}addReference(e,t,n={}){const i=this.ufoElement.sighting,s=tt(this.ufoElement.sighting,this.ufoElement.currentTime),a=`picture-${i.references.length+1}`,o={id:a,kind:"photo",src:e,title:t?this.said.write(void 0,t,this.writingLanguage):void 0,opacity:oA,registration:{headingDeg:s?.headingDeg??0,pitchDeg:s?.pitchDeg??0,fovDeg:Pl},...n};i.references=[...i.references,o],this.currentReferenceId=a,this.refreshReferenceList(),this.ufoElement.refresh()}addReferenceFromAddress(){this.addReference(""),this.referenceSrcInput.focus()}async addReferenceFromFile(){const e=this.addReferenceFileInput.files?.[0];if(!e)return;const t=await new Promise((n,i)=>{const s=new FileReader;s.onload=()=>n(s.result),s.onerror=()=>i(s.error),s.readAsDataURL(e)});this.addReferenceFileInput.value="",this.addReference(t,e.name.replace(/\.[^.]+$/,""))}currentReference(){return this.ufoElement.sighting.references.find(e=>e.id===this.currentReferenceId)}currentLandmarks(){return this.currentReference()?.landmarks??[]}writeLandmarks(e){const t=this.ufoElement.sighting;t.references=t.references.map(n=>n.id===this.currentReferenceId?{...n,landmarks:e.length>0?e:void 0}:n)}beginReferenceDrag(e){const t=this.currentReference();if(!t)return;if(this.armingLandmark||this.pendingLandmark){this.nameLandmarkAt(e);return}const n=this.landmarkEndAt(e);if(n){this.selectLandmark(n.landmarkId),this.referenceDragState={kind:"anchor",...n},this.setCanvasCursor("landmark"),this.startDragListening();return}this.referenceDragState={kind:"picture",startPointer:e,startHeadingDeg:t.registration.headingDeg,startPitchDeg:t.registration.pitchDeg,moved:!1},this.setCanvasCursor("panning"),this.startDragListening()}landmarkEndAt(e){const t=this.currentReference(),n=t?this.sceneElement.referenceAspect(t.id):void 0;if(!t||n===void 0)return;const i=8;for(const s of this.currentLandmarks()){const a=this.canvasPointOfDirection(Fn.worldDirectionOf(s.picture,t.registration,n));if(a&&Math.hypot(a.x-e.x,a.y-e.y)<=i)return{landmarkId:s.id,end:"picture"};const o=this.canvasPointOfDirection(Fn.worldDirection(s.scene));if(o&&Math.hypot(o.x-e.x,o.y-e.y)<=i)return{landmarkId:s.id,end:"scene"}}}onReferenceDragPointerMove(e){const t=this.referenceDragState,n=this.canvasPointFromEvent(e);if(!t||!n)return;if(t.kind==="anchor"){this.moveLandmarkEnd(t.landmarkId,t.end,n);return}const i=n.x-t.startPointer.x,s=n.y-t.startPointer.y;if(!t.moved&&Math.hypot(i,s)<3)return;t.moved=!0;const a=this.currentFovDeg()/this.ufoElement.canvasElement.height;this.referenceHeadingInput.value=String(this.rounded(t.startHeadingDeg+i*a)),this.referencePitchInput.value=String(this.rounded(Math.max(-90,Math.min(90,t.startPitchDeg-s*a)))),this.updateReference()}moveLandmarkEnd(e,t,n){const i=this.currentReference(),s=i?this.sceneElement.referenceAspect(i.id):void 0;if(!i||s===void 0)return;const a=this.directionAtCanvasPoint(n);this.writeLandmarks(this.currentLandmarks().map(o=>{if(o.id!==e)return o;if(t==="scene")return{...o,scene:Fn.aimOf(a)};const l=Fn.picturePointOf(a,i.registration,s);return l?{...o,picture:l}:o})),this.ufoElement.refresh()}endReferenceDrag(){const e=this.referenceDragState;this.referenceDragState=void 0,this.setCanvasCursor(this.canvasMode()==="picture"?"pan":this.hoverCursor),document.removeEventListener("pointermove",this.handleDragPointerMove),document.removeEventListener("pointerup",this.handleDragPointerUp),e?.kind==="anchor"&&this.fitReferenceToLandmarks()}onReferenceWheel(e){if(this.canvasMode()!=="picture")return;e.preventDefault();const t=Number(this.referenceFovInput.value)||Pl,n=Math.min(179,Math.max(1,t*Math.exp(Math.sign(e.deltaY)*.05)));this.referenceFovInput.value=String(this.rounded(n)),this.updateReference()}directionAtCanvasPoint(e){const t=this.ufoElement.canvasElement;return this.sceneElement.directionAt(e.x/t.width*2-1,-(e.y/t.height*2-1))}armLandmark(){this.currentReference()&&(this.armingLandmark=!0,this.pendingLandmark=void 0,this.setCanvasCursor("landmark"),this.syncRegisterStatus(),this.ufoElement.refresh())}disarmLandmark(){this.armingLandmark=!1,this.pendingLandmark=void 0,this.canvasMode()==="picture"&&(this.setCanvasCursor("pan"),this.syncRegisterStatus()),this.ufoElement.refresh()}nameLandmarkAt(e){const t=this.currentReference();if(!t)return;const n=this.directionAtCanvasPoint(e);if(!this.pendingLandmark){const a=this.sceneElement.referenceAspect(t.id);if(a===void 0){this.referenceStatus.textContent=this.messages.referenceNotLoaded;return}const o=Fn.picturePointOf(n,t.registration,a);if(!o){this.referenceStatus.textContent=this.messages.referenceLandmarkOffPicture;return}this.pendingLandmark=o,this.syncRegisterStatus(),this.ufoElement.refresh();return}const i=this.currentLandmarks(),s=this.nextLandmarkId(i);this.writeLandmarks([...i,{id:s,picture:this.pendingLandmark,scene:Fn.aimOf(n)}]),this.armingLandmark=!1,this.pendingLandmark=void 0,this.currentLandmarkId=s,this.setCanvasCursor("pan"),this.fitReferenceToLandmarks()}nextLandmarkId(e){let t=e.length+1;for(;e.some(n=>n.id===`landmark-${t}`);)t++;return`landmark-${t}`}fitReferenceToLandmarks(){const e=this.currentReference(),t=e?this.sceneElement.referenceAspect(e.id):void 0;if(!e||t===void 0)return;const n=this.currentLandmarks(),i=Fn.solve(n,t,e.registration.fovDeg);i?(this.referenceFit={n:n.length,residualDeg:i.residualDeg},this.referenceHeadingInput.value=String(this.rounded(i.registration.headingDeg)),this.referencePitchInput.value=String(this.rounded(i.registration.pitchDeg)),this.referenceRollInput.value=String(this.rounded(i.registration.rollDeg??0)),this.referenceFovInput.value=String(this.rounded(i.registration.fovDeg)),this.updateReference()):this.referenceFit=void 0,this.refreshLandmarkList(),this.syncRegisterStatus(),this.ufoElement.refresh()}landmarkResidualDeg(e,t,n){return Fn.worldDirectionOf(e.picture,t.registration,n).angleTo(Fn.worldDirection(e.scene))*180/Math.PI}landmarkLabel(e,t){const n=this.said.read(e.label);return n?`${t+1} · ${n}`:String(t+1)}refreshLandmarkList(){const e=this.currentReference(),t=this.currentLandmarks(),n=e?this.sceneElement.referenceAspect(e.id):void 0;this.referenceLandmarksSelect.innerHTML="";for(const[s,a]of t.entries()){const o=document.createElement("option");o.value=a.id;const l=e&&n!==void 0?` · ${this.landmarkResidualDeg(a,e,n).toFixed(1)}°`:"";o.textContent=this.landmarkLabel(a,s)+l,this.referenceLandmarksSelect.appendChild(o)}this.currentLandmarkId!==void 0&&!t.some(s=>s.id===this.currentLandmarkId)&&(this.currentLandmarkId=void 0),this.currentLandmarkId!==void 0&&(this.referenceLandmarksSelect.value=this.currentLandmarkId);const i=t.find(s=>s.id===this.currentLandmarkId);this.referenceLandmarksSelect.disabled=t.length===0,this.deleteReferenceLandmarkButton.disabled=i===void 0,this.referenceLandmarkLabelInput.disabled=i===void 0,this.shadow.activeElement!==this.referenceLandmarkLabelInput&&(this.referenceLandmarkLabelInput.value=this.said.read(i?.label)??"")}selectLandmark(e){this.currentLandmarkId=e,this.refreshLandmarkList(),this.ufoElement.refresh()}updateLandmarkLabel(){const e=this.currentLandmarkId;if(e===void 0)return;this.writeLandmarks(this.currentLandmarks().map(o=>o.id===e?{...o,label:this.said.write(o.label,this.referenceLandmarkLabelInput.value,this.writingLanguage)}:o));const t=this.referenceLandmarksSelect.options[this.referenceLandmarksSelect.selectedIndex],n=this.currentLandmarks(),i=n.findIndex(o=>o.id===e),s=this.currentReference(),a=s?this.sceneElement.referenceAspect(s.id):void 0;if(t&&i>=0){const o=s&&a!==void 0?` · ${this.landmarkResidualDeg(n[i],s,a).toFixed(1)}°`:"";t.textContent=this.landmarkLabel(n[i],i)+o}this.ufoElement.refresh()}deleteLandmark(){const e=this.currentLandmarkId;if(e===void 0)return;const t=this.currentLandmarks().filter(n=>n.id!==e);this.writeLandmarks(t),this.currentLandmarkId=t[t.length-1]?.id,this.fitReferenceToLandmarks()}landmarkHint(){const e=this.currentLandmarks().length+1;if(this.pendingLandmark)return this.messages.referenceLandmarkScene.replace("{n}",String(e));if(this.armingLandmark)return this.messages.referenceLandmarkPicture.replace("{n}",String(e))}syncRegisterStatus(){const e=this.landmarkHint();e?this.referenceStatus.textContent=e:this.referenceFit?this.referenceStatus.textContent=this.messages.referenceLandmarksFit.replace("{n}",String(this.referenceFit.n)).replace("{deg}",this.referenceFit.residualDeg.toFixed(1)):this.referenceStatus.textContent=this.messages.referenceRegisterHint}canvasPointOfDirection(e){const t=this.sceneElement.screenPointOf(e);if(!t)return;const n=this.ufoElement.canvasElement;return{x:(t.ndcX+1)/2*n.width,y:(1-t.ndcY)/2*n.height}}paintPictureOverlay=e=>{const t=this.currentReference();if(!t)return;const n=this.sceneElement.referenceAspect(t.id);if(n===void 0)return;const{registration:i}=t,s=[{u:0,v:0},{u:1,v:0},{u:1,v:1},{u:0,v:1}].map(o=>this.canvasPointOfDirection(Fn.worldDirectionOf(o,i,n))),a=this.currentLandmarks().map((o,l)=>({picture:this.canvasPointOfDirection(Fn.worldDirectionOf(o.picture,i,n)),scene:this.canvasPointOfDirection(Fn.worldDirection(o.scene)),label:this.landmarkLabel(o,l),selected:o.id===this.currentLandmarkId,residualDeg:this.landmarkResidualDeg(o,t,n)}));this.pendingLandmark&&a.push({picture:this.canvasPointOfDirection(Fn.worldDirectionOf(this.pendingLandmark,i,n)),scene:void 0,label:String(this.currentLandmarks().length+1),selected:!0,residualDeg:void 0}),e.paintPictureFrame(s.every(o=>o!==void 0)?s:void 0,a.filter(o=>o.picture!==void 0),this.landmarkHint())};adoptReferencePose(){const e=this.currentReference();if(!e)return;const{headingDeg:t,pitchDeg:n,rollDeg:i}=e.registration;this.headingInput.value=String(this.rounded(t)),this.pitchInput.value=String(this.rounded(n)),this.rollInput.value=String(this.rounded(i??0)),this.updateObserver();const s=this.ufoElement.currentTime,a=this.ufoElement.sighting.witnessTrack.toJSON().keyframes.findIndex(c=>c.t===s);if(a<0)return;const o=this.messages.referenceAdoptRationale.replace("{title}",this.referenceLabel(e)).replace("{n}",String(this.currentLandmarks().length)).replace("{deg}",(this.referenceFit?.residualDeg??0).toFixed(1)),l=[["headingDeg",t],["pitchDeg",n],["rollDeg",i??0]];for(const[c,h]of l)this.ufoElement.sighting.provenance.set(`witnessTrack.keyframes.${a}.pose.${c}`,{basis:"derived",rationale:o,of:this.rounded(h)})}syncStreetSearchAvailability(){const e=this.numberOrUndefined(this.latInput.value)!==void 0&&this.numberOrUndefined(this.lngInput.value)!==void 0;this.referenceStreetSearchButton.disabled=!e}async searchStreetPictures(){const e=tt(this.ufoElement.sighting,0),t=e?.lat??this.numberOrUndefined(this.latInput.value),n=e?.lng??this.numberOrUndefined(this.lngInput.value);if(t===void 0||n===void 0)return;const i=300;this.referenceStatus.textContent=this.messages.referenceStreetSearching,this.referenceStreetSearchButton.disabled=!0;try{this.streetPictures=await this.streetPictures$.nearby(t,n,i)}catch{this.streetPictures=[],this.referenceStatus.textContent=this.messages.referenceStreetFailed,this.referenceStreetSearchButton.disabled=!1;return}this.referenceStreetSearchButton.disabled=!1,this.referenceStreetSelect.innerHTML="";for(const[a,o]of this.streetPictures.entries()){const l=document.createElement("option");l.value=String(a),l.textContent=this.streetPictureLabel(o,this.messages.referenceStreetItem),this.referenceStreetSelect.appendChild(l)}const s=this.streetPictures.length>0;this.referenceStreetSelect.hidden=!s,this.referenceStreetAddButton.hidden=!s,this.referenceStatus.textContent=s?"":this.messages.referenceStreetNone.replace("{m}",String(i))}streetPictureLabel(e,t){return t.replace("{distance}",String(Math.round(e.distanceM))).replace("{bearing}",String(Math.round(e.bearingDeg))).replace("{date}",e.takenAt.slice(0,10)).replace("{panorama}",e.panorama?this.messages.referenceStreetPanorama:"")}addStreetPicture(){const e=this.streetPictures[Number(this.referenceStreetSelect.value)];e&&this.addReference(e.src,this.streetPictureLabel(e,this.messages.referenceStreetTitle),{kind:e.panorama?"panorama":"photo",credit:e.credit,creditUrl:e.creditUrl,registration:{headingDeg:e.azimuthDeg??0,pitchDeg:0,fovDeg:Pl}})}deleteReference(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting;e.references=e.references.filter(t=>t.id!==this.currentReferenceId),this.currentReferenceId=e.references[0]?.id,this.refreshReferenceList(),this.ufoElement.refresh()}buildSoundKindOptions(){for(const e of a1){const t=document.createElement("option");t.value=e,t.textContent=this.soundKindLabel(e,this.messages),this.soundKindOptions.set(e,t),this.soundKindSelect.appendChild(t)}}soundKindLabel(e,t){switch(e){case"hum":return t.soundHum;case"whistle":return t.soundWhistle;case"rumble":return t.soundRumble;case"crackle":return t.soundCrackle;default:return t.soundNone}}applySoundAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;const e=this.readSound();this.ufoElement.sighting.soundTrack.addKeyframe(this.ufoElement.currentTime,e),this.updateSoundPitchReadout(e.pitchHz),this.updateSoundFieldsDisabledState(e),this.ufoElement.refresh(),this.previewSound(e)}previewSound(e){clearTimeout(this.soundPreviewTimer),this.ufoElement.previewSound(e),this.soundPreviewTimer=setTimeout(()=>this.ufoElement.stopSoundPreview(),LA)}readSound(){return{kind:this.soundKindSelect.value,volume:Number(this.soundVolumeInput.value),pitchHz:Number(this.soundPitchInput.value),src:this.soundSrcInput.value.trim()||void 0}}syncSoundFromTimeline(){if(this.ufoElement.playbackState==="playing")return;const e=Pu(this.ufoElement.sighting,this.ufoElement.currentTime),t=this.shadow.activeElement;t!==this.soundKindSelect&&(this.soundKindSelect.value=e.kind),t!==this.soundVolumeInput&&(this.soundVolumeInput.value=String(e.volume)),t!==this.soundPitchInput&&(this.soundPitchInput.value=String(e.pitchHz)),t!==this.soundSrcInput&&(this.soundSrcInput.value=e.src??""),this.updateSoundPitchReadout(e.pitchHz),this.updateSoundFieldsDisabledState(e)}updateSoundPitchReadout(e){this.soundPitchValue.textContent=`${Math.round(e)} Hz`}updateSoundFieldsDisabledState(e){const t=e.kind==="none"&&!e.src;this.soundVolumeInput.disabled=t,this.soundSrcInput.disabled=t,this.soundPitchInput.disabled=t||e.src!==void 0}set weatherProvider(e){this.weatherInference=new Yh(e),this.scheduleWeatherLookup()}onWeatherInferredToggled(){this.weatherFromRecords=this.weatherInferredInput.checked,this.weatherFromRecords?this.scheduleWeatherLookup():(this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())}scheduleWeatherLookup(){this.weatherFromRecords&&(clearTimeout(this.weatherLookupTimer),this.weatherLookupTimer=setTimeout(()=>void this.inferWeather(),kA))}cancelWeatherLookup(){clearTimeout(this.weatherLookupTimer),this.weatherLookupToken++,this.weatherLookupPending=!1}async inferWeather(){if(!this.weatherFromRecords)return;const e=++this.weatherLookupToken;this.weatherLookupPending=!0,this.syncWeatherSourceState();const t=await this.weatherInference.infer(this.ufoElement.sighting);e!==this.weatherLookupToken||!this.weatherFromRecords||(this.weatherLookupPending=!1,this.weatherLookupResult=t,t.status==="inferred"?(this.weatherInference.applyTo(this.ufoElement.sighting,t),this.weatherTrackSpan=this.ufoElement.seekableDuration,this.ufoElement.refresh(),this.syncWeatherFromTimeline()):this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())}ensureWeatherTrackSpan(){if(!this.weatherFromRecords||this.ufoElement.sighting.weatherSource===void 0)return;const e=this.ufoElement.seekableDuration;this.weatherTrackSpan===void 0||e===this.weatherTrackSpan||(this.weatherTrackSpan=e,this.scheduleWeatherLookup())}syncWeatherSourceState(){const e=this.ufoElement.sighting.weatherSource,t=this.weatherFromRecords;for(const o of this.weatherFields)o.disabled=t&&e!==void 0&&o!==this.iceCrystalAlignmentInput||this.ufoElement.playbackState==="playing",this.ufoElement.playbackState==="playing"?o.title=this.messages.weatherWhilePlaying:o.title===this.messages.weatherWhilePlaying&&(o.title="");const n=this.weatherInference.canInfer(this.ufoElement.sighting);this.weatherInferredInput.disabled=!n,this.weatherInferredInput.checked=n&&this.weatherFromRecords;const i=n?this.messages.weatherInferredTitle:this.messages.weatherNeedsDateAndPlace;this.weatherInferredInput.title=i,this.labelWeatherInferred.title=i;const s=t&&e!==void 0;if(this.weatherSourceLink.hidden=!s,s){this.weatherSourceRow.hidden=!1,this.weatherSourceText.textContent="",this.weatherSourceLink.href=e.url,this.weatherSourceLink.textContent=this.observationInstantLabel();return}const a=t?this.weatherStatusMessage():"";this.weatherSourceText.textContent=a===""?"":`${a} `,this.weatherSourceRow.hidden=a===""}weatherStatusMessage(){if(this.weatherLookupPending)return this.messages.weatherLookingUp;switch(this.weatherLookupResult?.status){case"unavailable":return this.messages.weatherNoRecord;case"failed":return this.messages.weatherLookupFailed;default:return""}}observationInstantLabel(){const e=this.ufoElement.sighting.event,t=e.time&&Ds(e.time,e.place?.[0]?.lng??0,e.utcOffsetHours);return t?`, ${t.toISOString().slice(0,16).replace("T"," ")} UTC`:""}syncWeatherOwnership(){const e=this.ufoElement.sighting;this.cancelWeatherLookup(),this.weatherLookupResult=void 0,this.weatherFromRecords=e.weatherSource!==void 0||e.weatherTrack.allKeyframes.length===0,this.syncWeatherSourceState(),this.weatherFromRecords&&e.weatherSource===void 0&&this.scheduleWeatherLookup()}syncDurationField(){if(this.shadow.activeElement!==this.durationInput){const e=ua(this.ufoElement.sighting.event);this.durationInput.value=e!==void 0?String(e/1e3):""}this.updateDurationValidity()}updateDurationValidity(){const e=this.durationInput.value==="";this.durationInput.classList.toggle("missing-required",e),this.markUnansweredQuestions(),this.durationInput.setAttribute("aria-invalid",String(e));const t=u1(this.ufoElement.sighting.event);this.durationInput.title=t==="imprecise"?this.messages.durationImprecise:""}syncPlaybackControls(){this.ensureWeatherTrackSpan();const e=this.ufoElement.playbackState==="playing",t=this.ufoElement.seekableDuration>0;this.playPauseButton.textContent=e?"⏸":"▶",this.playPauseButton.disabled=!t;const n=t?e?this.messages.pause:this.messages.play:this.messages.noDuration;this.playPauseButton.title=n,this.playPauseButton.setAttribute("aria-label",n),this.loopButton.setAttribute("aria-pressed",String(this.ufoElement.autoReplayEnabled)),this.seekInput.max=String(this.ufoElement.seekableDuration),this.shadow.activeElement!==this.seekInput&&(this.seekInput.value=String(this.ufoElement.currentTime)),this.timeStartLabel.textContent=this.ufoElement.positionLabel,this.timeEndLabel.textContent=this.ufoElement.durationLabel,this.syncTimeDisplaySwitch()}switchTimeDisplay(){this.ufoElement.toggleTimeDisplay(),this.timeStartLabel.textContent=this.ufoElement.positionLabel,this.timeEndLabel.textContent=this.ufoElement.durationLabel,this.syncTimeDisplaySwitch()}syncTimeDisplaySwitch(){const e=this.ufoElement.canSwitchTimeDisplay,t=this.ufoElement.showingClockTime?this.messages.switchToElapsed:this.messages.switchToClockTime;for(const[n,i]of[[this.timeStartLabel,this.messages.currentPosition],[this.timeEndLabel,this.messages.duration]])n.title=e?`${i} — ${t}`:i,n.classList.toggle("switchable",e),e?(n.setAttribute("role","button"),n.setAttribute("tabindex","0")):(n.removeAttribute("role"),n.removeAttribute("tabindex"))}static TIME_QUALIFIERS=[{value:"",key:"timeQualifierExact"},{value:"~",key:"timeQualifierApproximate"},{value:"?",key:"timeQualifierUncertain"},{value:"%",key:"timeQualifierBoth"}];refreshTimeQualifierOptions(){for(const e of[this.obsTimeQualifier,this.obsEndTimeQualifier]){const t=e.value;e.replaceChildren(...Tt.TIME_QUALIFIERS.map(n=>{const i=document.createElement("option");return i.value=n.value,i.textContent=this.messages[n.key],i})),e.value=t}}qualifierOf(e){const t=e.trim().slice(-1);return"?~%".includes(t)?t:""}isPickable(e){return e?e.year!==void 0&&e.month!==void 0&&e.day!==void 0&&e.hour!==void 0&&e.minute!==void 0&&(e.second===void 0||e.second===0):!1}pickerValueOf(e){if(!this.isPickable(e))return"";const t=(n,i=2)=>String(n).padStart(i,"0");return`${t(e.year,4)}-${t(e.month)}-${t(e.day)}T${t(e.hour)}:${t(e.minute)}`}writeFromPicker(e,t,n,i){e.value===""&&e.validity.badInput||(n.value=e.value===""?"":`${e.value}${t.value}`,i())}chooseTimeInputMode(){const e=this.ufoElement.sighting.event,t=n=>n===void 0||this.isPickable(n);this.setEdtfMode(!(t(e.time)&&t(e.endTime)))}setEdtfMode(e){this.edtfMode=e,this.edtfModeButton.setAttribute("aria-pressed",String(e));for(const[t,n,i]of[[this.obsTimeInput,this.obsTimeNativeInput,this.obsTimeQualifier],[this.obsEndTimeInput,this.obsEndTimeNativeInput,this.obsEndTimeQualifier]])t.hidden=!e,n.hidden=e,i.hidden=e}syncObservationTimeFields(){const e=this.ufoElement.sighting.event.time;this.obsTimeInput.value=e?Kl(e):"",this.obsTimeNativeInput.value=this.pickerValueOf(e),this.obsTimeQualifier.value=this.qualifierOf(this.obsTimeInput.value),this.obsTimeInput.setCustomValidity(""),this.obsTimeInput.classList.remove("invalid")}syncObservationEndTimeFields(){const e=this.ufoElement.sighting.event.endTime;this.obsEndTimeInput.value=e?Kl(e):"",this.obsEndTimeNativeInput.value=this.pickerValueOf(e),this.obsEndTimeQualifier.value=this.qualifierOf(this.obsEndTimeInput.value),this.obsEndTimeInput.setCustomValidity(""),this.obsEndTimeInput.classList.remove("invalid")}syncUtcOffsetField(){const e=this.ufoElement.sighting.event.utcOffsetHours;this.utcOffsetInput.value=e===void 0?"":String(e),this.updateUtcOffsetValidity()}updateUtcOffsetValidity(){const e=this.ufoElement.sighting.event.utcOffsetHours,t=this.ufoElement.sighting.event.place?.[0]?.lng,n=t===void 0?void 0:Math.round(t/15),i=e!==void 0&&n!==void 0&&Math.abs(e-n)>FA;this.utcOffsetInput.classList.toggle("invalid",i),this.utcOffsetInput.title=i?this.messages.utcOffsetImplausible.replace("{solar}",n>=0?`+${n}`:String(n)):""}scheduleGroundElevation(){const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);e===void 0||t===void 0||this.groundElevationFor&&this.isSamePlace(this.groundElevationFor,e,t)||(clearTimeout(this.groundElevationTimer),this.groundElevationTimer=setTimeout(()=>void this.applyGroundElevation(e,t),NA))}isSamePlace(e,t,n){return Math.abs(e.lat-t)<Xr&&Math.abs(e.lng-n)<Xr}async applyGroundElevation(e,t){const n=++this.groundElevationToken,i=Wr(jh,this.chosenSourceId.get("elevation")),s=await new pf(i.create()).at(e,t);if(n!==this.groundElevationToken||s===void 0)return;this.groundElevationFor={lat:e,lng:t};const a=Math.max(0,(this.numberOrUndefined(this.elevationInput.value)??0)-(this.groundElevationM??0));this.groundElevationM=Math.round(s),this.syncElevationField(a),this.updateObserver()}syncElevationField(e){const t=this.groundElevationM;this.elevationInput.value=String(Math.round((t??0)+e)),this.elevationInput.min=t===void 0?"":String(t),this.elevationInput.title=t===void 0?"":this.messages.altitudeAboveSeaLevel,this.groundElevationOutput.textContent=t===void 0?"":this.messages.groundAt.replace("{m}",String(t))}syncGroundElevationField(){this.groundElevationToken++,clearTimeout(this.groundElevationTimer),this.groundElevationM=void 0,this.groundElevationFor=void 0,this.syncElevationField(tt(this.ufoElement.sighting,0)?.elevationM??0),this.scheduleGroundElevation()}syncPlaceNameField(){const e=this.ufoElement.sighting.event.place?.[0],t=e?.name??"";this.placeNameInput.value=t,this.placeNameInput.title=t,this.namedCoordinates=e&&t?{lat:e.lat,lng:e.lng}:void 0,this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent=""}syncWitnessMetadataFields(){const e=this.ufoElement.sighting;this.witnessIdInput.value=e.witness?.id??"",this.witnessDirNameInput.value=e.witness?.dirName??"",this.witnessTitleInput.value=e.witness?.title??"",this.witnessLastNameInput.value=e.witness?.lastName??"",this.witnessFirstNamesInput.value=e.witness?.firstNames?.join(", ")??"",this.caseIdInput.value=e.caseId??"",this.witnessAgeInput.value=e.testimony?.witnessAgeYears?.toString()??"",this.witnessOccupationInput.value=this.said.read(e.testimony?.witnessOccupation)??"",this.testimonySourceSelect.value=e.testimony?.source??"",this.testimonyFollowedUpSelect.value=e.testimony?.followedUp===void 0?"":e.testimony.followedUp?"yes":"no",this.descriptionInput.value=this.said.read(e.event.description)??"",this.showTags(),this.instrumentSelect.value=e.instrument.id}syncWeatherFromTimeline(){if(this.cloudEditor?.sync(),this.ufoElement.playbackState==="playing")return;const e=Ut(this.ufoElement.sighting,this.ufoElement.currentTime),t=this.shadow.activeElement;t!==this.cloudCoverInput&&(this.cloudCoverInput.value=String(e.cloudCover)),t!==this.highCloudCoverInput&&(this.highCloudCoverInput.value=String(e.highCloudCover??0)),t!==this.iceCrystalAlignmentInput&&(this.iceCrystalAlignmentInput.value=String(e.iceCrystalAlignment??.65)),t!==this.cloudDarknessInput&&(this.cloudDarknessInput.value=String(e.cloudDarkness)),t!==this.cloudBaseInput&&(this.cloudBaseInput.value=e.cloudBaseM===void 0?"":String(e.cloudBaseM)),t!==this.precipitationTypeSelect&&(this.precipitationTypeSelect.value=e.precipitationType),t!==this.precipitationIntensityInput&&(this.precipitationIntensityInput.value=String(e.precipitationIntensity)),t!==this.windDirectionInput&&(this.windDirectionInput.value=String(Math.round(e.windDirectionDeg))),t!==this.windSpeedInput&&(this.windSpeedInput.value=String(Math.round(e.windSpeed*2)/2)),t!==this.stormInput&&(this.stormInput.checked=e.storm)}syncObserverFromTimeline(){if(this.ufoElement.playbackState==="playing")return;this.syncStreetSearchAvailability();const e=this.ufoElement.sighting,t=e.witnessTrack.getInterpolatedPoseAt(this.ufoElement.currentTime),n=e.event.place?.[0],i=this.shadow.activeElement;i!==this.latInput&&(this.latInput.value=t?.lat!==void 0?String(t.lat):n?String(n.lat):""),i!==this.lngInput&&(this.lngInput.value=t?.lng!==void 0?String(t.lng):n?String(n.lng):""),i!==this.headingInput&&(this.headingInput.value=t?.headingDeg!==void 0?String(this.rounded(t.headingDeg)):""),i!==this.pitchInput&&(this.pitchInput.value=String(this.rounded(t?.pitchDeg??0)),this.rollInput.value=String(this.rounded(t?.rollDeg??0))),i!==this.elevationInput&&this.syncElevationField(t?.elevationM??0)}get appearance(){return{...this.currentAppearance}}set appearance(e){this.setAppearance(e)}setAppearance(e){const t="presetId"in e;this.currentAppearance={...this.currentAppearance,...e},this.updatePresetButtons(),!(this.isRecording||this.ufoElement.playbackState==="playing")&&this.applyAppearanceAtPlayhead(void 0,t)}applyAppearanceAtPlayhead(e,t=!0){const n=this.ufoElement.sighting.timeline,i=this.ufoElement.currentTime,s=n.getInterpolatedShapeAt(i,this.currentSourceId),a=this.buildAppearanceShape(e??s?.bounds??this.defaultBounds(),s,t);this.commitShapes(i,[{sourceId:this.currentSourceId,shape:a}]),this.ufoElement.refresh()}buildAppearanceShape(e,t,n=!0){if(t&&!n)return{...t,color:this.currentAppearance.color,transparency:this.currentAppearance.transparency,haloScale:this.currentAppearance.haloScale,blur:this.currentAppearance.blur,brightness:this.currentAppearance.brightness};const i=_f(e,this.currentAppearance);return t?{...i,angle:t.angle,title:t.title,selected:t.selected}:i}toggleSkyDetails(){const e=this.skyDetailsButton.getAttribute("aria-expanded")!=="true";this.skyDetailsButton.setAttribute("aria-expanded",String(e)),this.skyDetailsButton.textContent=e?"▴":"▾",this.skyDetailsButton.title=e?this.messages.skyDetailsHide:this.messages.skyDetails,this.skyDetailsButton.setAttribute("aria-label",this.skyDetailsButton.title);for(const t of this.clampedLines)t.classList.toggle("clamped",!e)}isGroupOpen(e){return e.getAttribute("aria-expanded")==="true"}toggleGroup(e,t){this.cloudEditor?.stopManipulation();for(const[n,i]of this.groupTabs.entries()){const s=i===e&&t;i.setAttribute("aria-expanded",String(s)),this.groupPanels[n].hidden=!s}this.syncCanvasMode()}isGroupIdOpen(e){const t=this.groupTabs.find(n=>n.getAttribute("aria-controls")===e);return t!==void 0&&this.isGroupOpen(t)}canvasMode(){return this.isGroupIdOpen("group-reference")&&this.currentReferenceId!==void 0?"picture":this.isGroupIdOpen("group-shape")?"shape":"scene"}syncCanvasMode(){const e=this.canvasMode(),t=e==="picture",n=this.lastCanvasMode==="picture",i=e!==this.lastCanvasMode;this.lastCanvasMode=e,this.ufoElement.selectionShown=e==="shape",this.ufoElement.overlayPainter=t?this.paintPictureOverlay:void 0,i&&this.ufoElement.refresh(),t!==n&&this.setCanvasCursor(t?"pan":this.hoverCursor),!t&&(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark();const s=this.currentReference();s&&this.syncReferenceStatus(s),this.syncStreetSearchAvailability()}openSubgroup(e){this.cloudEditor?.stopManipulation();const t=e.parentElement;for(const n of this.subgroupTabs){if(n.parentElement!==t)continue;const i=n===e;n.setAttribute("aria-expanded",String(i)),this.shadow.getElementById(n.getAttribute("aria-controls")).hidden=!i}}revealSubgroupOf(e){const t=e.closest(".subgroup-panel"),n=t&&this.subgroupTabs.find(i=>i.getAttribute("aria-controls")===t.id);n&&this.openSubgroup(n)}static SUMMARY_GROUPS=["observation","witness","location","decor","temporal","weather","sound"];static PANEL_ORDER=["observation","witness","location","decor","temporal","weather","sound","shape"];refreshParamSummary(){const t=this.paramSummaryBuilder.entriesFor(this.ufoElement.sighting,this.ufoElement.currentTime,{decorId:this.currentDecorId,decorPicker:!0,groundElevationM:this.groundElevationM??0}).map(i=>({...i,panel:Tt.SUMMARY_GROUPS.indexOf(i.group)})),n=t.map(i=>`${i.field}=${i.label}=${i.value}${i.unit}${i.fromSource?"*":""}`).join("|");n!==this.paramSummarySignature&&(this.paramSummarySignature=n,this.paramChips=t,this.renderParamSummary(),this.runAssessments())}paramChips=[];renderParamSummary(){const e=Tt.NESTED_GROUPS,t=[];let n;for(const i of[...this.paramChips,...this.assessmentChips]){if(n&&n.group!==i.group&&(n=void 0),e.includes(i.group)&&!n){const a=document.createElement("span");a.className="param-nest",a.dataset.group=i.group;const o=document.createElement("span");o.className="param-nest-label",o.textContent=i.group==="assessment"?this.messages.assessmentGroup:Tt.tabLabel(this.groupTabs[Tt.SUMMARY_GROUPS.indexOf(i.group)]),a.append(o),n={group:i.group,element:a},t.push(a)}const s=this.paramChip(i);n?n.element.append(s):t.push(s)}this.paramSummary.replaceChildren(...t)}static NESTED_GROUPS=["witness","decor","assessment"];static QUESTION_FIELDS={when:{panel:"temporal",fields:["obs-time","obs-time-native"]},where:{panel:"location",fields:["lat","lng"]},facing:{panel:"location",fields:["heading"]},"apparent-size":{panel:"shape",fields:[]},"sky-position":{panel:"shape",fields:[]},"how-long":{panel:"temporal",fields:["durationSeconds","obs-end-time","obs-end-time-native"]},appearance:{panel:"shape",fields:["shapeTitle","color"]},movement:{panel:"shape",fields:[]},sound:{panel:"sound",fields:["soundKind"]},conditions:{panel:"weather",fields:["cloudCover"]}};assessmentChips=[];assessmentToken=0;async runAssessments(){const e=++this.assessmentToken,t=await new E1(this.messages).read(this.ufoElement.sighting);e===this.assessmentToken&&(this.assessmentChips=t.entries.map(n=>({...n,panel:Tt.PANEL_ORDER.indexOf(n.about??"")})),this.markUnansweredQuestions(t.unanswered),this.renderParamSummary())}static tabLabel(e){return(e.querySelector("span:not(.tab-badge)")??e).textContent.trim()}static badgeOn(e){const t=e.querySelector(".tab-badge");if(t)return t;const n=document.createElement("span");return n.className="tab-badge",n.hidden=!0,e.append(n),n}unansweredQuestions=new Set;markUnansweredQuestions(e=this.unansweredQuestions){this.unansweredQuestions=e;const t=new Set;for(const s of e){const a=Tt.QUESTION_FIELDS[s];if(a&&!a.fields.some(o=>this.shadow.getElementById(o)?.classList.contains("missing-required")))for(const o of a.fields){const l=this.shadow.getElementById(o);l&&!l.hidden&&l.value===""&&t.add(o)}}for(const[s,a]of Object.entries(Tt.QUESTION_FIELDS))for(const o of Tt.QUESTION_FIELDS[s].fields){const l=this.shadow.getElementById(o);if(!l)continue;const c=t.has(o)&&!l.classList.contains("missing-required");l.classList.toggle("wanted",c),(c||l.title===this.messages.questionUnanswered)&&(l.title=c?this.messages.questionUnanswered:"")}const n=new Map;let i;for(const[s,a]of Object.entries(Tt.QUESTION_FIELDS))for(const o of a.fields){const l=this.shadow.getElementById(o);if(!l)continue;const c=l.classList.contains("missing-required");!c&&!l.classList.contains("wanted")||(c&&(i=a.panel),n.set(a.panel,(n.get(a.panel)??0)+1))}for(const[s,a]of this.groupTabs.entries()){const o=Tt.PANEL_ORDER[s],l=n.get(o)??0,c=o===i,h=Tt.badgeOn(a);h.hidden=l===0,h.textContent=String(l),h.classList.toggle("optional",!c),a.title=l===0?"":c?this.messages.durationRequired:this.messages.questionsUnanswered.replace("{count}",String(l))}}paramChip(e){const t=document.createElement("button");t.type="button",t.className=e.fromSource?"param-chip from-source":"param-chip",t.dataset.panel=String(e.panel),t.dataset.field=e.field;const n=document.createElement("span");if(n.className="param-chip-label",n.textContent=`${e.label} `,t.append(n),e.color!==void 0){const s=document.createElement("span");s.className="param-chip-swatch",s.style.background=e.color,t.append(s)}const i=document.createElement("span");return i.className="param-chip-value",i.textContent=e.unit===""?e.value:`${e.value} ${e.unit}`,t.append(i),t}onParamSummaryClick(e){const t=e.target.closest(".param-chip");if(t==null)return;const n=Number(t.dataset.panel);if(n<0)return;const i=this.groupPanels[n];this.toggleGroup(this.groupTabs[n],!0);const s=t.dataset.field;if(s.startsWith("decor:")){this.currentDecorId=s.slice(6),this.refreshDecorList(),this.decorSelect.focus();return}const a=this.shadow.getElementById(s);a===null||!i.contains(a)||(this.revealSubgroupOf(a),a.focus(),a instanceof HTMLInputElement&&a.type!=="checkbox"&&a.type!=="color"&&a.type!=="range"&&a.select(),a.scrollIntoView?.({block:"center"}))}onSelectionOrTimeChanged(){this.syncAppearanceFromTimeline(),this.syncObserverFromTimeline(),this.syncWeatherFromTimeline(),this.syncWeatherSourceState(),this.syncSoundFromTimeline(),this.syncDecorLitFromTimeline(),this.syncDecorPlacementFromTimeline(),this.syncIndoorLookReset(),this.updateAppearanceFieldsDisabledState(),this.updateShapeTitleValidity(),this.refreshRealSize(),this.refreshBlurDistanceBound(),this.refreshSkyCandidates(),this.refreshInstrumentOptions(),this.syncOpticsFromInstrument(),this.ufoElement.selectedSourceIds=this.selectedSourceIds;const e=this.ufoElement.sighting.timeline.sourceIds,t=e.filter(n=>this.selectedSourceIds.has(n)).length;this.deleteShapeButton.disabled=this.isRecording||this.ufoElement.playbackState==="playing"||t===0||e.length-t<1,this.refreshParamSummary()}updateAppearanceFieldsDisabledState(){const e=this.selectedSourceIds.size>1,t=e?this.messages.multipleShapesSelected:"";for(const n of[this.shapeTitleInput,this.colorInput,this.transparencyInput,this.haloScaleInput,this.blurInput,this.brightnessInput,this.apparentWidthInput,this.realWidthInput,this.objectDistanceInput,this.sizeLockSelect,this.clearDistanceHypothesisButton,this.sourceSelect,...Object.values(this.presetButtons)])n.disabled=e,n.title=t}syncAppearanceFromTimeline(){if(this.ufoElement.playbackState==="playing"||this.selectedSourceIds.size>1)return;const e=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId);e&&(this.currentAppearance={presetId:GA(e),color:e.color,transparency:e.transparency,haloScale:e.haloScale,blur:e.blur??0,brightness:e.brightness??0},this.updatePresetButtons(),this.colorInput.value=this.currentAppearance.color,this.transparencyInput.value=String(this.currentAppearance.transparency),this.haloScaleInput.value=String(this.currentAppearance.haloScale),this.blurInput.value=String(this.currentAppearance.blur),this.brightnessInput.value=String(this.currentAppearance.brightness),this.shadow.activeElement!==this.shapeTitleInput&&(this.shapeTitleInput.value=this.said.read(e.title)??""),this.refreshApparentSize())}updateShapeTitle(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime,n=e.getInterpolatedShapeAt(t,this.currentSourceId);n&&(this.commitShapes(t,[{sourceId:this.currentSourceId,shape:{...n,title:this.said.write(n.title,this.shapeTitleInput.value,this.writingLanguage)}}]),this.ufoElement.refresh(),this.refreshSourceList(),this.updateShapeTitleValidity())}sizeLock="none";onApparentWidthInput(){const e=this.numberOrUndefined(this.apparentWidthInput.value);if(!(e===void 0||e<=0||this.selectedSourceIds.size!==1)){if(this.sizeLock==="real"){const t=this.numberOrUndefined(this.realWidthInput.value);t!==void 0&&t>0&&this.sceneElement.setDistanceHypothesis(this.currentSourceId,et.distanceMAt(t,e))}this.applyApparentWidth(e)}}onRealWidthInput(){const e=this.numberOrUndefined(this.realWidthInput.value);if(e===void 0||e<=0||this.selectedSourceIds.size!==1)return;if(this.sizeLock==="apparent"){const n=this.currentApparentWidthDeg();n!==void 0&&n>0&&(this.sceneElement.setDistanceHypothesis(this.currentSourceId,et.distanceMAt(e,n)),this.refreshDepth());return}const t=this.currentDistanceM();t!==void 0&&t>0&&this.applyApparentWidth(et.angularWidthDeg({sizeM:e,distanceM:t}))}onDistanceInput(){const e=this.numberOrUndefined(this.objectDistanceInput.value);e===void 0||e<=0||this.applyDistance(e)}applyDistance(e){if(this.selectedSourceIds.size===1){if(this.sizeLock!=="apparent"){const t=this.numberOrUndefined(this.realWidthInput.value);t!==void 0&&t>0&&this.applyApparentWidth(et.angularWidthDeg({sizeM:t,distanceM:e}))}this.sceneElement.setDistanceHypothesis(this.currentSourceId,e),this.refreshDepth()}}applySizeLock(){this.sizeLock=this.sizeLockSelect.value,this.apparentWidthInput.readOnly=this.sizeLock==="apparent",this.realWidthInput.readOnly=this.sizeLock==="real",this.objectDistanceInput.readOnly=this.sizeLock==="distance"}currentApparentWidthDeg(){const e=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId);if(e)return e.angular?.widthDeg??this.currentProjection().pxToDeg(e.bounds.width)}currentDistanceM(){return this.sceneElement.depthOf(this.currentSourceId)?.distanceM}applyApparentWidth(e){const t=this.ufoElement.sighting.timeline,n=this.ufoElement.currentTime,i=t.getInterpolatedShapeAt(n,this.currentSourceId);if(!i)return;const s=this.currentProjection(),a=s.degToPx(e),o=i.bounds.height*(i.bounds.width===0?1:a/i.bounds.width),l={x:i.bounds.x+(i.bounds.width-a)/2,y:i.bounds.y+(i.bounds.height-o)/2,width:a,height:o},c=s.ofBounds(l),h=i.kind==="oval"?{...i,bounds:l,angular:c}:{...i,bounds:l,angular:c,points:this.scalePoints(i,l)};this.commitShapes(n,[{sourceId:this.currentSourceId,shape:h}]),this.ufoElement.refresh(),this.refreshApparentSize()}scalePoints(e,t){const n=e.bounds.width===0?1:t.width/e.bounds.width,i=e.bounds.height===0?1:t.height/e.bounds.height;return e.points.map(s=>({x:s.x*n,y:s.y*i}))}refreshInstrumentOptions(){const e=this.ufoElement.sighting,t=e.event.time?.year,n=rt.availableAt(t),i=e.instrument,s=n.includes(i)?n:[...n,i],a=this.instrumentSelect.value||i.id;this.instrumentSelect.replaceChildren();for(const o of s){const l=document.createElement("option");l.value=o.id;const c=o.name[this.showerLanguage()];l.textContent=n.includes(o)?c:this.messages.instrumentOutOfPeriod.replace("{name}",c),this.instrumentSelect.appendChild(l)}this.instrumentSelect.value=s.some(o=>o.id===a)?a:i.id}static exposureText(e){return e>=1?String(Math.round(e*100)/100):`1/${Math.round(1/e)}`}statedExposureSeconds(e){const t=Tt.exposureSeconds(this.exposureInput.value),n=e.exposureRangeSeconds;if(!n)return e.exposureSeconds??t;if(t!==void 0)return Math.min(n.max,Math.max(n.min,t))}static exposureSeconds(e){const t=e.trim();if(!t)return;const n=/^(\d*\.?\d+)\s*\/\s*(\d*\.?\d+)$/.exec(t);if(n){const s=Number(n[1]),a=Number(n[2]);return a>0?s/a:void 0}const i=Number(t);return Number.isFinite(i)&&i>0?i:void 0}syncOpticsFromInstrument(){const e=this.ufoElement.sighting,t=e.instrument,n=tt(e,this.ufoElement.currentTime),i=t.frame,s=n?.fovDeg??rt.fieldOfViewDeg(t),a=i?rt.focalLengthMmFor(t,s):s;this.focalLengthInput!==this.shadow.activeElement&&(this.focalLengthInput.value=a===void 0?"":String(Math.round(a*10)/10)),this.unitFocalLength.textContent=i?this.messages.unitMillimetres:this.messages.unitDegrees,this.labelFocalLength.textContent=i?this.messages.focalLength:this.messages.fieldOfView,this.focalLengthInput.disabled=i!==void 0&&i.focalRangeMm===void 0,this.focalLengthInput.min=String(i?.focalRangeMm?.minMm??1),this.focalLengthInput.max=String(i?.focalRangeMm?.maxMm??2e3);const o=n?.fNumber??t.fNumber;this.fNumberInput!==this.shadow.activeElement&&(this.fNumberInput.value=o===void 0?"":String(o)),this.setRowVisible(this.fNumberInput,t.fNumber!==void 0),this.fNumberInput.disabled=t.fNumberRange===void 0,this.fNumberInput.min=String(t.fNumberRange?.min??.7),this.fNumberInput.max=String(t.fNumberRange?.max??64);const l=e.exposure;this.exposureInput!==this.shadow.activeElement&&(this.exposureInput.value=l===void 0?"":Tt.exposureText(l)),this.setRowVisible(this.exposureInput,t.exposureSeconds!==void 0),this.exposureInput.disabled=t.exposureRangeSeconds===void 0,this.focusDistanceInput!==this.shadow.activeElement&&(this.focusDistanceInput.value=n?.focusDistanceM===void 0?"":String(n.focusDistanceM)),this.setRowVisible(this.focusDistanceInput,i!==void 0&&t.fNumber!==void 0)}retuneFieldOfView(e){const t=this.ufoElement.sighting,n=rt.fieldOfViewDeg(e),i=rt.fieldOfViewDeg(t.instrument);for(const s of[...t.witnessTrack.allKeyframes])Math.abs(s.pose.fovDeg-n)>UA||t.witnessTrack.addKeyframe(s.t,{...s.pose,fovDeg:i})}retuneExposure(e){const t=this.ufoElement.sighting,n=t.exposureSeconds,i=t.instrument.exposureRangeSeconds;if(n===void 0||n===e.exposureSeconds||!i){t.exposureSeconds=void 0;return}t.exposureSeconds=Math.min(i.max,Math.max(i.min,n))}currentFovDeg(){const e=this.ufoElement.sighting;return tt(e,this.ufoElement.currentTime)?.fovDeg??rt.fieldOfViewDeg(e.instrument)}currentProjection(){return oi.of(this.ufoElement.sighting.instrument,this.ufoElement.canvasElement.height,this.currentFovDeg())}refreshApparentSize(){const e=this.selectedSourceIds.size===1?this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId):void 0;if(!e){this.apparentSizeOutput.textContent="",this.hasFocus(this.apparentWidthInput)||(this.apparentWidthInput.value=""),this.refreshRealSize();return}const t=e.angular?.widthDeg??this.currentProjection().pxToDeg(e.bounds.width),n=et.inMoons(t);this.hasFocus(this.apparentWidthInput)||(this.apparentWidthInput.value=this.plain(t,t<1?2:1)),this.apparentSizeOutput.textContent=this.messages.apparentSize.replace("{moons}",n.toLocaleString(void 0,{maximumFractionDigits:n<10?1:0})),this.refreshRealSize()}hasFocus(e){return this.typingIn===e}typingIn;typing(e,t){this.typingIn=e;try{t()}finally{this.typingIn=void 0}}plain(e,t){return String(Number(e.toFixed(t)))}refreshBlurDistanceBound(){const e=this.currentAppearance.blur;if(e<=0||this.selectedSourceIds.size!==1){this.blurBoundOutput.textContent="";return}const t=this.ufoElement.sighting.instrument,n=t.frame;if(!n){this.blurBoundOutput.textContent=this.messages.blurBoundNoInstrument;return}const i=tt(this.ufoElement.sighting,this.ufoElement.currentTime),s=i?.focusDistanceM;if(s!==void 0){this.blurBoundOutput.textContent=this.messages.blurBoundNotAtInfinity.replace("{focus}",this.meters(s));return}const a=(i?rt.focalLengthMmFor(t,i.fovDeg):void 0)??n.focalLengthMm,o=i?.fNumber??t.fNumber;if(o===void 0||a<=0){this.blurBoundOutput.textContent="";return}const l=this.ufoElement.canvasElement.height;if(l<=0)return;const c=2*td*e/l*n.heightMm,h=a*a/(o*c)/1e3;this.blurBoundOutput.textContent=this.messages.blurBound.replace("{max}",this.meters(h))}refreshRealSize(){if(this.refreshDepth(),this.selectedSourceIds.size!==1){this.realSizeOutput.textContent="";return}const e=this.currentSourceId;if(this.sceneElement.sizeContradictory(e)){this.realSizeOutput.textContent=this.messages.realSizeContradiction;return}const{minM:t,maxM:n}=this.sceneElement.sizeRangeOf(e);if(t===void 0&&n===void 0){this.realSizeOutput.textContent=this.messages.realSizeUnknown;return}const i=this.numberOrUndefined(this.realWidthInput.value),s=i!==void 0&&(t!==void 0&&i<t||n!==void 0&&i>n)?this.messages.realSizeOutside:"";if(t!==void 0&&n!==void 0){const a=this.sceneElement.distanceRangeAt(e,this.ufoElement.currentTime),o=a.minM===void 0||a.maxM===void 0?"":this.messages.realDistanceHere.replace("{min}",this.meters(a.minM)).replace("{max}",this.meters(a.maxM));this.realSizeOutput.textContent=this.messages.realSizeBetween.replace("{min}",this.meters(t)).replace("{max}",this.meters(n))+o+s;return}this.realSizeOutput.textContent=(t!==void 0?this.messages.realSizeAtLeast.replace("{min}",this.meters(t)):this.messages.realSizeAtMost.replace("{max}",this.meters(n)))+s}decimal(e,t){return e.toLocaleString(void 0,{minimumFractionDigits:t,maximumFractionDigits:t})}clearDistanceHypothesis(){this.selectedSourceIds.size===1&&(this.sceneElement.setDistanceHypothesis(this.currentSourceId,void 0),this.refreshDepth())}refreshDepth(){const e=this.selectedSourceIds.size===1?this.sceneElement.depthOf(this.currentSourceId):void 0;if(!e){this.depthBasisOutput.textContent="",this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=""),this.hasFocus(this.realWidthInput)||(this.realWidthInput.value="");return}const t=this.meters(e.distanceM);this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=this.plain(e.distanceM,e.distanceM<10?1:0));const n=this.currentApparentWidthDeg();if(!this.hasFocus(this.realWidthInput)){const s=n===void 0||n<=0?void 0:et.sizeMAt(e.distanceM,n);this.realWidthInput.value=s===void 0?"":this.plain(s,s<1?2:s<10?1:0)}this.clearDistanceHypothesisButton.hidden=e.basis!=="hypothesis";const i={stated:this.messages.depthStated,hypothesis:this.messages.depthHypothesis,derived:this.messages.depthDerived,bounded:this.messages.depthBounded,conventional:this.messages.depthConventional}[e.basis];this.depthBasisOutput.textContent=i.replace("{m}",t)}commitShapes(e,t){const n=this.ufoElement.sighting,i=oi.of(n.instrument,et.CANVAS_HEIGHT_PX,ln.fovOf(n,e));n.timeline.addKeyframe(e,t.map(s=>{const a=ln.aimOf(n,e,s.shape.bounds),o=i.ofBounds(s.shape.bounds);return{...s,shape:a?{...s.shape,aim:a,angular:o}:{...s.shape,angular:o}}}))}meters(e){const t=e<1?2:e<10?1:0;return e.toLocaleString(void 0,{maximumFractionDigits:t})}updateShapeTitleValidity(){const e=this.selectedSourceIds.size===1&&this.shapeTitleInput.value==="";this.shapeTitleInput.classList.toggle("invalid",e),this.shapeTitleInput.setAttribute("aria-invalid",String(e))}shapeLabel(e){const t=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,e),n=this.said.read(t?.title);if(n)return n;const i=/^ufo-(\d+)$/.exec(e);return i?`${this.messages.shape} ${i[1]}`:e}addShape(){if(this.isRecording)return;const e=this.ufoElement.sighting.timeline,t=new Set([...e.sourceIds,this.currentSourceId]);let n=t.size+1;for(;t.has(`ufo-${n}`);)n++;this.currentSourceId=`ufo-${n}`,this.selectedSourceIds=new Set([this.currentSourceId]),this.applyAppearanceAtPlayhead(this.offsetDefaultBounds(e.sourceIds.length)),this.shapeTitleInput.value=this.shapeLabel(this.currentSourceId),this.updateShapeTitle()}deleteShape(){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const e=this.ufoElement.sighting.timeline,t=e.sourceIds.filter(i=>this.selectedSourceIds.has(i));if(t.length===0||e.sourceIds.length-t.length<1)return;const n=t.length===1?this.messages.confirmDeleteShape.replace("{name}",this.shapeLabel(t[0])):this.messages.confirmDeleteShapes.replace("{count}",String(t.length));this.askConfirm(n,()=>this.removeShapes(t))}removeShapes(e){const t=this.ufoElement.sighting.timeline;for(const n of e)t.removeSource(n);this.currentSourceId=t.sourceIds[0],this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.ufoElement.refresh()}askConfirm(e,t){this.answerConfirm(!1),this.confirmMessage.textContent=e,this.confirmOverlay.hidden=!1,this.confirmAcceptButton.focus(),this.confirmAnswer=t}answerConfirm(e){const t=this.confirmAnswer;this.confirmAnswer=void 0,this.confirmOverlay.hidden=!0,e&&t?.()}offsetDefaultBounds(e){const t=this.defaultBounds(),n=24;return{...t,x:t.x+e*n,y:t.y+e*n}}refreshSourceList(){const e=this.ufoElement.sighting.timeline,t=[...new Set([...e.sourceIds,this.currentSourceId])];this.sourceSelect.innerHTML="";for(const n of t){const i=document.createElement("option");i.value=n,i.textContent=this.shapeLabel(n),this.sourceSelect.appendChild(i)}this.sourceSelect.value=this.currentSourceId}decorLabel(e){const t=this.said.read(e.title);if(t)return t;const i=this.ufoElement.sighting.decor.filter(a=>a.kind===e.kind).indexOf(e)+1;return`${this.decorKindSelect.querySelector(`option[value="${e.kind}"]`)?.textContent??e.kind} ${i}`}addDecor(e=this.decorKindSelect.value){const t=this.ufoElement.sighting,i={id:`decor-${t.decor.length+1}`,kind:e,title:this.nextDecorLabel(e),eastM:8*t.decor.length,northM:15,headingDeg:0,lit:!1,...e==="aircraft"?this.defaultAircraft():{},...e==="building"?{floors:ta}:{},windows:jm(e)};t.decor=[...t.decor,i],this.currentDecorId=i.id,this.refreshDecorList(),this.ufoElement.refresh()}defaultAircraft(){const e=2*Jh,t=Math.round(e/zA*1e3);return{lights:Nc.byId("airliner")?.create(),track:[{t:0,eastM:-Jh,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:Jh,northM:1e3,altitudeM:1500,headingDeg:90}]}}nextDecorLabel(e){const t=this.ufoElement.sighting.decor.filter(i=>i.kind===e).length;return`${this.decorKindSelect.querySelector(`option[value="${e}"]`)?.textContent??e} ${t+1}`}deleteDecor(){if(this.currentDecorId===void 0)return;const e=this.ufoElement.sighting;e.decor=e.decor.filter(t=>t.id!==this.currentDecorId),this.currentDecorId=e.decor[0]?.id,this.refreshDecorList(),this.ufoElement.refresh()}selectDecor(e){this.currentDecorId=e,this.decorSelect.value=e,this.syncDecorFields()}updateDecor(){if(this.currentDecorId===void 0)return;const e=this.ufoElement.sighting,t=this.wrapDegrees(Number(this.decorHeadingInput.value),this.decorHeadingInput)??0,n=this.decorWitnessSideSelect.value;e.decor=e.decor.map(i=>{if(i.id!==this.currentDecorId)return i;const s=Kr(i.kind)&&n!==""?n:void 0,a=Number(this.decorEastInput.value),o=Number(this.decorNorthInput.value),l=Number(this.decorAltitudeInput.value),c=i.track??(l!==0?[]:void 0);if(c){const h=this.ufoElement.currentTime,d={t:h,eastM:a,northM:o,altitudeM:l,headingDeg:t},u=c.filter(f=>f.t!==h);return{...i,title:this.said.write(i.title,this.decorTitleInput.value,this.writingLanguage),color:this.statedDecorColor(i),track:[...u,d].sort((f,p)=>f.t-p.t),sightingUrl:this.stringOrUndefined(this.decorSightingUrlInput.value),witnessSide:s,sizeM:this.statedDecorSize(),model:this.statedDecorModel(),floors:i.kind==="building"?Number(this.decorFloorsInput.value):void 0,occupiedFloor:i.kind==="building"?Number(this.decorOccupiedFloorInput.value):void 0}}return{...i,title:this.said.write(void 0,this.decorTitleInput.value,this.writingLanguage),color:this.statedDecorColor(i),eastM:a,northM:o,headingDeg:t,sightingUrl:this.stringOrUndefined(this.decorSightingUrlInput.value),witnessSide:s,sizeM:this.statedDecorSize(),model:this.statedDecorModel(),floors:i.kind==="building"?Number(this.decorFloorsInput.value):void 0,occupiedFloor:i.kind==="building"?Number(this.decorOccupiedFloorInput.value):void 0}}),this.decorSelect.options[this.decorSelect.selectedIndex].textContent=this.decorLabel(e.decor.find(i=>i.id===this.currentDecorId)),this.syncDecorVisibility(),this.updateDecorTitleValidity(),this.ufoElement.refresh()}syncDecorSizeFields(e){const t=e?nn.naturalSize(e.kind,e.floors):void 0,n=[[this.decorWidthInput,e?.sizeM?.widthM,t?.widthM],[this.decorLengthInput,e?.sizeM?.lengthM,t?.lengthM],[this.decorHeightInput,e?.sizeM?.heightM,t?.heightM]];for(const[i,s,a]of n)i.value=s===void 0?"":String(this.roundedMeters(s)),i.placeholder=a===void 0?"":String(this.roundedMeters(a))}syncDecorModelFields(e){this.refreshDecorModelOptions(e),this.decorModelSelect.value=e?.model?.id??"",this.decorModelUrlInput.value=e?.model?.url??"",this.decorModelTitleInput.value=e?.model?.credit?.title??"",this.decorModelAuthorInput.value=e?.model?.credit?.author??"",this.decorModelLicenseInput.value=e?.model?.credit?.license??"",this.decorModelSourceInput.value=e?.model?.credit?.sourceUrl??"",this.decorModelAdvanced.open=e?.model?.url!==void 0}async refreshDecorModelOptions(e){const t=e??this.ufoElement.sighting.decor.find(a=>a.id===this.currentDecorId),n=t?await this.decorModelProvider.entries(t.kind).catch(()=>[]):[],i=t?.model?.id??"",s=document.createElement("option");s.value="",s.textContent=this.messages.decorModelNone,this.decorModelSelect.replaceChildren(s,...n.map(a=>{const o=document.createElement("option");return o.value=a.id,o.textContent=a.name,o.title=`${a.credit.title}${a.credit.author?` — ${a.credit.author}`:""} (${a.credit.license})`,o})),this.decorModelSelect.value=i}updateDecorModelChoice(){const e=this.decorModelSelect.value;(async()=>{const t=e?await this.decorModelProvider.entry(e).catch(()=>{}):void 0,n=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId);if(t?.sizeM&&n&&!n.sizeM){const i=[[this.decorWidthInput,t.sizeM.widthM],[this.decorLengthInput,t.sizeM.lengthM],[this.decorHeightInput,t.sizeM.heightM]];for(const[s,a]of i)a!==void 0&&(s.value=String(this.roundedMeters(a)))}this.updateDecor()})()}roundedMeters(e){return Math.round(e*100)/100}positiveMeters(e){const t=Number(e);return e.trim()===""||!Number.isFinite(t)||t<=0?void 0:t}statedDecorColor(e){const t=this.decorColorInput.value;return t==="#808080"&&e.color===void 0?void 0:t}statedDecorSize(){const e=this.positiveMeters(this.decorWidthInput.value),t=this.positiveMeters(this.decorLengthInput.value),n=this.positiveMeters(this.decorHeightInput.value);return e===void 0&&t===void 0&&n===void 0?void 0:{widthM:e,lengthM:t,heightM:n}}statedDecorModel(){const e=this.stringOrUndefined(this.decorModelUrlInput.value);if(e){const n=this.stringOrUndefined(this.decorModelTitleInput.value),i=this.stringOrUndefined(this.decorModelLicenseInput.value);return{url:e,credit:n!==void 0&&i!==void 0?{title:n,license:i,author:this.stringOrUndefined(this.decorModelAuthorInput.value),sourceUrl:this.stringOrUndefined(this.decorModelSourceInput.value)}:void 0}}const t=this.stringOrUndefined(this.decorModelSelect.value);return t===void 0?void 0:{id:t}}addMilestone(){const e=Math.round(this.ufoElement.currentTime),t=this.ufoElement.sighting;t.milestones.find(i=>i.t===e)||(t.milestones=pa([...t.milestones,{t:e,label:this.nextMilestoneLabel()}])),this.currentMilestoneT=e,this.refreshMilestoneList(),this.ufoElement.refresh()}nextMilestoneLabel(){const e=new Set(this.ufoElement.sighting.milestones.map(t=>t.label));for(let t=0;t<26;t++){const n=String.fromCharCode(65+t);if(!e.has(n))return n}return String(this.ufoElement.sighting.milestones.length+1)}deleteMilestone(){const e=this.currentMilestoneT;if(e===void 0)return;const t=this.ufoElement.sighting,n=t.milestones.find(i=>i.t===e);n&&this.askConfirm(this.messages.confirmDeleteMilestone.replace("{name}",this.said.read(n.label)??""),()=>{t.milestones=t.milestones.filter(i=>i.t!==e),this.currentMilestoneT=t.milestones[0]?.t,this.refreshMilestoneList(),this.ufoElement.refresh()})}selectMilestone(e){this.currentMilestoneT=e,this.syncMilestoneFields(),this.ufoElement.currentTime=e}updateMilestone(){const e=this.currentMilestoneT;if(e===void 0)return;const t=this.ufoElement.sighting;t.milestones=t.milestones.map(n=>n.t===e?{...n,label:this.said.write(n.label,this.milestoneLabelInput.value,this.writingLanguage)??"",note:this.said.write(n.note,this.milestoneNoteInput.value,this.writingLanguage)}:n),this.refreshMilestoneList(),this.ufoElement.refresh()}refreshMilestoneList(){const e=pa(this.ufoElement.sighting.milestones);e.some(t=>t.t===this.currentMilestoneT)||(this.currentMilestoneT=e[0]?.t),this.milestoneSelect.replaceChildren(...e.map(t=>{const n=document.createElement("option");return n.value=String(t.t),n.textContent=`${this.said.read(t.label)??""} — ${this.formatSeconds(t.t)}`,n.title=this.said.read(t.note)??"",n})),this.currentMilestoneT!==void 0&&(this.milestoneSelect.value=String(this.currentMilestoneT)),this.syncMilestoneFields()}formatSeconds(e){return`${(e/1e3).toFixed(1)} s`}syncMilestoneFields(){const e=this.ufoElement.sighting.milestones.find(n=>n.t===this.currentMilestoneT),t=e!==void 0;for(const n of[this.milestoneSelect,this.milestoneLabelInput,this.milestoneNoteInput,this.deleteMilestoneButton])n.disabled=!t,this.setRowVisible(n,t);this.milestoneLabelInput.value=this.said.read(e?.label)??"",this.milestoneNoteInput.value=this.said.read(e?.note)??""}updateDecorTitleValidity(){const e=this.currentDecorId!==void 0&&this.decorTitleInput.value==="";this.decorTitleInput.classList.toggle("invalid",e),this.decorTitleInput.setAttribute("aria-invalid",String(e))}updateDecorWindows(){if(this.currentDecorId===void 0)return;const e=this.ufoElement.sighting;e.decor=e.decor.map(t=>{if(t.id!==this.currentDecorId)return t;const n={};for(const i of gr){const s=this.decorWindowInputs[i];if(s.value==="")continue;const a=id(t.kind,i)?0:nd,o=Math.max(a,Math.min(100,Number(s.value)));n[i]=o,String(o)!==s.value&&(s.value=String(o))}return{...t,windows:n}}),this.ufoElement.refresh()}updateDecorLit(){if(this.currentDecorId===void 0||this.ufoElement.playbackState==="playing")return;const e=this.ufoElement.sighting,t=this.ufoElement.currentTime,n=this.decorLitInput.checked;e.decor=e.decor.map(i=>{if(i.id!==this.currentDecorId)return i;const s=[...(i.litKeyframes??[]).filter(a=>a.t!==t),{t,lit:n}].sort((a,o)=>a.t-o.t);return{...i,litKeyframes:s}}),this.ufoElement.refresh()}refreshDecorList(){const e=this.ufoElement.sighting.decor;this.decorSelect.innerHTML="";for(const t of e){const n=document.createElement("option");n.value=t.id,n.textContent=this.decorLabel(t),this.decorSelect.appendChild(n)}this.currentDecorId!==void 0&&(this.decorSelect.value=this.currentDecorId),this.syncDecorFields()}syncDecorFields(){const e=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId),t=e!==void 0;this.deleteDecorButton.disabled=!t;for(const n of[this.decorSelect,this.decorTitleInput,this.decorEastInput,this.decorNorthInput,this.decorHeadingInput,this.decorLitInput,this.decorSightingUrlInput,this.decorWidthInput,this.decorLengthInput,this.decorHeightInput,this.decorModelSelect,this.decorModelUrlInput,this.decorModelTitleInput,this.decorModelAuthorInput,this.decorModelLicenseInput,this.decorModelSourceInput,this.decorFloorsInput,this.decorOccupiedFloorInput,this.decorWitnessSideSelect,this.decorLightRigSelect,this.decorAltitudeInput,this.lookAtDecorButton])n.disabled=!t;this.decorTitleInput.value=this.said.read(e?.title)??"",this.decorColorInput.value=e?.color??"#808080",this.showDecorPlacement(e),this.decorLitInput.checked=e?jl(e,this.ufoElement.currentTime):!1,this.refreshDecorLightRigOptions(e),this.decorSightingUrlInput.value=e?.sightingUrl??"",this.syncDecorSizeFields(e),this.syncDecorModelFields(e),this.decorFloorsInput.value=String(e?.floors??ta),this.decorOccupiedFloorInput.value=String(e?.occupiedFloor??0),this.decorWitnessSideSelect.value=e?.witnessSide??"";for(const n of gr){const i=e?.windows?.[n];this.decorWindowInputs[n].value=i===void 0?"":String(i)}this.syncDecorVisibility(),this.updateDecorTitleValidity()}setRowVisible(e,t){const n=e.closest("label")??e;n.hidden=!t}syncDecorVisibility(){const e=this.ufoElement.sighting.decor.find(c=>c.id===this.currentDecorId),t=e!==void 0,n=e?.kind;this.setRowVisible(this.decorSelect,t),this.setRowVisible(this.deleteDecorButton,t),this.setRowVisible(this.decorTitleInput,t),this.setRowVisible(this.decorEastInput,t),this.setRowVisible(this.decorNorthInput,t),this.setRowVisible(this.decorAltitudeInput,t),this.setRowVisible(this.decorHeadingInput,t),this.setRowVisible(this.decorWidthInput,t),this.setRowVisible(this.decorLengthInput,t),this.setRowVisible(this.decorHeightInput,t),this.setRowVisible(this.decorModelSelect,t),this.decorModelAdvanced.hidden=!t,this.setRowVisible(this.decorLitInput,t&&e?.kind!=="aircraft");const i=t&&n!==void 0&&Nu(n);this.setRowVisible(this.labelDecorWindows,i);const s=n!==void 0?ku(n):[];for(const c of gr)this.decorWindowInputs[c].disabled=!t,this.decorWindowInputs[c].min=String(n!==void 0&&id(n,c)?0:nd),this.setRowVisible(this.decorWindowInputs[c],i&&s.includes(c));const a=t&&n!==void 0&&Kr(n);this.setRowVisible(this.decorWitnessSideSelect,a);const o=n!==void 0?T1(n):[];for(const c of gr)this.optionWitnessSide[c].hidden=!o.includes(c);const l=t&&n==="building";this.setRowVisible(this.decorFloorsInput,l),this.setRowVisible(this.decorOccupiedFloorInput,l),this.decorOccupiedFloorInput.max=String(e?.floors??ta)}showDecorPlacement(e){const t=e?fa(e,this.ufoElement.currentTime):void 0,n=[[this.decorEastInput,t?.eastM??0],[this.decorNorthInput,t?.northM??0],[this.decorAltitudeInput,t?.altitudeM??0],[this.decorHeadingInput,t?.headingDeg??0]];for(const[i,s]of n)this.shadow.activeElement!==i&&(i.value=String(this.rounded(s)))}syncDecorPlacementFromTimeline(){this.ufoElement.playbackState!=="playing"&&this.showDecorPlacement(this.ufoElement.sighting.decor.find(e=>e.id===this.currentDecorId))}showNextMeteor(){const e=this.sceneElement.meteorByRank(this.meteorRank++);e&&(this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=e.t,this.headingInput.value=String(Math.round(e.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(e.altitudeDeg*10)/10),this.updateObserver())}resetMeteorRankIfSkyChanged(){const e=this.sceneElement.meteorByRank(0),t=e?`${e.t}`:"";t!==this.meteorRankFor&&(this.meteorRankFor=t,this.meteorRank=0)}meteorRankFor;skyCandidatesKey;meteorRank=0;showerLanguage(){return na(Ts.preferencesFor(this),["en","fr"])}get said(){return this.saidTexts??=new Zi(Ts.preferencesFor(this))}saidTexts;tagNames=new rd({});get writingLanguage(){return this.showerLanguage()}refreshSkyCandidates(){this.resetMeteorRankIfSkyChanged();const e=this.ufoElement.sighting,t=e.event.place?.[0],n=e.event.time,i=t&&t.lat!==void 0&&t.lng!==void 0&&n?.year!==void 0?Ds(n,t.lng,e.event.utcOffsetHours):void 0,s=JSON.stringify([i?.getTime(),t?.lat,t?.lng,this.groundElevationM,e.instrumentId,e.exposureSeconds,Ut(e,0),this.messages.skyLine,this.meteorRankFor,this.sceneElement.satelliteState.status,this.satelliteSpanMs()]);if(s===this.skyCandidatesKey)return;if(this.skyCandidatesKey=s,!i||!t||t.lat===void 0||t.lng===void 0){this.showMeteorButton.hidden=!0,this.showCometButton.hidden=!0,this.showSatelliteButton.hidden=!0,this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",this.messages.skyUnknown);return}const a={lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0},o=[this.starsClause(i,a),this.showerClause(i,a),this.cometClause(i,a),this.satelliteClause(i,a),this.opticsClause(i,a),this.rainbowClause(i,a),this.glowClause(i,a)].filter(l=>l!==void 0);this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",o.join(" · "))}instrumentGain(){const e=this.ufoElement.sighting;return mn.gainFor(e.instrument,{fNumber:tt(e,0)?.fNumber,fieldOfViewDeg:ln.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const n=Cn("Sun",e,t).altitudeDeg,i=this.instrumentGain(),s=nr(n,i),a=c=>c.toLocaleString(void 0,{maximumFractionDigits:1});if(s<OA)return this.messages.skyStarsNone;const o=this.ufoElement.sighting.instrument,l=Math.abs(i)<.1?this.messages.skyStarsEye.replace("{limit}",a(s)):(i>0?this.messages.skyStarsDeeper:this.messages.skyStarsShallower).replace("{limit}",a(s)).replace("{device}",o.name[this.showerLanguage()]).replace("{gain}",a(Math.abs(i))).replace("{eye}",a(nr(n)));return s<=ao?l:l+this.messages.skyStarsCatalogue.replace("{catalogue}",a(ao))}showerClause(e,t){const n=Dt.observedRatePerHour(Dt.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),i=da.activeAt(e);if(i.length===0)return this.showMeteorButton.hidden=!this.sceneElement.meteorByRank(0),this.messages.skyNothingActive.replace("{sporadic}",n);const s=i.map(a=>{const o=da.radiantPosition(a.shower,e,t);return{entry:a,position:o,rate:da.observedRatePerHour(a.zhr,o.altitudeDeg,a.shower.populationIndex)}}).sort((a,o)=>o.rate-a.rate)[0];return s.rate<=0?(this.showMeteorButton.hidden=!this.sceneElement.meteorByRank(0),this.messages.skyShowerBelowHorizon.replace("{name}",s.entry.shower.name[this.showerLanguage()])):(this.showMeteorButton.hidden=!this.sceneElement.meteorByRank(0),this.messages.skyShowerActive.replace("{name}",s.entry.shower.name[this.showerLanguage()]).replace("{altitude}",String(Math.round(s.position.altitudeDeg))).replace("{bearing}",_s.towards(s.position.azimuthDeg,this.showerLanguage())).replace("{rate}",s.rate.toLocaleString(void 0,{maximumFractionDigits:s.rate<10?1:0})).replace("{sporadic}",n))}cometClause(e,t){const n=ql.brightestAt(e,t);if(!n||n.magnitude>xo){this.showCometButton.hidden=!0;return}return this.showCometButton.hidden=n.position.altitudeDeg<=0,this.cometText(n)}satelliteClause(e,t){const n=Mi.visibilityAt(e,t),i=this.realSatelliteClause(n.lowOrbitLit||n.sunAltitudeDeg>=0);if(i!==void 0)return i;if(this.showSatelliteButton.hidden=!0,!n.anythingInOrbit)return n.sunAltitudeDeg<0?this.messages.skySatellitesNotYet:void 0;const s=nr(n.sunAltitudeDeg,this.instrumentGain()),a=n.classes.filter(d=>d.peakMagnitude<=s),o=this.listed(a.map(d=>d.name[this.showerLanguage()]));if(n.sunAltitudeDeg>=0)return a.length===0?void 0:(a.length===1?this.messages.skySatellitesDaylightOne:this.messages.skySatellitesDaylight).replace("{eras}",o);const l=Math.round(n.shadowHeightKm).toLocaleString(),c=(n.trackedObjects??0).toLocaleString(),h=d=>d.replace("{height}",l).replace("{count}",c);return n.lowOrbitLit?a.length===0?h(this.messages.skySatellitesLit):h(this.messages.skySatellitesLitWith).replace("{eras}",o):h(this.messages.skySatellitesShadowed)}realSatelliteClause(e){const t=this.sceneElement.satelliteState;if(t.status!=="ready")return;if(t.coverage?.every(h=>h.status!=="covered"))return this.showSatelliteButton.hidden=!0,t.coverage.some(h=>h.status==="gap")?this.messages.skySatelliteElementsGap:void 0;const n=this.visibleSatellitePasses(),i=n.filter(h=>this.passTimelineMs(h)<=this.ufoElement.seekableDuration);if(this.showSatelliteButton.hidden=i.length===0,n.length===0)return e?this.messages.skySatellitePassesNone:void 0;const a=n[0].peak,l=(n.length===1?this.messages.skySatellitePassesOne:this.messages.skySatellitePasses).replace("{count}",String(n.length)).replace("{name}",a.object.name).replace("{magnitude}",a.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(a.altitudeDeg))).replace("{bearing}",_s.towards(a.azimuthDeg,this.showerLanguage())).replace("{time}",this.witnessClock(a.date)),c=this.starlinkTrain(n);return c?`${l}, ${c}`:l}visibleSatellitePasses(){const e=this.instrumentGain(),t=this.observerAtStart();return this.sceneElement.satellitePassesDuring(this.satelliteSpanMs()).filter(n=>{const i=n.peak.magnitude;if(i===void 0)return!1;const s=Cn("Sun",n.peak.date,t);return i<=nr(s.altitudeDeg,e)}).sort((n,i)=>n.peak.magnitude-i.peak.magnitude)}starlinkTrain(e){const t=new Map;for(const a of e){const{kind:o,launch:l}=a.peak.object;o!=="starlink"||!l||(a.peak.date.getTime()-Date.parse(`${l}T00:00:00Z`))/864e5>60||t.set(l,(t.get(l)??0)+1)}const[n,i]=[...t.entries()].sort((a,o)=>o[1]-a[1])[0]??[];if(!n||!i||i<3)return;const s=new Date(`${n}T00:00:00Z`).toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skySatelliteTrain.replace("{count}",String(i)).replace("{date}",s)}satelliteSpanMs(){const e=(this.ufoElement.sighting.event.durationSeconds??0)*1e3;return Math.max(e,this.ufoElement.seekableDuration)}observerAtStart(){const e=this.ufoElement.sighting.event.place?.[0],t=tt(this.ufoElement.sighting,0);return{lat:t?.lat??e?.lat??0,lng:t?.lng??e?.lng??0,elevationM:this.groundElevationM??0}}passTimelineMs(e){const t=this.ufoElement.sighting,n=Ds(t.event.time??{},this.observerAtStart().lng,t.event.utcOffsetHours);return n?e.peak.date.getTime()-n.getTime():1/0}witnessClock(e){const n=this.ufoElement.sighting.event.utcOffsetHours??Math.round(this.observerAtStart().lng/15);return new Date(e.getTime()+n*36e5).toLocaleTimeString(this.showerLanguage(),{hour:"2-digit",minute:"2-digit",second:"2-digit",timeZone:"UTC"})}showNextSatellite(){const e=this.visibleSatellitePasses().filter(i=>this.passTimelineMs(i)<=this.ufoElement.seekableDuration);if(e.length===0)return;const t=e.map(i=>`${i.object.norad}@${i.peak.date.getTime()}`).join();t!==this.satelliteRankFor&&(this.satelliteRankFor=t,this.satelliteRank=0);const n=e[this.satelliteRank++%e.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.passTimelineMs(n),this.headingInput.value=String(Math.round(n.peak.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(n.peak.altitudeDeg*10)/10),this.updateObserver()}satelliteRankFor;satelliteRank=0;opticsClause(e,t){const n=Ut(this.ufoElement.sighting,0),i=Cn("Sun",e,t),s=Cn("Moon",e,t),a=Je.deckLitUntilDeg(Je.DECK_HEIGHT_M),o=i.altitudeDeg>-a,l=o?i:s;if(l.altitudeDeg<=-a)return;const c=n.highCloudCover;if(c===void 0||c<=0)return this.messages.skyOpticsNoIce;if(Je.strength(c,n.lowerCloudCover??n.cloudCover,l.altitudeDeg,a)<=0)return this.messages.skyOpticsHidden;const h=o?this.messages.skyOpticsSun:this.messages.skyOpticsMoon,d=this.listed(Je.formsAt(l.altitudeDeg,a).map(f=>this.opticsFormName(f))),u=n.iceCrystalAlignment??.65;return this.messages.skyOpticsPossible.replace("{forms}",d).replace("{source}",h)+this.messages.skyOpticsAlignment.replace("{alignment}",String(Math.round(u*100)))}rainbowClause(e,t){const n=Ut(this.ufoElement.sighting,0);if(n.precipitationType!=="rain"||n.precipitationIntensity<=0)return;const i=Cn("Sun",e,t),s=Cn("Moon",e,t),a=i.altitudeDeg>0,o=a?i:s;if(o.altitudeDeg<=0)return this.messages.skyBowNoSource;const l=n.lowerCloudCover??n.cloudCover;if(an.strength(n.precipitationIntensity,l,o.altitudeDeg)<=0)return this.messages.skyBowHidden;const c=an.formsAt(o.altitudeDeg);if(c.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(o.altitudeDeg))).replace("{radius}",String(Math.round(an.primary().radiusDeg)));const h=this.listed(c.map(u=>this.bowFormName(u)));if(a)return this.messages.skyBowPossible.replace("{forms}",h);const d=Math.round(vc(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",h).replace("{lit}",String(d))}glowClause(e,t){if(Cn("Sun",e,t).altitudeDeg>WA)return;const i=this.glows.assess(e,t),s=this.showerLanguage(),a=[];if(i.milkyWay&&a.push(this.messages.skyGlowBand.replace("{contrast}",this.decimal(i.milkyWay.contrast,1)).replace("{altitude}",String(Math.round(i.milkyWay.altitudeDeg))).replace("{bearing}",_s.towards(i.milkyWay.azimuthDeg,s))),i.zodiacal){const h=i.zodiacal.sunSeparationDeg<=it.CONE_SEPARATION_DEG;a.push((h?this.messages.skyGlowCone:this.messages.skyGlowZodiacalBand).replace("{contrast}",this.decimal(i.zodiacal.contrast,1)).replace("{altitude}",String(Math.round(i.zodiacal.altitudeDeg))).replace("{bearing}",_s.towards(i.zodiacal.azimuthDeg,s)).replace("{elongation}",String(Math.round(i.zodiacal.sunSeparationDeg))))}if(a.length>0)return this.listed(a);const o=this.decimal(i.darkestSkyMagPerArcsec2,1),l=Cn("Moon",e,t),c=i.darkestSkyMagPerArcsec2<VA;if(c&&l.altitudeDeg>0){const h=Math.round(vc(e).illuminatedFraction*100);return this.messages.skyGlowMoon.replace("{lit}",String(h)).replace("{sky}",o)}return c?this.messages.skyGlowTwilight.replace("{sky}",o):this.messages.skyGlowNothingUp.replace("{sky}",o)}glows=new it;bowFormName(e){return(e.id==="primary"?this.messages.skyBowPrimary:this.messages.skyBowSecondary).replace("{radius}",String(Math.round(e.radiusDeg))).replace("{top}",String(Math.round(e.topAltitudeDeg)))}opticsFormName(e){const t=n=>String(Math.round(n??0));switch(e.id){case"halo22":return this.messages.skyOpticsHalo22.replace("{angle}",t(e.angleDeg));case"halo46":return this.messages.skyOpticsHalo46.replace("{angle}",t(e.angleDeg));case"parhelia":return this.messages.skyOpticsParhelia.replace("{angle}",t(e.angleDeg));case"tangentArc":return this.messages.skyOpticsTangentArc;case"parhelicCircle":return this.messages.skyOpticsParhelicCircle;case"circumzenithal":return this.messages.skyOpticsCircumzenithal.replace("{angle}",t(e.angleDeg));case"circumhorizontal":return this.messages.skyOpticsCircumhorizontal;case"pillar":return this.messages.skyOpticsPillar}}listed(e){return new Intl.ListFormat(this.showerLanguage(),{style:"long",type:"conjunction"}).format(e)}cometText(e){const t=e.apparition.name[this.showerLanguage()],n=e.magnitude.toLocaleString(void 0,{maximumFractionDigits:1});return e.position.altitudeDeg<=0?this.messages.skyCometBelowHorizon.replace("{name}",t).replace("{magnitude}",n):(e.elongationDeg<ql.TWILIGHT_ELONGATION_DEG?this.messages.skyCometInDaylight:e.tailLengthDeg===void 0?this.messages.skyCometNoTail:this.messages.skyComet).replace("{name}",t).replace("{magnitude}",n).replace("{altitude}",String(Math.round(e.position.altitudeDeg))).replace("{bearing}",_s.towards(e.position.azimuthDeg,this.showerLanguage())).replace("{tail}",String(Math.round(e.tailLengthDeg??0))).replace("{elongation}",String(Math.round(e.elongationDeg)))}lookAtComet(){const e=this.ufoElement.sighting,t=e.event.place?.[0],n=e.event.time;if(!t||t.lat===void 0||t.lng===void 0||n?.year===void 0)return;const i=Ds(n,t.lng,e.event.utcOffsetHours);if(!i)return;const s=ql.brightestAt(i,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});s&&(this.headingInput.value=String(this.rounded(s.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(s.position.altitudeDeg)),this.updateObserver())}rounded(e){return Math.round(e*10)/10}lookAtDecor(){const e=this.ufoElement.sighting.decor.find(l=>l.id===this.currentDecorId);if(!e)return;const{eastM:t,northM:n,altitudeM:i}=fa(e,this.ufoElement.currentTime),s=Math.hypot(t,n);if(s===0&&i===0)return;const a=Math.atan2(t,n)*180/Math.PI,o=Math.atan2(i-BA,s)*180/Math.PI;this.headingInput.value=String(Math.round(a*10)/10),this.pitchInput.value=String(Math.round(o*10)/10),this.updateObserver()}refreshDecorLightRigOptions(e){const t=e?Nc.forKind(e.kind):[],n=document.createElement("option");n.value="",n.textContent=this.messages.decorLightsNone,this.decorLightRigSelect.replaceChildren(n,...t.map(s=>{const a=document.createElement("option");return a.value=s.id,a.textContent=s.name,a}));const i=e?.lights?.map(s=>s.id).join()??"";this.decorLightRigSelect.value=t.find(s=>s.create().map(a=>a.id).join()===i)?.id??""}updateDecorLightRig(){const e=this.ufoElement.sighting,t=e.decor.find(i=>i.id===this.currentDecorId);if(!t)return;const n=Nc.byId(this.decorLightRigSelect.value);e.decor=e.decor.map(i=>i.id===t.id?{...i,lights:n?n.create():void 0}:i),this.ufoElement.refresh(),this.dispatchEvent(new CustomEvent("sightingchange"))}syncDecorLitFromTimeline(){if(this.ufoElement.playbackState==="playing"||this.shadow.activeElement===this.decorLitInput)return;const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);e&&(this.decorLitInput.checked=jl(e,this.ufoElement.currentTime))}updatePresetButtons(){for(const e of Gm)this.presetButtons[e]?.setAttribute("aria-pressed",String(e===this.currentAppearance.presetId))}get samplingRate(){return Number(this.samplingRateInput.value)}buildPrototype(e=this.defaultBounds()){return _f(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-Vr.width/2,y:e.height/2-Vr.height/2,width:Vr.width,height:Vr.height}}toggleRecording(){this.endDrag();const e=this.ufoElement.canvasElement;this.isRecording?(this.recorder?.stop(),this.isRecording=!1,this.setRecordButtonLabel(!1),this.setCanvasCursor(void 0),e.style.touchAction="",this.sourceSelect.disabled=!1,this.addShapeButton.disabled=!1,this.ufoElement.refresh(),this.refreshSourceList()):(this.recorder=new tA(this.ufoElement.sighting.timeline,new nA(this.samplingRate)),this.recorder.start(this.currentSourceId,this.buildPrototype()),this.isRecording=!0,this.setRecordButtonLabel(!0),this.setCanvasCursor("record"),e.style.touchAction="none",this.sourceSelect.disabled=!0,this.addShapeButton.disabled=!0,this.deleteShapeButton.disabled=!0)}setRecordButtonLabel(e){this.recordButton.textContent=e?"⏹":"⏺";const t=e?this.messages.stop:this.messages.record;this.recordButton.title=t,this.recordButton.setAttribute("aria-label",t)}async loadLocaleMessages(){const e=na(Ts.preferencesFor(this),od);e!=="en"&&(this.tagNames=new rd(await q1(e)),this.showTags(),this.applyMessages(await X1(e)))}showTags(){this.tagsInput.value=this.ufoElement.sighting.event.tags?.map(e=>this.tagNames.name(e)).join(", ")??""}applyMessages(e){this.currentSourceId===kl&&this.shapeTitleInput.value===`${this.messages.shape} 1`?(this.messages=e,this.shapeTitleInput.value=`${this.messages.shape} 1`,this.updateShapeTitle()):this.messages=e,this.presetButtons.oval.textContent=e.oval,this.presetButtons.polygon.textContent=e.polygon,this.contextAddVertexButton.textContent=e.addVertex,this.contextDeleteVertexButton.textContent=e.deleteVertex,this.labelColor.textContent=e.color,this.labelTransparency.textContent=e.transparency,this.labelHalo.textContent=e.halo,this.labelBlur.textContent=e.blur,this.labelBrightness.textContent=e.brightness,this.labelShape.textContent=e.shape,this.labelShapeTitle.textContent=e.shapeTitle,this.labelUtcOffset.textContent=e.utcOffset,this.utcOffsetInput.placeholder=e.utcOffsetPlaceholder,this.labelApparentWidth.textContent=e.apparentWidth,this.labelRealWidth.textContent=e.realWidth,this.labelObjectDistance.textContent=e.distance,this.labelSizeLock.textContent=e.sizeLock;for(const[i,s]of[["option-lock-none",e.lockNone],["option-lock-apparent",e.lockApparent],["option-lock-real",e.lockReal],["option-lock-distance",e.lockDistance]])this.shadow.getElementById(i).textContent=s;this.clearDistanceHypothesisButton.textContent=e.clearDistanceHypothesis,this.clearDistanceHypothesisButton.title=e.clearDistanceHypothesisTitle,this.refreshApparentSize(),this.labelSamplingRate.textContent=e.samplingRate,this.labelDuration.textContent=e.duration,this.durationInput.placeholder=e.durationPlaceholder,this.addShapeButton.title=e.addShape,this.addShapeButton.setAttribute("aria-label",e.addShape),this.deleteShapeButton.title=e.deleteShape,this.deleteShapeButton.setAttribute("aria-label",e.deleteShape),this.contextGroupButton.textContent=e.group,this.contextUngroupButton.textContent=e.ungroup,this.contextBringToFrontButton.textContent=e.bringToFront,this.contextSendToBackButton.textContent=e.sendToBack,this.contextDeleteButton.textContent=e.contextMenuDelete,this.exportButton.textContent=e.export,this.labelImportFile.textContent=e.importFile,this.labelImportUrl.textContent=e.importUrl,this.importUrlInput.placeholder=e.importUrlPlaceholder,this.importUrlButton.textContent=e.importButton,this.labelWitnessAge.textContent=e.witnessAge,this.labelWitnessOccupation.textContent=e.witnessOccupation,this.labelTestimonySource.textContent=e.testimonySource,this.labelTestimonyFollowedUp.textContent=e.testimonyFollowedUp;for(const[i,s]of[["option-source-unknown",e.testimonySourceUnknown],["option-source-on-site",e.testimonySourceOnSite],["option-source-interview",e.testimonySourceInterview],["option-source-telephone",e.testimonySourceTelephone],["option-source-questionnaire",e.testimonySourceQuestionnaire],["option-source-letter",e.testimonySourceLetter],["option-source-press",e.testimonySourcePress],["option-followed-unknown",e.testimonyUnknown],["option-followed-yes",e.testimonyYes],["option-followed-no",e.testimonyNo]]){const a=this.shadow.getElementById(i);a&&(a.textContent=s)}this.labelNarrativeKey.textContent=e.narrativeKey.replace("{source}",Ns[0].name),this.labelNarrativeWorkspace.textContent=e.narrativeWorkspace,this.narrativeWorkspaceInput.placeholder=e.narrativeWorkspacePlaceholder,this.narrativeWorkspaceInput.title=e.narrativeWorkspaceHint,this.labelNarrativeRemember.textContent=e.narrativeRemember,this.narrativeStopButton.textContent=e.narrativeStop,this.narrativeDraftButton.textContent=e.narrativeDraft,this.descriptionInput.placeholder=e.narrativePlaceholder,this.syncNarrativeEnabled(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.labelPlaceName.textContent=e.placeName,this.placeNameInput.placeholder=e.placeNamePlaceholder,this.searchPlaceButton.textContent=e.searchPlace,this.labelPlaceMatch.textContent=e.placeMatch,this.labelLatitude.textContent=e.latitude,this.labelLongitude.textContent=e.longitude,this.labelHeading.textContent=e.heading,this.headingInput.placeholder=e.headingPlaceholder,this.labelPitch.textContent=e.pitch,this.labelRoll.textContent=e.roll,this.labelElevation.textContent=e.elevation,this.labelObservationTime.textContent=e.observationTime,this.labelObservationEndTime.textContent=e.observationEndTime,this.obsTimeInput.placeholder=e.edtfPlaceholder,this.obsTimeInput.title=e.observationTimeHint,this.obsEndTimeInput.placeholder=e.edtfPlaceholder,this.obsEndTimeInput.title=e.observationEndTimeHint,this.presetsGroup.setAttribute("aria-label",e.presetsGroupLabel),this.labelDecor.textContent=e.decor,this.labelDecorGroup.textContent=e.decor,this.optionDecorBuilding.textContent=e.decorBuilding,this.optionDecorTree.textContent=e.decorTree,this.optionDecorCrop.textContent=e.decorCrop,this.optionDecorMound.textContent=e.decorMound,this.optionDecorStreetlight.textContent=e.decorStreetlight,this.optionDecorVehicle.textContent=e.decorVehicle,this.optionDecorAircraft.textContent=e.decorAircraft,this.optionDecorEntity.textContent=e.decorEntity,this.labelDecorLights.textContent=e.decorLights,this.labelDecorAltitude.textContent=e.decorAltitude,this.showMeteorButton.title=e.showMeteor,this.showMeteorButton.setAttribute("aria-label",e.showMeteor),this.showCometButton.title=e.showComet,this.showCometButton.setAttribute("aria-label",e.showComet),this.showSatelliteButton.title=e.showSatellite,this.showSatelliteButton.setAttribute("aria-label",e.showSatellite),this.lookAtDecorButton.title=e.lookAtDecor,this.lookAtDecorButton.setAttribute("aria-label",e.lookAtDecor),this.optionDecorWitness.textContent=e.decorWitness,this.deleteDecorButton.title=e.deleteDecor,this.deleteDecorButton.setAttribute("aria-label",e.deleteDecor),this.labelDecorTitle.textContent=e.decorTitle,this.labelDecorEast.textContent=e.decorEast,this.labelDecorNorth.textContent=e.decorNorth,this.labelDecorHeading.textContent=e.decorHeading,this.labelDecorColor.textContent=e.decorColor,this.labelDecorLit.textContent=e.decorLit,this.labelDecorSightingUrl.textContent=e.decorSightingUrl,this.contextViewTestimonyButton.textContent=e.viewTestimony,this.labelContextMasks.textContent=`${e.masks} ▸`,this.addDecorWitnessButton.textContent=e.addWitness,this.addDecorBuildingButton.title=e.addDecor,this.addDecorBuildingButton.setAttribute("aria-label",e.addDecor),this.confirmAcceptButton.textContent=e.confirmAccept,this.confirmDeclineButton.textContent=e.confirmDecline,this.labelMilestones.textContent=e.milestones,this.labelMilestoneLabel.textContent=e.milestoneLabel,this.labelMilestoneNote.textContent=e.milestoneNote;for(const[i,s]of[[this.addMilestoneButton,e.addMilestone],[this.deleteMilestoneButton,e.deleteMilestone]])i.title=s,i.setAttribute("aria-label",s);this.labelDecorWidth.textContent=e.decorWidth,this.labelDecorLength.textContent=e.decorLength,this.labelDecorHeight.textContent=e.decorHeight,this.labelDecorModel.textContent=e.decorModel,this.labelDecorModelAdvanced.textContent=e.decorModelAdvanced,this.labelDecorModelUrl.textContent=e.decorModelUrl,this.labelDecorModelTitle.textContent=e.decorModelTitle,this.labelDecorModelAuthor.textContent=e.decorModelAuthor,this.labelDecorModelLicense.textContent=e.decorModelLicense,this.labelDecorModelSource.textContent=e.decorModelSource,this.labelDecorFloors.textContent=e.decorFloors,this.labelDecorOccupiedFloor.textContent=e.decorOccupiedFloor,this.labelDecorWitnessSide.textContent=e.decorWitnessSide,this.labelDecorWindows.textContent=e.decorWindows,this.optionWitnessSideNone.textContent=e.decorWitnessSideNone;const t={front:e.decorSideFront,behind:e.decorSideBehind,left:e.decorSideLeft,right:e.decorSideRight,"front-left":e.decorSideFrontLeft,"front-right":e.decorSideFrontRight,"behind-left":e.decorSideBehindLeft,"behind-right":e.decorSideBehindRight};for(const i of gr)this.labelDecorSide[i].textContent=t[i],this.optionWitnessSide[i].textContent=t[i];this.refreshDecorList(),this.labelWitnessId.textContent=e.witnessId,this.labelWitnessDirName.textContent=e.witnessDirName,this.labelWitnessTitle.textContent=e.witnessTitle,this.labelWitnessLastName.textContent=e.witnessLastName,this.labelWitnessFirstNames.textContent=e.witnessFirstNames,this.witnessFirstNamesInput.placeholder=e.tagsPlaceholder,this.labelCaseId.textContent=e.caseId,this.labelDescription.textContent=e.description,this.labelTags.textContent=e.tags,this.tagsInput.placeholder=e.tagsPlaceholder,this.labelShapeGroup.textContent=e.shapeGroup,this.labelTemporalGroup.textContent=e.temporalGroup,this.labelLocationGroup.textContent=e.locationGroup,this.labelObservationGroup.textContent=e.observationGroup,this.labelWitnessGroup.textContent=e.witnessGroup,this.labelWeatherGroup.textContent=e.weather,this.refreshTimeQualifierOptions(),this.edtfModeButton.title=e.edtfModeTitle,this.edtfModeButton.setAttribute("aria-label",e.edtfModeTitle),this.paramSummaryBuilder=new Bf(e,this.showerLanguage(),this.said,this.tagNames),this.refreshParamSummary();const n=this.skyDetailsButton.getAttribute("aria-expanded")==="true";this.skyDetailsButton.title=n?e.skyDetailsHide:e.skyDetails,this.skyDetailsButton.setAttribute("aria-label",this.skyDetailsButton.title),this.labelCloudCover.textContent=e.cloudCover,this.labelHighCloud.textContent=e.highCloudCover,this.labelIceAlignment.textContent=e.iceCrystalAlignment,this.labelFNumber.textContent=e.aperture,this.labelExposure.textContent=e.exposure,this.labelFocusDistance.textContent=e.focusDistance,this.syncOpticsFromInstrument(),this.labelCloudDarkness.textContent=e.cloudDarkness,this.labelCloudBase.textContent=e.cloudBase,this.labelPrecipitationType.textContent=e.precipitationType,this.optionPrecipitationNone.textContent=e.precipitationNone,this.optionPrecipitationRain.textContent=e.precipitationRain,this.optionPrecipitationSnow.textContent=e.precipitationSnow,this.optionPrecipitationHail.textContent=e.precipitationHail,this.labelPrecipitationIntensity.textContent=e.precipitationIntensity,this.labelWindDirection.textContent=e.windDirection,this.labelWindSpeed.textContent=e.windSpeed,this.labelStorm.textContent=e.storm,this.labelCloudsGroup.textContent=e.cloudsGroup,this.labelPrecipitationGroup.textContent=e.precipitationGroup,this.labelWindGroup.textContent=e.windGroup,this.labelWeatherInferred.textContent=e.weatherInferred,this.syncWeatherSourceState(),this.labelSoundGroup.textContent=e.soundGroup,this.labelSoundKind.textContent=e.soundKind,this.labelSoundVolume.textContent=e.soundVolume,this.labelSoundPitch.textContent=e.soundPitch,this.labelSoundSrc.textContent=e.soundSrc,this.soundSrcInput.placeholder=e.soundSrcPlaceholder,this.labelReferenceGroup.textContent=e.referenceGroup,this.labelReference.textContent=e.reference,this.labelReferenceTitle.textContent=e.referenceTitle,this.labelReferenceSrc.textContent=e.referenceSrc,this.referenceSrcInput.placeholder=e.referenceSrcPlaceholder,this.labelReferenceKind.textContent=e.referenceKind,this.referenceKindSelect.querySelector("#reference-kind-photo").textContent=e.referencePhoto,this.referenceKindSelect.querySelector("#reference-kind-panorama").textContent=e.referencePanorama,this.labelReferenceCredit.textContent=e.referenceCredit,this.labelReferenceCreditUrl.textContent=e.referenceCreditUrl,this.labelReferenceT.textContent=e.referenceT,this.labelReferenceDrawing.textContent=e.referenceDrawing,this.labelReferenceOpacity.textContent=e.referenceOpacity,this.labelReferenceHeading.textContent=e.referenceHeading,this.labelReferencePitch.textContent=e.referencePitch,this.labelReferenceRoll.textContent=e.referenceRoll,this.labelReferenceFov.textContent=e.referenceFov,this.referenceUsePoseButton.textContent=e.referenceUsePose,this.addReferenceUrlButton.textContent=e.addReferenceUrl,this.labelAddReferenceFile.textContent=e.addReferenceFile,this.deleteReferenceButton.title=e.deleteReference,this.deleteReferenceButton.setAttribute("aria-label",e.deleteReference),this.labelReferenceLandmarks.textContent=e.referenceLandmarks,this.addReferenceLandmarkButton.textContent=e.addReferenceLandmark,this.deleteReferenceLandmarkButton.title=e.deleteReferenceLandmark,this.deleteReferenceLandmarkButton.setAttribute("aria-label",e.deleteReferenceLandmark),this.labelReferenceLandmarkLabel.textContent=e.referenceLandmarkLabel,this.referenceLandmarkLabelInput.placeholder=e.referenceLandmarkLabelPlaceholder,this.referenceAdoptPoseButton.textContent=e.referenceAdoptPose,this.referenceStreetSearchButton.textContent=e.referenceStreetSearch,this.referenceStreetAddButton.textContent=e.referenceStreetAdd;for(const[i,s]of this.soundKindOptions)s.textContent=this.soundKindLabel(i,e);this.labelInstrument.textContent=e.instrument,this.loopButton.title=e.autoReplay,this.loopButton.setAttribute("aria-label",e.autoReplay),this.setRecordButtonLabel(this.isRecording),this.syncPlaybackControls()}onPointerDown(e){if(this.isRecording){this.onPointerMove(e);return}const t=this.canvasPointFromEvent(e);if(!t)return;const n=this.canvasMode();if(n==="picture"){this.ufoElement.playbackState!=="playing"&&this.beginReferenceDrag(t);return}const i=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,a=this.ufoElement.playbackState==="playing",o=n==="shape";if(o)if(this.selectedSourceIds.size>1){const h=new kc(this.selectedMembers()),d=st.hitTestHandle({bounds:h.bounds(),angle:0},t);if(d==="rotate"){if(a)return;this.dragState={kind:"group-rotate",group:h,startPointer:t},this.startDragListening();return}if(d){if(a)return;this.dragState={kind:"group-resize",group:h,handle:d},this.startDragListening();return}}else{const h=i.getInterpolatedShapeAt(s,this.currentSourceId),d=h?.kind==="polygon"?st.hitTestVertex(h,t):void 0;if(h?.kind==="polygon"&&d!==void 0){if(a)return;this.dragState={kind:"vertex",sourceId:this.currentSourceId,original:h,vertexIndex:d},this.startDragListening();return}const u=h&&st.hitTestHandle(h,t);if(h&&u){if(a)return;this.beginDrag(u==="rotate"?"rotate":"resize",this.currentSourceId,h,t,u);return}}const l=this.ufoElement.shapeAt(t.x,t.y,Um);if(!l){const h=this.pickDecorAt(e);if(h!==void 0){this.selectDecor(h);return}a||this.beginCameraDrag(t);return}if(this.revealShapePanel(),e.shiftKey?this.toggleUnitSelection(l.sourceId):this.selectedSourceIds.has(l.sourceId)||this.selectUnit(l.sourceId),a||!o)return;const c=[...this.selectedSourceIds].map(h=>({sourceId:h,original:h===l.sourceId?l.shape:i.getInterpolatedShapeAt(s,h)??l.shape}));this.dragState={kind:"move",sources:c,startPointer:t},this.startDragListening()}revealShapePanel(){const e=this.groupTabs.find(t=>t.getAttribute("aria-controls")==="group-shape");e&&this.toggleGroup(e,!0)}selectedMembers(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime;return[...this.selectedSourceIds].map(n=>({sourceId:n,shape:e.getInterpolatedShapeAt(t,n)})).filter(n=>!!n.shape)}selectUnit(e){const t=this.ufoElement.sighting.timeline.groupMembers(e)??[e];t.length===this.selectedSourceIds.size&&t.every(n=>this.selectedSourceIds.has(n))&&e===this.currentSourceId||(this.selectedSourceIds=new Set(t),this.currentSourceId=e,this.refreshSourceList(),this.onSelectionOrTimeChanged())}toggleUnitSelection(e){const t=this.ufoElement.sighting.timeline,n=t.groupMembers(e)??[e];if(n.every(s=>this.selectedSourceIds.has(s))){if(n.length>=this.selectedSourceIds.size)return;for(const s of n)this.selectedSourceIds.delete(s);if(!this.selectedSourceIds.has(this.currentSourceId)){const s=t.sourceIds;this.currentSourceId=[...this.selectedSourceIds].sort((a,o)=>s.indexOf(a)-s.indexOf(o)).pop()}}else{for(const s of n)this.selectedSourceIds.add(s);this.currentSourceId=e}this.refreshSourceList(),this.onSelectionOrTimeChanged()}onContextMenu(e){if(e.preventDefault(),this.isRecording||this.ufoElement.playbackState==="playing")return;this.hideContextMenu(),this.hideDecorContextMenu();const t=this.canvasPointFromEvent(e);if(!t)return;const n=this.ufoElement.sighting.timeline,i=this.ufoElement.currentTime,s=this.selectedSourceIds.size===1?n.getInterpolatedShapeAt(i,this.currentSourceId):void 0,o=s?.kind==="polygon"&&st.hitTestVertex(s,t)!==void 0?{sourceId:this.currentSourceId}:this.ufoElement.shapeAt(t.x,t.y,Um);if(o){this.selectedSourceIds.has(o.sourceId)||this.selectUnit(o.sourceId),this.currentSourceId=o.sourceId,this.contextMenuPoint=t,this.showContextMenu(e.clientX,e.clientY);return}const l=this.pickDecorAt(e),c=l?this.ufoElement.sighting.decor.find(h=>h.id===l):void 0;c&&this.showDecorContextMenu(e.clientX,e.clientY,c)}pickDecorAt(e){const n=this.ufoElement.canvasElement.getBoundingClientRect();if(n.width===0||n.height===0)return;const i=(e.clientX-n.left)/n.width*2-1,s=-((e.clientY-n.top)/n.height*2-1);return this.sceneElement.pickDecorAt(i,s)}showContextMenu(e,t){this.contextMenu.style.left=`${e}px`,this.contextMenu.style.top=`${t}px`,this.contextMenu.hidden=!1;const n=this.ufoElement.sighting.timeline.sourceIds,i=n.filter(f=>this.selectedSourceIds.has(f)),s=n.length<=i.length,a=i.length>0&&n.slice(n.length-i.length).every(f=>this.selectedSourceIds.has(f)),o=i.length>0&&n.slice(0,i.length).every(f=>this.selectedSourceIds.has(f));this.contextBringToFrontButton.disabled=s||a,this.contextSendToBackButton.disabled=s||o,this.contextBringToFrontButton.title=s?this.messages.onlyOneShape:a?this.messages.alreadyAtFront:"",this.contextSendToBackButton.title=s?this.messages.onlyOneShape:o?this.messages.alreadyAtBack:"",this.contextGroupButton.disabled=this.selectedSourceIds.size<2,this.contextGroupButton.title=this.contextGroupButton.disabled?this.messages.needTwoShapesToGroup:"";const l=this.ufoElement.sighting.timeline.groupMembers(this.currentSourceId)!==void 0;this.contextUngroupButton.disabled=!l,this.contextUngroupButton.title=l?"":this.messages.notGrouped,this.contextDeleteButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.title=this.contextDeleteButton.disabled?this.messages.onlyOneShape:"";const c=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId),h=this.selectedSourceIds.size===1&&c?.kind==="polygon";this.contextAddVertexButton.disabled=!h,this.contextAddVertexButton.title=h?"":this.messages.notAPolygon;const d=h&&this.contextMenuPoint?st.hitTestVertex(c,this.contextMenuPoint):void 0,u=h&&c.points.length<=Zm;this.contextDeleteVertexButton.disabled=!h||d===void 0||u,this.contextDeleteVertexButton.title=h?u?this.messages.tooFewVertices:"":this.messages.notAPolygon,document.addEventListener("click",this.handleOutsideContextMenuClick)}hideContextMenu(){this.contextMenu.hidden=!0,this.contextMenuPoint=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}handleOutsideContextMenuClick=e=>{e.composedPath().includes(this.contextMenu)||e.composedPath().includes(this.decorContextMenu)||(this.hideContextMenu(),this.hideDecorContextMenu())};showDecorContextMenu(e,t,n){this.contextMenuDecorId=n.id,this.decorContextMenu.style.left=`${e}px`,this.decorContextMenu.style.top=`${t}px`,this.decorContextMenu.hidden=!1,this.contextViewTestimonyButton.disabled=!n.sightingUrl,this.contextViewTestimonyButton.title=n.sightingUrl?"":this.messages.noWitnessRecording,this.refreshContextMasksSubmenu(n),document.addEventListener("click",this.handleOutsideContextMenuClick)}hideDecorContextMenu(){this.decorContextMenu.hidden=!0,this.contextMenuDecorId=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}refreshContextMasksSubmenu(e){this.contextMasksSubmenu.innerHTML="";for(const t of this.ufoElement.sighting.timeline.sourceIds){const n=document.createElement("label"),i=document.createElement("input");i.type="checkbox",i.checked=e.occludesSourceIds?.includes(t)??!1,i.addEventListener("change",()=>this.updateDecorOccludesShape(e.id,t,i.checked)),n.appendChild(i),n.appendChild(document.createTextNode(this.shapeLabel(t))),this.contextMasksSubmenu.appendChild(n)}}updateDecorOccludesShape(e,t,n){const i=this.ufoElement.sighting;i.decor=i.decor.map(s=>{if(s.id!==e)return s;const a=n?[...new Set([...s.occludesSourceIds??[],t])]:(s.occludesSourceIds??[]).filter(o=>o!==t);return{...s,occludesSourceIds:a.length>0?a:void 0}}),this.ufoElement.refresh()}viewWitnessTestimony(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.contextMenuDecorId);this.hideDecorContextMenu(),e?.sightingUrl&&this.importFromUrl(e.sightingUrl)}addVertexAtContextMenu(){const e=this.contextMenuPoint;if(this.hideContextMenu(),!e)return;const t=this.ufoElement.currentTime,n=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(n?.kind!=="polygon")return;const i=st.insertVertexNear(n,e);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:i}]),this.ufoElement.refresh()}deleteVertexAtContextMenu(){const e=this.contextMenuPoint;if(this.hideContextMenu(),!e)return;const t=this.ufoElement.currentTime,n=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(n?.kind!=="polygon")return;const i=st.hitTestVertex(n,e);if(i===void 0)return;const s=st.deleteVertex(n,i);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:s}]),this.ufoElement.refresh()}bringSelectedToFront(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(n=>this.selectedSourceIds.has(n)))e.bringToFront(t);this.hideContextMenu(),this.ufoElement.refresh()}sendSelectedToBack(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(n=>this.selectedSourceIds.has(n)).reverse())e.sendToBack(t);this.hideContextMenu(),this.ufoElement.refresh()}groupSelected(){this.selectedSourceIds.size<2||(this.ufoElement.sighting.timeline.group([...this.selectedSourceIds]),this.hideContextMenu(),this.ufoElement.refresh())}ungroupSelected(){this.ufoElement.sighting.timeline.ungroup(this.currentSourceId),this.selectedSourceIds=new Set([this.currentSourceId]),this.hideContextMenu(),this.ufoElement.refresh()}beginDrag(e,t,n,i,s){this.dragState={kind:e,sourceId:t,original:n,handle:s,startPointer:i},this.startDragListening()}beginCameraDrag(e){const t=this.isWitnessInsideDecor();this.cameraDragState={startPointer:e,startHeadingDeg:t?this.indoorLookYawDeg:this.numberOrUndefined(this.headingInput.value)??0,startPitchDeg:t?this.indoorLookPitchDeg:this.numberOrUndefined(this.pitchInput.value)??0,insideDecor:t},t||this.sceneElement.setCompassForced(!0),this.setCanvasCursor("panning"),this.startDragListening()}isWitnessInsideDecor(){return this.ufoElement.sighting.decor.some(e=>e.witnessSide!==void 0&&Kr(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(n=>n.witnessSide!==void 0&&Kr(n.kind)),t=e?`${e.id}:${e.witnessSide}`:void 0;t!==this.lastInhabitedKey&&(this.lastInhabitedKey=t,this.indoorLookYawDeg=0,this.indoorLookPitchDeg=0,this.sceneElement.setIndoorLook(0,0))}startDragListening(){document.addEventListener("pointermove",this.handleDragPointerMove),document.addEventListener("pointerup",this.handleDragPointerUp)}onDragPointerMove(e){if(this.referenceDragState){this.onReferenceDragPointerMove(e);return}if(this.cameraDragState){this.onCameraDragPointerMove(e);return}if(!this.dragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const n=this.ufoElement.currentTime;if(this.dragState.kind==="move"){const{sources:i,startPointer:s}=this.dragState,a=t.x-s.x,o=t.y-s.y,l=i.map(({sourceId:c,original:h})=>({sourceId:c,shape:{...h,bounds:{...h.bounds,x:h.bounds.x+a,y:h.bounds.y+o}}}));this.commitShapes(n,l)}else if(this.dragState.kind==="group-resize"){const{group:i,handle:s}=this.dragState;this.commitShapes(n,i.resize(s,t))}else if(this.dragState.kind==="group-rotate"){const{group:i,startPointer:s}=this.dragState;this.commitShapes(n,i.rotate(t,s))}else if(this.dragState.kind==="vertex"){const{sourceId:i,original:s,vertexIndex:a}=this.dragState,o=st.moveVertex(s,a,t);this.commitShapes(n,[{sourceId:i,shape:o}])}else{const{kind:i,sourceId:s,original:a,handle:o}=this.dragState,l=i==="resize"?st.resizeShape(a,o,t):st.rotateShape(a,t);this.commitShapes(n,[{sourceId:s,shape:l}])}this.ufoElement.refresh()}onCameraDragPointerMove(e){if(!this.cameraDragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const{startPointer:n,startHeadingDeg:i,startPitchDeg:s,insideDecor:a}=this.cameraDragState,o=i+(t.x-n.x)*zm,l=Math.max(-90,Math.min(90,s-(t.y-n.y)*zm));if(a){this.indoorLookYawDeg=o,this.indoorLookPitchDeg=l,this.sceneElement.setIndoorLook(o,l),this.ufoElement.refresh();return}this.headingInput.value=String(this.rounded(o)),this.pitchInput.value=String(this.rounded(l)),this.updateObserver()}endDrag(){if(this.referenceDragState){this.endReferenceDrag();return}!this.dragState&&!this.cameraDragState||(this.cameraDragState&&!this.cameraDragState.insideDecor&&this.sceneElement.setCompassForced(!1),this.dragState=void 0,this.cameraDragState=void 0,this.setCanvasCursor(this.hoverCursor),document.removeEventListener("pointermove",this.handleDragPointerMove),document.removeEventListener("pointerup",this.handleDragPointerUp))}nudgeBounds(e,t){const n={...e};if(t.shiftKey){switch(t.key){case"ArrowLeft":n.width=Math.max(Es,n.width-vs);break;case"ArrowRight":n.width+=vs;break;case"ArrowUp":n.height=Math.max(Es,n.height-vs);break;case"ArrowDown":n.height+=vs;break}n.x-=(n.width-e.width)/2,n.y-=(n.height-e.height)/2}else switch(t.key){case"ArrowLeft":n.x-=vs;break;case"ArrowRight":n.x+=vs;break;case"ArrowUp":n.y-=vs;break;case"ArrowDown":n.y+=vs;break}return n}moveOrResizeSelectedShapes(e){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.currentTime,n=this.selectedMembers();if(n.length!==0){if(e.preventDefault(),n.length===1){const{sourceId:i,shape:s}=n[0];this.commitShapes(t,[{sourceId:i,shape:{...s,bounds:this.nudgeBounds(s.bounds,e)}}])}else{const i=new kc(n),s=this.nudgeBounds(i.bounds(),e);this.commitShapes(t,i.scaleTo(s))}this.ufoElement.refresh()}}updateHoverCursor(e){this.isRecording||this.dragState||this.cameraDragState||(this.hoverCursor=this.hoverCursorAt(e),this.setCanvasCursor(this.hoverCursor))}hoverCursorAt(e){const t=this.canvasPointFromEvent(e);if(!t)return;const n=this.canvasMode(),i=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,a=this.ufoElement.playbackState!=="playing";if(n==="picture")return a?"pan":void 0;const o=n==="shape";if(a&&o)if(this.selectedSourceIds.size>1){const l=st.hitTestHandle({bounds:new kc(this.selectedMembers()).bounds(),angle:0},t);if(l)return this.cursorForHandle(l,0)}else{const l=i.getInterpolatedShapeAt(s,this.currentSourceId);if(l?.kind==="polygon"&&st.hitTestVertex(l,t)!==void 0)return"vertex";const c=l&&st.hitTestHandle(l,t);if(l&&c)return this.cursorForHandle(c,l.angle)}return i.hitTest(s,t.x,t.y)?a&&o?"move":"select":this.pickDecorAt(e)!==void 0?"select":a?"pan":void 0}cursorForHandle(e,t){return e==="rotate"?"rotate":`resize-${st.resizeAxisFor(e,t)}`}setCanvasCursor(e){const t=this.ufoElement.canvasElement;e?t.dataset.cursor=e:delete t.dataset.cursor}onPointerMove(e){if(!this.isRecording){this.updateHoverCursor(e);return}const t=this.ufoElement.canvasElement,n=t.getBoundingClientRect(),i=e.clientX-n.left,s=e.clientY-n.top;this.recorder?.onPointerMove(i,s),this.ufoElement.renderer.clear(t.width,t.height),this.ufoElement.renderer.paintShape($m(this.buildPrototype({x:0,y:0,width:Vr.width,height:Vr.height}),i,s))}canvasPointFromEvent(e){const t=this.ufoElement.canvasElement,n=t.getBoundingClientRect();if(!(n.width===0||n.height===0))return{x:(e.clientX-n.left)/n.width*t.width,y:(e.clientY-n.top)/n.height*t.height}}}const XA={stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed"},Wm="rr0-sighting-editor",Vm="rr0-ufo-recorder";class qA extends Tt{}function YA(){xc(),customElements.get(Wm)||customElements.define(Wm,Tt),customElements.get(Vm)||customElements.define(Vm,qA)}YA();export{Pn as $,si as A,ut as B,le as C,cw as D,ki as E,sI as F,pt as G,St as H,QA as I,JA as J,qe as K,To as L,nI as M,Oo as N,xt as O,ow as P,Oi as Q,po as R,oo as S,$A as T,eI as U,Re as V,Cg as W,tI as X,to as Y,cn as Z,jn as _,ZA as a,jA as a0,ur as a1,Dg as a2,iI as a3,Db as a4,tc as a5,Kd as a6,oc as a7,rn as a8,Ng as a9,Qu as aa,ef as ab,Qe as ac,Ps as ad,Eo as ae,di as af,is as ag,KA as b,Cn as c,oI as d,ic as e,Rn as f,aI as g,Ve as h,P as i,Dp as j,rI as k,lI as l,Eb as m,Qs as n,zc as o,ad as p,Cy as q,wt as r,Ds as s,Kt as t,yd as u,Sn as v,ju as w,ss as x,Nb as y,Gb as z};