const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/browser-yamnet-classifier-AB9vKKwv.js","assets/preload-helper-xFrS6Fgo.js"])))=>i.map(i=>d[i]); import{_ as ut}from"./preload-helper-xFrS6Fgo.js";const dt=document.querySelector("#manual-report-form"),_=window.BOOMCAST_I18N||{};function Dt(){var ct;if(!dt||!document.querySelector("#burst-mode"))return null;const e=document.querySelector("#burst-start"),n=e.closest(".burst-listener"),i=e.closest(".manual-report__supporting"),l=document.querySelector("#burst-state"),h=document.querySelector("#burst-panel"),A=document.querySelector("#burst-heading"),ae=document.querySelector("#burst-detail"),U=document.querySelector("#burst-waveform"),J=document.querySelector("#burst-preview"),tt=document.querySelector("#burst-resume"),nt=document.querySelector("#burst-discard"),_t=document.querySelector("#burst-stop"),$=document.querySelector("#burst-error"),d=document.querySelector("#burst-mode"),Ne=document.querySelector("#burst-options"),P=document.querySelector("#burst-maximum"),F=document.querySelector("#burst-test-mode"),ve=document.querySelector("#burst-manual-capture"),ye=document.querySelector("#burst-diagnostics"),Se=document.querySelector("#burst-export"),oe=document.querySelector("#burst-review"),_e=document.querySelector("#burst-capture-list"),ie=document.querySelector("#burst-upload-error"),q=new Float32Array(300);let j=0,w="off",x,S,z,g,B,se,ke,I,f,G,Ce,T,N=0,rt=0,at,ot,ce,p=[],L=[],K=!1,Ae=!1,Ue="",Pe=!1;const kt=()=>new Promise((t,r)=>{const a=indexedDB.open("boomcast-burst",1);a.onupgradeneeded=()=>a.result.createObjectStore("clips",{keyPath:"key"}),a.onsuccess=()=>t(a.result),a.onerror=()=>r(a.error)}),Ee=async(t,r)=>{const a=await kt();try{return await new Promise((o,u)=>{const v=a.transaction("clips",t==="read"?"readonly":"readwrite").objectStore("clips"),m=t==="put"?v.put(r):t==="delete"?v.delete(r):v.getAll();m.onsuccess=()=>o(m.result),m.onerror=()=>u(m.error)})}finally{a.close()}},Fe=(t,r)=>Ee("put",{key:`${f}:${r}`,sessionId:f,index:r,file:t.file,at:t.at,duration:t.duration,expires:Date.now()+24*3600*1e3}).catch(()=>{$.textContent="Temporary clip storage unavailable. Keep this page open until submission.",$.hidden=!1}),it=t=>Ee("delete",`${f}:${t}`).catch(()=>{}),Ct=((ct=dt.querySelector('[name="csrfmiddlewaretoken"]'))==null?void 0:ct.value)||"";d.addEventListener("change",()=>{Ne.hidden=!d.checked});const je=async(t,r={})=>{const a=await fetch(t,{method:"POST",credentials:"same-origin",headers:{"X-CSRFToken":Ct,...r instanceof FormData?{}:{"Content-Type":"application/json"}},body:r instanceof FormData?r:JSON.stringify(r)});if(a.redirected&&a.url.includes("/login"))throw new Error("Sign in before starting Burst Listening.");const o=await a.json();if(!a.ok)throw new Error(o.error||`HTTP ${a.status}`);return o},Be=()=>`/fireworks/burst-sessions/${f}/`,c=(t,r={})=>{if(d.checked){L.push({kind:t,wall_at:new Date().toISOString(),elapsed_ms:Math.round(performance.now()-G),...r}),L.length>250&&(L=[...L.slice(0,20),...L.slice(-230)]);try{localStorage.setItem(`boomcast-burst-${f||"starting"}`,JSON.stringify({sessionId:f,timeline:L,lastFrameAt:T,frameCount:N,interrupted:K}))}catch{}}},Y=()=>{if(!d.checked||!G)return;const t=Math.floor((Date.now()-Ce)/1e3);!Pe&&Math.abs(Date.now()-Ce-(performance.now()-G))>5e3&&(Pe=!0,c("clock_disagreement",{note:"Wall and monotonic elapsed time differ; an exact interruption time cannot be inferred."})),ye.textContent=`${K?"Interrupted":w==="review"?"Review":"Listening"} · ${Math.floor(t/60)}:${String(t%60).padStart(2,"0")} · ${p.length} clips · Last confirmed microphone activity: ${T||"none yet"}${Ue}`,!K&&w!=="review"&&t>=Number(P.value)*60&&(c("auto_stop"),X())},st=async()=>{var t;if(!(!f||w==="off"||w==="review"))try{const r=await je(Be(),{sequence:++rt,wall_at:new Date().toISOString(),elapsed_ms:Math.round(performance.now()-G),audio_frames:N,track_state:((t=x==null?void 0:x.getAudioTracks()[0])==null?void 0:t.readyState)||"ended",visibility:document.visibilityState});c("heartbeat_received",{audio_frames:N,last_confirmed_audio_at:T,server_at:r.received_at}),r.previous_timeout_at&&(c("server_heartbeat_recovered",{last_server_heartbeat:r.previous_seen_at,timeout_detected_at:r.previous_timeout_at,first_recovered_at:r.received_at}),Ue=` · Server gap: last received ${r.previous_seen_at}, timeout detected ${r.previous_timeout_at}, recovered ${r.received_at}. Microphone coverage during this gap is uncertain.`,Y())}catch(r){c("heartbeat_error",{message:r.message})}},qe=()=>{_e.replaceChildren(),p.forEach((t,r)=>{const a=document.createElement("li"),o=document.createElement("span");o.textContent=`${new Date(t.at).toLocaleTimeString()} · ${t.duration.toFixed(1)}s `;const u=document.createElement("audio");u.controls=!0,u.src=t.url;const b=document.createElement("label"),v=document.createElement("input");v.type="radio",v.name="burst-primary-choice",v.checked=r===0,v.value=String(r),b.append(v," Primary clip ");const m=document.createElement("button");m.type="button",m.textContent="Delete",m.addEventListener("click",async()=>{const Z=p.length-1;URL.revokeObjectURL(t.url),p.splice(r,1),await it(Z);for(const[xe,ee]of p.entries())await Fe(ee,xe);qe(),Y()}),a.append(o,u,b,m),_e.append(a)})};function Ve(){const t=U.getContext("2d");t.clearRect(0,0,U.width,U.height),t.fillStyle="#ffbd62";const r=U.width/q.length,a=Math.max(.003,...q);for(let o=0;o{for(let m=0;mc("wake_lock_released"))}catch(o){c("wake_lock_error",{message:o.message})}const a=x.getAudioTracks()[0];a.addEventListener("mute",()=>Q("track_muted")),a.addEventListener("ended",()=>Q("track_ended")),a.addEventListener("unmute",()=>c("track_unmuted"))}S=new AudioContext,await S.audioWorklet.addModule(new URL("/static/vite/assets/burst-listener-worklet-BeONn75i.js",import.meta.url)),z=S.createMediaStreamSource(x),g=new AudioWorkletNode(S,"burst-listener"),g.port.postMessage(d.checked?"burst":"single"),B=S.createGain(),B.gain.value=0,g.port.onmessage=({data:a})=>{if(a.type==="level"&&(w==="listening"||w==="tail"))q[j]=a.value,j=(j+1)%q.length,Ve();else if(a.type==="trigger"&&w==="listening")c("capture_start"),D("tail");else if(a.type==="heartbeat")N=a.frames,T=new Date().toISOString(),N===a.frames&&!L.some(o=>o.kind==="first_audio_frames")&&c("first_audio_frames");else if(a.type==="clip"){const o=new File([Et(a.samples,a.sampleRate)],qt(),{type:"audio/wav"});if(I)I(o),I=null;else if(d.checked&&(w==="tail"||w==="listening")){if(p.length<30){const u={file:o,url:URL.createObjectURL(o),at:new Date().toISOString(),duration:a.samples.length/a.sampleRate};p.push(u),Fe(u,p.length-1)}c("capture_end",{count:p.length}),qe(),Y(),D("listening")}else w==="tail"&&(He(),ke=o,se=URL.createObjectURL(o),J.src=se,J.hidden=!1,D("captured"))}},z.connect(g),g.connect(B).connect(S.destination),await S.resume(),c("audio_context_running"),S.addEventListener("statechange",()=>{c(`audio_context_${S.state}`),S.state==="suspended"&&Q("audio_context_suspended")}),q.fill(0),j=0,Ve(),D("listening"),c("recording_armed"),Y(),st()}catch(a){await X(),d.checked&&p.length===0&&(localStorage.removeItem("boomcast-burst-active"),f=null,d.disabled=P.disabled=F.disabled=!1,oe.hidden=!0,ye.hidden=Se.hidden=!0,ve.hidden=!0,D("off")),n&&(n.dataset.state="error"),i&&(i.dataset.state="error"),l&&(l.textContent=_.microphoneUnavailable||"Microphone unavailable"),$.textContent=a.name==="NotAllowedError"?_.microphoneDenied||"Microphone permission was denied. Manual reporting is still available.":a.message||_.microphoneFailed||"Microphone capture failed.",$.hidden=!1}finally{e.disabled=!1}}async function X(){if(d.checked&&w==="tail"&&g){const t=await Promise.race([new Promise(r=>{I=r,g.port.postMessage("snapshot")}),new Promise(r=>setTimeout(()=>r(null),750))]);if(I=null,t&&p.length<30){const r={file:t,url:URL.createObjectURL(t),at:new Date().toISOString(),duration:Math.min(20,t.size/(S.sampleRate*2))};p.push(r),Fe(r,p.length-1),c("capture_end_on_stop")}}if(d.checked&&f&&w!=="review"){c("explicit_stop"),window.clearInterval(at),window.clearInterval(ot);try{await je(`${Be()}stop/`)}catch(t){c("stop_error",{message:t.message})}try{await(ce==null?void 0:ce.release())}catch{}}I&&(I(null),I=null),He(),g==null||g.disconnect(),z==null||z.disconnect(),B==null||B.disconnect(),x==null||x.getTracks().forEach(t=>t.stop()),await(S==null?void 0:S.close()),x=S=z=g=B=null,q.fill(0),j=0,d.checked&&f?(oe.hidden=!1,ve.hidden=!0,qe(),D("review"),Y()):(d.disabled=P.disabled=F.disabled=!1,D("off"))}function Q(t){!d.checked||w==="off"||w==="review"||(K=!0,c(t,{last_confirmed_active:T,first_observed_inactive:new Date().toISOString()}),$.textContent=`Listening interrupted. Last confirmed active: ${T||"unknown"}; first observed inactive: ${new Date().toISOString()}. The stop time is uncertain.`,$.hidden=!1,X())}function We(){He(),q.fill(0),j=0,Ve(),g==null||g.port.postMessage("reset"),g&&D("listening")}return e.addEventListener("click",xt),_t.addEventListener("click",X),nt.addEventListener("click",We),tt.addEventListener("click",We),ve.addEventListener("click",()=>{c("manual_capture"),g==null||g.port.postMessage("manual")}),Se.addEventListener("click",async()=>{let t=null;try{t=await(await fetch(Be(),{credentials:"same-origin"})).json()}catch{}const r={session_id:f,pwa:window.matchMedia("(display-mode: standalone)").matches,test_mode:F.value,timeline:L,last_audio_frame_at:T,audio_frames:N,capture_count:p.length,server:t},a=URL.createObjectURL(new Blob([JSON.stringify(r,null,2)],{type:"application/json"})),o=document.createElement("a");o.href=a,o.download=`boomcast-burst-${f}.json`,o.click(),setTimeout(()=>URL.revokeObjectURL(a),1e3)}),window.addEventListener("pagehide",()=>{c("pagehide"),d.checked?Q("pagehide"):X()}),window.addEventListener("pageshow",()=>c("pageshow")),document.addEventListener("visibilitychange",()=>{c(`visibility_${document.visibilityState}`),document.hidden&&(d.checked?Q("visibility_hidden"):X())}),document.addEventListener("freeze",()=>{c("freeze"),Q("freeze")}),document.addEventListener("resume",()=>c("resume")),(async()=>{if(window.indexedDB)try{const t=await Ee("read");for(const u of t.filter(b=>b.expiresu.sessionId===r&&u.expires>=Date.now()).sort((u,b)=>u.index-b.index);if(!r||!a.length)return;f=r,d.checked=!0,Ne.hidden=!1,d.disabled=P.disabled=F.disabled=!0,p=a.map(u=>({file:u.file,url:URL.createObjectURL(u.file),at:u.at,duration:u.duration}));const o=JSON.parse(localStorage.getItem(`boomcast-burst-${f}`)||"{}");L=o.timeline||[],T=o.lastFrameAt||null,N=o.frameCount||0,G=performance.now(),Ce=Date.now(),K=!0,c("page_reloaded",{last_confirmed_active:T,first_observed_inactive:new Date().toISOString()}),ye.hidden=Se.hidden=!1,oe.hidden=!1,qe(),D("review"),$.textContent="Previous listening was interrupted by a page reload. Captured clips were recovered; coverage after the last confirmed audio frame is unknown.",$.hidden=!1}catch{}})(),{get active(){return w!=="off"},get reviewingBurst(){return d.checked&&w==="review"},async burstForSubmission(t){var r,a;if(!f||w!=="review"||!p.length)throw new Error("Stop listening and keep at least one clip before submitting.");if(Ae)throw new Error("Burst submission is already in progress.");Ae=!0;try{ie.hidden=!1,ie.textContent="Checking clips for speech and classifying the primary clip on this device…";const{AudioPreprocessor:o}=await ut(async()=>{const{AudioPreprocessor:m}=await import("./audio-preprocessor-B6FBlKED.js");return{AudioPreprocessor:m}},[]),{BrowserYamnetClassifier:u}=await ut(async()=>{const{BrowserYamnetClassifier:m}=await import("./browser-yamnet-classifier-AB9vKKwv.js");return{BrowserYamnetClassifier:m}},__vite__mapDeps([0,1]));let b=null;const v=Number(((r=_e.querySelector('input[name="burst-primary-choice"]:checked'))==null?void 0:r.value)||0);for(let m=0;m/speech|conversation|narration|monologue|whisper|speaking/i.test(ee.class)&&ee.score>=.5))throw new Error("speech detected; delete this clip before submitting");m===v&&(b=xe.slice(0,5).map(({class:ee,score:Lt})=>({class:ee,score:Lt})))}catch(Z){throw ie.textContent=`Clip ${m+1}: ${Z.message}. Review or retry this clip.`,new Error(ie.textContent)}t.append("burst_predictions",JSON.stringify(b)),ie.hidden=!0}finally{Ae=!1}t.append("burst_session_id",f),t.append("burst_primary",((a=_e.querySelector('input[name="burst-primary-choice"]:checked'))==null?void 0:a.value)||"0"),t.append("burst_captures",JSON.stringify(p.map(o=>({captured_at:o.at,duration_seconds:o.duration})))),p.forEach(o=>t.append("burst_audio",o.file))},async clipForSubmission(){return ke||(w==="off"||!g?null:new Promise(t=>{I=t,g.port.postMessage("snapshot")}))},submissionSucceeded(){d.checked?(p.forEach((t,r)=>{URL.revokeObjectURL(t.url),it(r)}),p=[],localStorage.removeItem(`boomcast-burst-${f}`),localStorage.removeItem("boomcast-burst-active"),oe.hidden=!0,f=null,d.checked=!1,Ne.hidden=!0,d.disabled=P.disabled=F.disabled=!1,D("off")):We()}}}const s=window.BOOMCAST_I18N||{},R=document.querySelector("#manual-report-form"),fe=document.querySelector("#manual-submit"),le=document.querySelector("#manual-submit-label"),E=document.querySelector("#manual-occurrences"),ht=document.querySelector("#manual-decrease"),gt=document.querySelector("#manual-increase"),Rt=document.querySelector("#manual-latitude"),Ot=document.querySelector("#manual-longitude"),De=document.querySelector("#manual-direction-degrees"),$t=document.querySelector("#manual-direction-accuracy"),Te=()=>document.querySelector("#manual-capture-direction"),k=()=>document.querySelector("#manual-direction-status"),y=()=>document.querySelector("#manual-direction-panel"),re=document.querySelector("#manual-compass"),Re=document.querySelector("#manual-compass-home"),ue=document.querySelector("#manual-compass-rose"),It=document.querySelector("#manual-compass-heading"),Le=document.querySelector("#manual-report-time"),lt=document.querySelector("#report-clock-hours"),mt=document.querySelector("#report-clock-minutes"),Oe=document.querySelector("#manual-occurred-at"),bt=document.querySelector("#report-clock-mode-label"),Je=document.querySelector("#report-clock-date"),W=document.querySelector("#report-clock-edit"),de=document.querySelector("#report-clock-reset"),Ze=document.querySelector("#report-clock-editor"),te=document.querySelector("#report-clock-draft-date"),me=document.querySelector("#report-clock-draft-time"),ze=document.querySelector("#report-clock-apply"),Ge=document.querySelector("#report-clock-cancel"),pe=document.querySelector("#report-clock-error"),O=document.querySelector("#manual-time-approximate");let C="NOW",ge=null,be=!1;const pt=document.querySelector("#manual-burst-status"),ft=document.querySelector("#manual-burst-duration");let ne,$e,H=null;const V=Dt(),Ke=e=>Number.isFinite(e),Xe=e=>[s.north||"North",s.northeast||"Northeast",s.east||"East",s.southeast||"Southeast",s.south||"South",s.southwest||"Southwest",s.west||"West",s.northwest||"Northwest"][Math.floor((e+22.5)%360/45)],Ie=e=>Number(e.toFixed(1)).toString(),Me=()=>{var h,A;if(!Le)return;const e=C==="OVERRIDE"?ge:new Date;Le.dateTime=e.toISOString();const n=new Intl.DateTimeFormat(document.documentElement.lang||void 0,{hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(e),i=(h=n.find(ae=>ae.type==="hour"))==null?void 0:h.value,l=(A=n.find(ae=>ae.type==="minute"))==null?void 0:A.value;!i||!l||!lt||!mt||(lt.textContent=i,mt.textContent=l,Le.setAttribute("aria-label",`${i}:${l}`),Je&&(Je.hidden=C!=="OVERRIDE",C==="OVERRIDE"&&(Je.textContent=new Intl.DateTimeFormat(document.documentElement.lang||void 0,{day:"numeric",month:"long",year:"numeric"}).format(e))))};Me();Le&&window.setInterval(Me,6e4);const Tt=(le==null?void 0:le.textContent)||"I heard fireworks",Qe=e=>{const n=i=>String(i).padStart(2,"0");return`${e.getFullYear()}-${n(e.getMonth()+1)}-${n(e.getDate())}T${n(e.getHours())}:${n(e.getMinutes())}`},wt=()=>{pe&&(pe.hidden=!0,pe.textContent="",te.removeAttribute("aria-invalid"),me.removeAttribute("aria-invalid"))},et=()=>{Ze.hidden=!0,W.setAttribute("aria-expanded","false"),wt(),W.focus()};W==null||W.addEventListener("click",()=>{const[e,n]=Qe(C==="OVERRIDE"?ge:new Date).split("T");te.value=e,me.value=n,O.checked=C==="OVERRIDE"&&be,O.disabled=!1,wt(),Ze.hidden=!1,W.setAttribute("aria-expanded","true"),te.focus()});Ge==null||Ge.addEventListener("click",()=>{O.checked=C==="OVERRIDE"&&be,O.disabled=C==="NOW",et()});ze==null||ze.addEventListener("click",()=>{const e=te.value,n=me.value.trim(),i=`${e}T${n}`,h=/^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d$/.test(i)?new Date(i):null;if(!h||Number.isNaN(h.getTime())||Qe(h)!==i||h.getTime()>Date.now()+3e5){pe.textContent=!h||Number.isNaN(h.getTime())||Qe(h)!==i?s.invalidReportTime||"Enter a valid date and time.":s.futureReportTime||"Report time cannot be in the future.",pe.hidden=!1,te.setAttribute("aria-invalid","true"),me.setAttribute("aria-invalid","true"),(e?me:te).focus();return}ge=h,be=O.checked,C="OVERRIDE",Oe.value=h.toISOString(),bt.textContent=s.adjusted||"Adjusted",de.hidden=!1,Me(),et()});de==null||de.addEventListener("click",()=>{C="NOW",ge=null,be=!1,Oe.value="",O.checked=!1,O.disabled=!0,bt.textContent=s.now||"Now",de.hidden=!0,Me(),Ze.hidden||et(),W.focus()});const M=(e,n="")=>{if(R.dataset.state=e,fe.disabled=e==="submitting",le&&(le.textContent=e==="submitting"?s.sendingReport||"Sending…":Tt),n){const i=document.querySelector("#manual-submission");i.className="manual-report__submission",i.textContent=n}},vt=e=>{const n=e==null?void 0:e.dataset.nextNoteToken,i=document.querySelector("#manual-note-context");!n||!i||i.value===n||(i.value=n,window.htmx&&htmx.ajax("GET","/fireworks/notes/?token="+encodeURIComponent(n),{target:"#live-field-notes",swap:"outerHTML"}))},yt=(e,n)=>{const i=new DOMParser().parseFromString(e,"text/html").querySelector("#manual-submission");return i?(document.querySelector("#manual-submission").replaceWith(i),n&&vt(i),M(n?"submitted":"error"),n):(M("error",s.reportFailed||"Could not send the report. Please try again."),!1)},St=()=>{const e=Number(E.value)>=3;pt&&(pt.textContent=e?s.burstEvent||"Burst Event":s.ordinaryReport||"Ordinary report"),ft&&(ft.hidden=!e)},we=e=>{const n=Number.parseInt(e,10);E.value=String(Math.min(1e3,Math.max(1,Number.isFinite(n)?n:1))),ht.disabled=E.value==="1",gt.disabled=E.value==="1000",St()};we(E.value);ht.addEventListener("click",()=>we(Number(E.value)-1));gt.addEventListener("click",()=>we(Number(E.value)+1));E.addEventListener("change",()=>we(E.value));E.addEventListener("input",St);const he=()=>{ne&&window.removeEventListener("deviceorientation",ne),window.clearTimeout($e),ne=null,$e=null,re.hidden=!0,H=null},Mt=e=>{const n=-e;if(H===null)H=n,ue.style.transition="none",ue.style.transform=`rotate(${H}deg)`,ue.offsetWidth,ue.style.transition="";else{const i=(n-H+540)%360-180;H+=i,ue.style.transform=`rotate(${H}deg)`}It.textContent=`${Ie(e)}° · ${Xe(e)}`,re.setAttribute("aria-label",`${s.compassDirection||"Compass direction"} ${Ie(e)}° ${Xe(e)}`),re.hidden=!1},Nt=(e,n)=>{const i=k();if(i)if(i.classList.toggle("manual-direction-panel__status--accuracy",n!==null),n===null)i.textContent=s.accuracyUnavailable||"Accuracy unavailable";else{const h=document.createElement("span");h.textContent=s.accuracy||"Accuracy";const A=document.createElement("strong");A.textContent=`±${Ie(n)}°`,i.replaceChildren(h,A)}const l=Te();l&&(l.textContent=s.stopCapture||"Stop measuring direction")},At=()=>{k()&&(he(),y()&&(y().dataset.state="measuring"),k().textContent=s.pointPhone||"Point the top of your phone toward the sound — direction will update live.",ne=e=>{const n="webkitCompassHeading"in e,i=Ke(e.webkitCompassHeading)?e.webkitCompassHeading:!n&&e.absolute&&Ke(e.alpha)?(360-e.alpha)%360:null;if(i===null||i<0||i>=360)return;const l=Ke(e.webkitCompassAccuracy)&&e.webkitCompassAccuracy>=0?e.webkitCompassAccuracy:null;De.value=i,$t.value=l===null?"":l,Nt(i,l),Mt(i),window.clearTimeout($e)},window.addEventListener("deviceorientation",ne),$e=window.setTimeout(()=>{he();const e=Te(),n=k();e&&(e.textContent=s.captureDirection||"Start measuring direction"),n&&(n.textContent=s.compassUnavailable||"Compass unavailable on this device."),y()&&(y().dataset.state="unavailable")},15e3))},Ut=async()=>{var e;if(ne){he(),Te().textContent=s.captureAgain||"Measure again",y()&&(y().dataset.state=De.value?"captured":"ready");return}if((e=k())==null||e.classList.remove("manual-direction-panel__status--accuracy"),!window.isSecureContext){k().textContent=s.secureCompass||"Compass capture requires a secure HTTPS connection.",y()&&(y().dataset.state="unavailable");return}if(typeof window.DeviceOrientationEvent>"u"){k().textContent=s.compassUnavailable||"Compass unavailable on this device.",y()&&(y().dataset.state="unavailable");return}if(typeof DeviceOrientationEvent.requestPermission=="function"){k().textContent=s.compassPermission||"Requesting compass permission…";try{if(await DeviceOrientationEvent.requestPermission(!0)!=="granted"){k()&&(k().textContent=s.compassDenied||"Compass permission denied."),y()&&(y().dataset.state="unavailable");return}}catch{k()&&(k().textContent=s.compassDenied||"Compass permission denied."),y()&&(y().dataset.state="unavailable");return}}At()},Ye=async()=>{if(Oe&&(Oe.value=C==="OVERRIDE"?ge.toISOString():""),O&&(O.checked=C==="OVERRIDE"&&be,O.disabled=C==="NOW"),we(E.value),he(),M("submitting",s.sendingReport||"Sending…"),V!=null&&V.active){try{const e=new FormData(R);if(V.reviewingBurst)await V.burstForSubmission(e);else{const l=await V.clipForSubmission();l&&e.append("audio",l)}const n=await fetch(R.action,{method:"POST",body:e,credentials:"same-origin"}),i=await n.text();yt(i,n.ok)&&V.submissionSucceeded()}catch(e){M("error",e.message||s.reportFailed||"Could not send the report. Please try again.")}return}if(window.htmx)try{htmx.ajax("POST",R.action,{source:R,target:"#manual-submission",swap:"outerHTML"})}catch{M("error",s.reportFailed||"Could not send the report. Please try again.")}else R.submit()};R.addEventListener("click",e=>{e.target.closest("#manual-capture-direction")&&Ut(),e.target.closest(".manual-direction-panel__close")&&(he(),Re&&Re.append(re))});document.body.addEventListener("htmx:beforeSwap",e=>{var n;((n=e.detail.target)==null?void 0:n.id)==="manual-direction-panel"&&Re&&Re.append(re)});document.body.addEventListener("htmx:afterSwap",e=>{var i,l;if(((i=e.detail.target)==null?void 0:i.id)!=="manual-direction-panel")return;Te()&&((l=y().querySelector(".manual-direction-panel__copy"))==null||l.after(re));const n=document.querySelector("#manual-direction-summary");if(n&&De.value!==""){const h=Number(De.value);n.textContent=`${Xe(h)} · ${Ie(h)}°`,y().dataset.state="captured"}});fe.addEventListener("click",()=>{if(!fe.disabled){if(M("submitting",s.requestingLocation||"Requesting your optional location…"),!navigator.geolocation){Ye();return}navigator.geolocation.getCurrentPosition(e=>{Rt.value=e.coords.latitude,Ot.value=e.coords.longitude,Ye()},()=>Ye(),{enableHighAccuracy:!1,maximumAge:3e5,timeout:1e4})}});R.addEventListener("submit",e=>{e.preventDefault(),fe.disabled||fe.click()});document.body.addEventListener("htmx:afterRequest",e=>{if(e.detail.elt!==R)return;const n=e.detail.xhr;n?n.status>=400?yt(n.responseText,!1):M("submitted"):M("error",s.reportFailed||"Could not send the report. Please try again.")});document.body.addEventListener("htmx:sendError",e=>{e.detail.elt===R&&M("error",s.reportFailed||"Could not send the report. Please try again.")});document.body.addEventListener("htmx:afterSwap",()=>vt(document.querySelector("#manual-submission")));