@camstack/addon-pipeline-orchestrator 1.2.667 → 1.2.668

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.
Files changed (48) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/assets/viewer/.viewer-current-files.json +26 -26
  3. package/assets/viewer/.viewer-version +1 -1
  4. package/assets/viewer/_expo/static/js/web/[frameId]-6678de89f250e616a6e8b31e484776f7.js +23 -0
  5. package/assets/viewer/_expo/static/js/web/[id]-274b188f325e7602d613a7d82b6ba93d.js +2 -0
  6. package/assets/viewer/_expo/static/js/web/{[id]-78f7c87c88400a873d0b533e7c23f76a.js → [id]-49c4637772031ebb0b758071c909bdfc.js} +5 -5
  7. package/assets/viewer/_expo/static/js/web/[id]-5416a07ae546037a982b9b525bee40e1.js +61 -0
  8. package/assets/viewer/_expo/static/js/web/{[id]-f3da975fca51aba463a0f02017e72a65.js → [id]-822bd7753b2a6ce9eaae34189956b84d.js} +7 -7
  9. package/assets/viewer/_expo/static/js/web/{[section]-b015bac86cf9f4878c5e8039708fc7d1.js → [section]-1b5d8b74359eb108edd0901a92586041.js} +26 -26
  10. package/assets/viewer/_expo/static/js/web/{__common-5347bf558599c0f47249bb63f3bc8096.js → __common-26a6e690c38cd77825005af3ec9904c4.js} +1316 -1316
  11. package/assets/viewer/_expo/static/js/web/{_layout-fa940306541897e284d2e42a3dae7308.js → _layout-5f29482b8560e605cd84c264755889ee.js} +24 -24
  12. package/assets/viewer/_expo/static/js/web/_layout-7941849521c5563693c949ce2be84a2c.js +29 -0
  13. package/assets/viewer/_expo/static/js/web/{add-server-dc8c504e936a81d69e40f6efa6ac7b2b.js → add-server-e6cd5c48f580b43fe7f9bfa9b44b7bf6.js} +2 -2
  14. package/assets/viewer/_expo/static/js/web/{cameras-6a7062fac61db150930c4ea824098806.js → cameras-839bf8e4a9b15e2367b3d285e1e09af9.js} +27 -27
  15. package/assets/viewer/_expo/static/js/web/cameras-c1f38aa4390adb995b3f21311359b358.js +21 -0
  16. package/assets/viewer/_expo/static/js/web/{connect-a04da8316c872406a85fecfac72afb97.js → connect-b761b71002eee769adcc986f42b31c73.js} +2 -2
  17. package/assets/viewer/_expo/static/js/web/{enroll-6fe018df6035905080abf2163931500a.js → enroll-63cdefaa7736905d95828d18ca705756.js} +19 -19
  18. package/assets/viewer/_expo/static/js/web/events-4243a05bc2c5e164a505d4723673030d.js +79 -0
  19. package/assets/viewer/_expo/static/js/web/grids-c2e8e7178728973d43333f342ba15177.js +3 -0
  20. package/assets/viewer/_expo/static/js/web/history-f1194b0400e1d3e475ff2c3863cfd09e.js +3 -0
  21. package/assets/viewer/_expo/static/js/web/{index-b2db94a55da06710686c8d231c3a160f.js → index-1545a88a03f2c8ae623784bc2030a56a.js} +2 -2
  22. package/assets/viewer/_expo/static/js/web/{new-41d5293ef3668dcabd305dd0cec83c60.js → new-36acda0a3591819694bde23efa19d419.js} +2 -2
  23. package/assets/viewer/_expo/static/js/web/settings-a2c7e2a0eab3097de352e3bf17d37558.js +23 -0
  24. package/assets/viewer/_expo/static/js/web/{sign-in-ac807c2017f1f0665288ee84bfc94787.js → sign-in-d85edd56c66340fb85a5962c7460fd4e.js} +38 -38
  25. package/assets/viewer/embed/assets/{MaskShapeCanvas-DI4BY7W2-DwhST5rm.js → MaskShapeCanvas-DI4BY7W2-OFXMXri-.js} +1 -1
  26. package/assets/viewer/embed/assets/{MotionZonesSettings-CiYjd-yl-Djy2GKmM.js → MotionZonesSettings-CiYjd-yl-BirmOvge.js} +1 -1
  27. package/assets/viewer/embed/assets/{PrivacyMaskSettings-BmRdUrPp-DpHYAfGf.js → PrivacyMaskSettings-BmRdUrPp-D7nMj8O6.js} +1 -1
  28. package/assets/viewer/embed/assets/{SceneMonitorEditor-J4Ix_0tu-4MX1nGnM.js → SceneMonitorEditor-J4Ix_0tu-03IFAET6.js} +1 -1
  29. package/assets/viewer/embed/assets/{index-DNz_mNxu.js → index-CVe7tetL.js} +3 -3
  30. package/assets/viewer/embed/index.html +1 -1
  31. package/assets/viewer/index.html +1 -1
  32. package/dist/_stub.js +2 -2
  33. package/dist/{_virtual_mf-localSharedImportMap___mfe_internal__addon_pipeline_orchestrator_widgets-RuJPE6QL.mjs → _virtual_mf-localSharedImportMap___mfe_internal__addon_pipeline_orchestrator_widgets-CLnvB6ao.mjs} +2 -2
  34. package/dist/_virtual_mf___mfe_internal__addon_pipeline_orchestrator_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-aRBdTAvV.mjs +26 -0
  35. package/dist/_virtual_mf___mfe_internal__addon_pipeline_orchestrator_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.js-BgldU2G0.mjs +26 -0
  36. package/dist/{hostInit-B2CXeCkI.mjs → hostInit-B0JRyOPt.mjs} +2 -2
  37. package/dist/index.js +126 -14
  38. package/dist/index.mjs +126 -14
  39. package/dist/remoteEntry.js +1 -1
  40. package/package.json +2 -2
  41. package/assets/viewer/_expo/static/js/web/Clipboard-cba253dbeeeb383ce66f3c84fbe67025.js +0 -8
  42. package/assets/viewer/_expo/static/js/web/Haptics-4770c6d7c73d2becf4ac20cfd82301e3.js +0 -3
  43. package/assets/viewer/_expo/static/js/web/alarm-8c1402344adf58c18245c2a1da1a316b.js +0 -1
  44. package/assets/viewer/_expo/static/js/web/index-2d40982745027241350379ea664ebf48.js +0 -1
  45. package/assets/viewer/_expo/static/js/web/index-7fb91729ac1133d8e8e2873ea9046958.js +0 -2
  46. package/assets/viewer/_expo/static/js/web/index-cdd684984f16d19f8d2c87782de30fa6.js +0 -4
  47. package/dist/_virtual_mf___mfe_internal__addon_pipeline_orchestrator_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-BDfpXeSr.mjs +0 -26
  48. package/dist/_virtual_mf___mfe_internal__addon_pipeline_orchestrator_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.js-DBMfBxpT.mjs +0 -26
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./MotionZonesSettings-CiYjd-yl-Djy2GKmM.js","./MaskShapeCanvas-DI4BY7W2-DwhST5rm.js","./PrivacyMaskSettings-BmRdUrPp-DpHYAfGf.js","./SceneMonitorEditor-J4Ix_0tu-4MX1nGnM.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./MotionZonesSettings-CiYjd-yl-BirmOvge.js","./MaskShapeCanvas-DI4BY7W2-OFXMXri-.js","./PrivacyMaskSettings-BmRdUrPp-D7nMj8O6.js","./SceneMonitorEditor-J4Ix_0tu-03IFAET6.js"])))=>i.map(i=>d[i]);
2
2
  function zB(e,t){for(var a=0;a<t.length;a++){const r=t[a];if(typeof r!="string"&&!Array.isArray(r)){for(const c in r)if(c!=="default"&&!(c in e)){const m=Object.getOwnPropertyDescriptor(r,c);m&&Object.defineProperty(e,c,m.get?m:{enumerable:!0,get:()=>r[c]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const c of document.querySelectorAll('link[rel="modulepreload"]'))r(c);new MutationObserver(c=>{for(const m of c)if(m.type==="childList")for(const d of m.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&r(d)}).observe(document,{childList:!0,subtree:!0});function a(c){const m={};return c.integrity&&(m.integrity=c.integrity),c.referrerPolicy&&(m.referrerPolicy=c.referrerPolicy),c.crossOrigin==="use-credentials"?m.credentials="include":c.crossOrigin==="anonymous"?m.credentials="omit":m.credentials="same-origin",m}function r(c){if(c.ep)return;c.ep=!0;const m=a(c);fetch(c.href,m)}})();function qB(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Wy={exports:{}},Jd={};var kA;function LB(){if(kA)return Jd;kA=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function a(r,c,m){var d=null;if(m!==void 0&&(d=""+m),c.key!==void 0&&(d=""+c.key),"key"in c){m={};for(var h in c)h!=="key"&&(m[h]=c[h])}else m=c;return c=m.ref,{$$typeof:e,type:r,key:d,ref:c!==void 0?c:null,props:m}}return Jd.Fragment=t,Jd.jsx=a,Jd.jsxs=a,Jd}var SA;function BB(){return SA||(SA=1,Wy.exports=LB()),Wy.exports}var v=BB(),Zy={exports:{}},eu={},Yy={exports:{}},Xy={};var wA;function FB(){return wA||(wA=1,(function(e){function t(Y,de){var Re=Y.length;Y.push(de);e:for(;0<Re;){var Qe=Re-1>>>1,re=Y[Qe];if(0<c(re,de))Y[Qe]=de,Y[Re]=re,Re=Qe;else break e}}function a(Y){return Y.length===0?null:Y[0]}function r(Y){if(Y.length===0)return null;var de=Y[0],Re=Y.pop();if(Re!==de){Y[0]=Re;e:for(var Qe=0,re=Y.length,V=re>>>1;Qe<V;){var ie=2*(Qe+1)-1,fe=Y[ie],be=ie+1,ee=Y[be];if(0>c(fe,Re))be<re&&0>c(ee,fe)?(Y[Qe]=ee,Y[be]=Re,Qe=be):(Y[Qe]=fe,Y[ie]=Re,Qe=ie);else if(be<re&&0>c(ee,Re))Y[Qe]=ee,Y[be]=Re,Qe=be;else break e}}return de}function c(Y,de){var Re=Y.sortIndex-de.sortIndex;return Re!==0?Re:Y.id-de.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var m=performance;e.unstable_now=function(){return m.now()}}else{var d=Date,h=d.now();e.unstable_now=function(){return d.now()-h}}var f=[],k=[],x=1,E=null,R=3,T=!1,N=!1,j=!1,q=!1,B=typeof setTimeout=="function"?setTimeout:null,F=typeof clearTimeout=="function"?clearTimeout:null,U=typeof setImmediate<"u"?setImmediate:null;function H(Y){for(var de=a(k);de!==null;){if(de.callback===null)r(k);else if(de.startTime<=Y)r(k),de.sortIndex=de.expirationTime,t(f,de);else break;de=a(k)}}function Q(Y){if(j=!1,H(Y),!N)if(a(f)!==null)N=!0,te||(te=!0,we());else{var de=a(k);de!==null&&Me(Q,de.startTime-Y)}}var te=!1,K=-1,W=5,oe=-1;function he(){return q?!0:!(e.unstable_now()-oe<W)}function Ae(){if(q=!1,te){var Y=e.unstable_now();oe=Y;var de=!0;try{e:{N=!1,j&&(j=!1,F(K),K=-1),T=!0;var Re=R;try{t:{for(H(Y),E=a(f);E!==null&&!(E.expirationTime>Y&&he());){var Qe=E.callback;if(typeof Qe=="function"){E.callback=null,R=E.priorityLevel;var re=Qe(E.expirationTime<=Y);if(Y=e.unstable_now(),typeof re=="function"){E.callback=re,H(Y),de=!0;break t}E===a(f)&&r(f),H(Y)}else r(f);E=a(f)}if(E!==null)de=!0;else{var V=a(k);V!==null&&Me(Q,V.startTime-Y),de=!1}}break e}finally{E=null,R=Re,T=!1}de=void 0}}finally{de?we():te=!1}}}var we;if(typeof U=="function")we=function(){U(Ae)};else if(typeof MessageChannel<"u"){var Ee=new MessageChannel,Ie=Ee.port2;Ee.port1.onmessage=Ae,we=function(){Ie.postMessage(null)}}else we=function(){B(Ae,0)};function Me(Y,de){K=B(function(){Y(e.unstable_now())},de)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(Y){Y.callback=null},e.unstable_forceFrameRate=function(Y){0>Y||125<Y?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):W=0<Y?Math.floor(1e3/Y):5},e.unstable_getCurrentPriorityLevel=function(){return R},e.unstable_next=function(Y){switch(R){case 1:case 2:case 3:var de=3;break;default:de=R}var Re=R;R=de;try{return Y()}finally{R=Re}},e.unstable_requestPaint=function(){q=!0},e.unstable_runWithPriority=function(Y,de){switch(Y){case 1:case 2:case 3:case 4:case 5:break;default:Y=3}var Re=R;R=Y;try{return de()}finally{R=Re}},e.unstable_scheduleCallback=function(Y,de,Re){var Qe=e.unstable_now();switch(typeof Re=="object"&&Re!==null?(Re=Re.delay,Re=typeof Re=="number"&&0<Re?Qe+Re:Qe):Re=Qe,Y){case 1:var re=-1;break;case 2:re=250;break;case 5:re=1073741823;break;case 4:re=1e4;break;default:re=5e3}return re=Re+re,Y={id:x++,callback:de,priorityLevel:Y,startTime:Re,expirationTime:re,sortIndex:-1},Re>Qe?(Y.sortIndex=Re,t(k,Y),a(f)===null&&Y===a(k)&&(j?(F(K),K=-1):j=!0,Me(Q,Re-Qe))):(Y.sortIndex=re,t(f,Y),N||T||(N=!0,te||(te=!0,we()))),Y},e.unstable_shouldYield=he,e.unstable_wrapCallback=function(Y){var de=R;return function(){var Re=R;R=de;try{return Y.apply(this,arguments)}finally{R=Re}}}})(Xy)),Xy}var xA;function $B(){return xA||(xA=1,Yy.exports=FB()),Yy.exports}var Jy={exports:{}},vt={};var MA;function UB(){if(MA)return vt;MA=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),a=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),c=Symbol.for("react.profiler"),m=Symbol.for("react.consumer"),d=Symbol.for("react.context"),h=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),k=Symbol.for("react.memo"),x=Symbol.for("react.lazy"),E=Symbol.for("react.activity"),R=Symbol.iterator;function T(V){return V===null||typeof V!="object"?null:(V=R&&V[R]||V["@@iterator"],typeof V=="function"?V:null)}var N={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},j=Object.assign,q={};function B(V,ie,fe){this.props=V,this.context=ie,this.refs=q,this.updater=fe||N}B.prototype.isReactComponent={},B.prototype.setState=function(V,ie){if(typeof V!="object"&&typeof V!="function"&&V!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,V,ie,"setState")},B.prototype.forceUpdate=function(V){this.updater.enqueueForceUpdate(this,V,"forceUpdate")};function F(){}F.prototype=B.prototype;function U(V,ie,fe){this.props=V,this.context=ie,this.refs=q,this.updater=fe||N}var H=U.prototype=new F;H.constructor=U,j(H,B.prototype),H.isPureReactComponent=!0;var Q=Array.isArray;function te(){}var K={H:null,A:null,T:null,S:null},W=Object.prototype.hasOwnProperty;function oe(V,ie,fe){var be=fe.ref;return{$$typeof:e,type:V,key:ie,ref:be!==void 0?be:null,props:fe}}function he(V,ie){return oe(V.type,ie,V.props)}function Ae(V){return typeof V=="object"&&V!==null&&V.$$typeof===e}function we(V){var ie={"=":"=0",":":"=2"};return"$"+V.replace(/[=:]/g,function(fe){return ie[fe]})}var Ee=/\/+/g;function Ie(V,ie){return typeof V=="object"&&V!==null&&V.key!=null?we(""+V.key):ie.toString(36)}function Me(V){switch(V.status){case"fulfilled":return V.value;case"rejected":throw V.reason;default:switch(typeof V.status=="string"?V.then(te,te):(V.status="pending",V.then(function(ie){V.status==="pending"&&(V.status="fulfilled",V.value=ie)},function(ie){V.status==="pending"&&(V.status="rejected",V.reason=ie)})),V.status){case"fulfilled":return V.value;case"rejected":throw V.reason}}throw V}function Y(V,ie,fe,be,ee){var Se=typeof V;(Se==="undefined"||Se==="boolean")&&(V=null);var _e=!1;if(V===null)_e=!0;else switch(Se){case"bigint":case"string":case"number":_e=!0;break;case"object":switch(V.$$typeof){case e:case t:_e=!0;break;case x:return _e=V._init,Y(_e(V._payload),ie,fe,be,ee)}}if(_e)return ee=ee(V),_e=be===""?"."+Ie(V,0):be,Q(ee)?(fe="",_e!=null&&(fe=_e.replace(Ee,"$&/")+"/"),Y(ee,ie,fe,"",function(Ft){return Ft})):ee!=null&&(Ae(ee)&&(ee=he(ee,fe+(ee.key==null||V&&V.key===ee.key?"":(""+ee.key).replace(Ee,"$&/")+"/")+_e)),ie.push(ee)),1;_e=0;var Be=be===""?".":be+":";if(Q(V))for(var Ge=0;Ge<V.length;Ge++)be=V[Ge],Se=Be+Ie(be,Ge),_e+=Y(be,ie,fe,Se,ee);else if(Ge=T(V),typeof Ge=="function")for(V=Ge.call(V),Ge=0;!(be=V.next()).done;)be=be.value,Se=Be+Ie(be,Ge++),_e+=Y(be,ie,fe,Se,ee);else if(Se==="object"){if(typeof V.then=="function")return Y(Me(V),ie,fe,be,ee);throw ie=String(V),Error("Objects are not valid as a React child (found: "+(ie==="[object Object]"?"object with keys {"+Object.keys(V).join(", ")+"}":ie)+"). If you meant to render a collection of children, use an array instead.")}return _e}function de(V,ie,fe){if(V==null)return V;var be=[],ee=0;return Y(V,be,"","",function(Se){return ie.call(fe,Se,ee++)}),be}function Re(V){if(V._status===-1){var ie=V._result;ie=ie(),ie.then(function(fe){(V._status===0||V._status===-1)&&(V._status=1,V._result=fe)},function(fe){(V._status===0||V._status===-1)&&(V._status=2,V._result=fe)}),V._status===-1&&(V._status=0,V._result=ie)}if(V._status===1)return V._result.default;throw V._result}var Qe=typeof reportError=="function"?reportError:function(V){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var ie=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof V=="object"&&V!==null&&typeof V.message=="string"?String(V.message):String(V),error:V});if(!window.dispatchEvent(ie))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",V);return}console.error(V)},re={map:de,forEach:function(V,ie,fe){de(V,function(){ie.apply(this,arguments)},fe)},count:function(V){var ie=0;return de(V,function(){ie++}),ie},toArray:function(V){return de(V,function(ie){return ie})||[]},only:function(V){if(!Ae(V))throw Error("React.Children.only expected to receive a single React element child.");return V}};return vt.Activity=E,vt.Children=re,vt.Component=B,vt.Fragment=a,vt.Profiler=c,vt.PureComponent=U,vt.StrictMode=r,vt.Suspense=f,vt.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=K,vt.__COMPILER_RUNTIME={__proto__:null,c:function(V){return K.H.useMemoCache(V)}},vt.cache=function(V){return function(){return V.apply(null,arguments)}},vt.cacheSignal=function(){return null},vt.cloneElement=function(V,ie,fe){if(V==null)throw Error("The argument must be a React element, but you passed "+V+".");var be=j({},V.props),ee=V.key;if(ie!=null)for(Se in ie.key!==void 0&&(ee=""+ie.key),ie)!W.call(ie,Se)||Se==="key"||Se==="__self"||Se==="__source"||Se==="ref"&&ie.ref===void 0||(be[Se]=ie[Se]);var Se=arguments.length-2;if(Se===1)be.children=fe;else if(1<Se){for(var _e=Array(Se),Be=0;Be<Se;Be++)_e[Be]=arguments[Be+2];be.children=_e}return oe(V.type,ee,be)},vt.createContext=function(V){return V={$$typeof:d,_currentValue:V,_currentValue2:V,_threadCount:0,Provider:null,Consumer:null},V.Provider=V,V.Consumer={$$typeof:m,_context:V},V},vt.createElement=function(V,ie,fe){var be,ee={},Se=null;if(ie!=null)for(be in ie.key!==void 0&&(Se=""+ie.key),ie)W.call(ie,be)&&be!=="key"&&be!=="__self"&&be!=="__source"&&(ee[be]=ie[be]);var _e=arguments.length-2;if(_e===1)ee.children=fe;else if(1<_e){for(var Be=Array(_e),Ge=0;Ge<_e;Ge++)Be[Ge]=arguments[Ge+2];ee.children=Be}if(V&&V.defaultProps)for(be in _e=V.defaultProps,_e)ee[be]===void 0&&(ee[be]=_e[be]);return oe(V,Se,ee)},vt.createRef=function(){return{current:null}},vt.forwardRef=function(V){return{$$typeof:h,render:V}},vt.isValidElement=Ae,vt.lazy=function(V){return{$$typeof:x,_payload:{_status:-1,_result:V},_init:Re}},vt.memo=function(V,ie){return{$$typeof:k,type:V,compare:ie===void 0?null:ie}},vt.startTransition=function(V){var ie=K.T,fe={};K.T=fe;try{var be=V(),ee=K.S;ee!==null&&ee(fe,be),typeof be=="object"&&be!==null&&typeof be.then=="function"&&be.then(te,Qe)}catch(Se){Qe(Se)}finally{ie!==null&&fe.types!==null&&(ie.types=fe.types),K.T=ie}},vt.unstable_useCacheRefresh=function(){return K.H.useCacheRefresh()},vt.use=function(V){return K.H.use(V)},vt.useActionState=function(V,ie,fe){return K.H.useActionState(V,ie,fe)},vt.useCallback=function(V,ie){return K.H.useCallback(V,ie)},vt.useContext=function(V){return K.H.useContext(V)},vt.useDebugValue=function(){},vt.useDeferredValue=function(V,ie){return K.H.useDeferredValue(V,ie)},vt.useEffect=function(V,ie){return K.H.useEffect(V,ie)},vt.useEffectEvent=function(V){return K.H.useEffectEvent(V)},vt.useId=function(){return K.H.useId()},vt.useImperativeHandle=function(V,ie,fe){return K.H.useImperativeHandle(V,ie,fe)},vt.useInsertionEffect=function(V,ie){return K.H.useInsertionEffect(V,ie)},vt.useLayoutEffect=function(V,ie){return K.H.useLayoutEffect(V,ie)},vt.useMemo=function(V,ie){return K.H.useMemo(V,ie)},vt.useOptimistic=function(V,ie){return K.H.useOptimistic(V,ie)},vt.useReducer=function(V,ie,fe){return K.H.useReducer(V,ie,fe)},vt.useRef=function(V){return K.H.useRef(V)},vt.useState=function(V){return K.H.useState(V)},vt.useSyncExternalStore=function(V,ie,fe){return K.H.useSyncExternalStore(V,ie,fe)},vt.useTransition=function(){return K.H.useTransition()},vt.version="19.2.3",vt}var CA;function kw(){return CA||(CA=1,Jy.exports=UB()),Jy.exports}var eb={exports:{}},kn={};var AA;function HB(){if(AA)return kn;AA=1;var e=kw();function t(f){var k="https://react.dev/errors/"+f;if(1<arguments.length){k+="?args[]="+encodeURIComponent(arguments[1]);for(var x=2;x<arguments.length;x++)k+="&args[]="+encodeURIComponent(arguments[x])}return"Minified React error #"+f+"; visit "+k+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function a(){}var r={d:{f:a,r:function(){throw Error(t(522))},D:a,C:a,L:a,m:a,X:a,S:a,M:a},p:0,findDOMNode:null},c=Symbol.for("react.portal");function m(f,k,x){var E=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:c,key:E==null?null:""+E,children:f,containerInfo:k,implementation:x}}var d=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function h(f,k){if(f==="font")return"";if(typeof k=="string")return k==="use-credentials"?k:""}return kn.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,kn.createPortal=function(f,k){var x=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!k||k.nodeType!==1&&k.nodeType!==9&&k.nodeType!==11)throw Error(t(299));return m(f,k,null,x)},kn.flushSync=function(f){var k=d.T,x=r.p;try{if(d.T=null,r.p=2,f)return f()}finally{d.T=k,r.p=x,r.d.f()}},kn.preconnect=function(f,k){typeof f=="string"&&(k?(k=k.crossOrigin,k=typeof k=="string"?k==="use-credentials"?k:"":void 0):k=null,r.d.C(f,k))},kn.prefetchDNS=function(f){typeof f=="string"&&r.d.D(f)},kn.preinit=function(f,k){if(typeof f=="string"&&k&&typeof k.as=="string"){var x=k.as,E=h(x,k.crossOrigin),R=typeof k.integrity=="string"?k.integrity:void 0,T=typeof k.fetchPriority=="string"?k.fetchPriority:void 0;x==="style"?r.d.S(f,typeof k.precedence=="string"?k.precedence:void 0,{crossOrigin:E,integrity:R,fetchPriority:T}):x==="script"&&r.d.X(f,{crossOrigin:E,integrity:R,fetchPriority:T,nonce:typeof k.nonce=="string"?k.nonce:void 0})}},kn.preinitModule=function(f,k){if(typeof f=="string")if(typeof k=="object"&&k!==null){if(k.as==null||k.as==="script"){var x=h(k.as,k.crossOrigin);r.d.M(f,{crossOrigin:x,integrity:typeof k.integrity=="string"?k.integrity:void 0,nonce:typeof k.nonce=="string"?k.nonce:void 0})}}else k==null&&r.d.M(f)},kn.preload=function(f,k){if(typeof f=="string"&&typeof k=="object"&&k!==null&&typeof k.as=="string"){var x=k.as,E=h(x,k.crossOrigin);r.d.L(f,x,{crossOrigin:E,integrity:typeof k.integrity=="string"?k.integrity:void 0,nonce:typeof k.nonce=="string"?k.nonce:void 0,type:typeof k.type=="string"?k.type:void 0,fetchPriority:typeof k.fetchPriority=="string"?k.fetchPriority:void 0,referrerPolicy:typeof k.referrerPolicy=="string"?k.referrerPolicy:void 0,imageSrcSet:typeof k.imageSrcSet=="string"?k.imageSrcSet:void 0,imageSizes:typeof k.imageSizes=="string"?k.imageSizes:void 0,media:typeof k.media=="string"?k.media:void 0})}},kn.preloadModule=function(f,k){if(typeof f=="string")if(k){var x=h(k.as,k.crossOrigin);r.d.m(f,{as:typeof k.as=="string"&&k.as!=="script"?k.as:void 0,crossOrigin:x,integrity:typeof k.integrity=="string"?k.integrity:void 0})}else r.d.m(f)},kn.requestFormReset=function(f){r.d.r(f)},kn.unstable_batchedUpdates=function(f,k){return f(k)},kn.useFormState=function(f,k,x){return d.H.useFormState(f,k,x)},kn.useFormStatus=function(){return d.H.useHostTransitionStatus()},kn.version="19.2.3",kn}var IA;function C_(){if(IA)return eb.exports;IA=1;function e(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),eb.exports=HB(),eb.exports}var EA;function QB(){if(EA)return eu;EA=1;var e=$B(),t=kw(),a=C_();function r(s){var l="https://react.dev/errors/"+s;if(1<arguments.length){l+="?args[]="+encodeURIComponent(arguments[1]);for(var p=2;p<arguments.length;p++)l+="&args[]="+encodeURIComponent(arguments[p])}return"Minified React error #"+s+"; visit "+l+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function c(s){return!(!s||s.nodeType!==1&&s.nodeType!==9&&s.nodeType!==11)}function m(s){var l=s,p=s;if(s.alternate)for(;l.return;)l=l.return;else{s=l;do l=s,(l.flags&4098)!==0&&(p=l.return),s=l.return;while(s)}return l.tag===3?p:null}function d(s){if(s.tag===13){var l=s.memoizedState;if(l===null&&(s=s.alternate,s!==null&&(l=s.memoizedState)),l!==null)return l.dehydrated}return null}function h(s){if(s.tag===31){var l=s.memoizedState;if(l===null&&(s=s.alternate,s!==null&&(l=s.memoizedState)),l!==null)return l.dehydrated}return null}function f(s){if(m(s)!==s)throw Error(r(188))}function k(s){var l=s.alternate;if(!l){if(l=m(s),l===null)throw Error(r(188));return l!==s?null:s}for(var p=s,g=l;;){var M=p.return;if(M===null)break;var A=M.alternate;if(A===null){if(g=M.return,g!==null){p=g;continue}break}if(M.child===A.child){for(A=M.child;A;){if(A===p)return f(M),s;if(A===g)return f(M),l;A=A.sibling}throw Error(r(188))}if(p.return!==g.return)p=M,g=A;else{for(var D=!1,L=M.child;L;){if(L===p){D=!0,p=M,g=A;break}if(L===g){D=!0,g=M,p=A;break}L=L.sibling}if(!D){for(L=A.child;L;){if(L===p){D=!0,p=A,g=M;break}if(L===g){D=!0,g=A,p=M;break}L=L.sibling}if(!D)throw Error(r(189))}}if(p.alternate!==g)throw Error(r(190))}if(p.tag!==3)throw Error(r(188));return p.stateNode.current===p?s:l}function x(s){var l=s.tag;if(l===5||l===26||l===27||l===6)return s;for(s=s.child;s!==null;){if(l=x(s),l!==null)return l;s=s.sibling}return null}var E=Object.assign,R=Symbol.for("react.element"),T=Symbol.for("react.transitional.element"),N=Symbol.for("react.portal"),j=Symbol.for("react.fragment"),q=Symbol.for("react.strict_mode"),B=Symbol.for("react.profiler"),F=Symbol.for("react.consumer"),U=Symbol.for("react.context"),H=Symbol.for("react.forward_ref"),Q=Symbol.for("react.suspense"),te=Symbol.for("react.suspense_list"),K=Symbol.for("react.memo"),W=Symbol.for("react.lazy"),oe=Symbol.for("react.activity"),he=Symbol.for("react.memo_cache_sentinel"),Ae=Symbol.iterator;function we(s){return s===null||typeof s!="object"?null:(s=Ae&&s[Ae]||s["@@iterator"],typeof s=="function"?s:null)}var Ee=Symbol.for("react.client.reference");function Ie(s){if(s==null)return null;if(typeof s=="function")return s.$$typeof===Ee?null:s.displayName||s.name||null;if(typeof s=="string")return s;switch(s){case j:return"Fragment";case B:return"Profiler";case q:return"StrictMode";case Q:return"Suspense";case te:return"SuspenseList";case oe:return"Activity"}if(typeof s=="object")switch(s.$$typeof){case N:return"Portal";case U:return s.displayName||"Context";case F:return(s._context.displayName||"Context")+".Consumer";case H:var l=s.render;return s=s.displayName,s||(s=l.displayName||l.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case K:return l=s.displayName||null,l!==null?l:Ie(s.type)||"Memo";case W:l=s._payload,s=s._init;try{return Ie(s(l))}catch{}}return null}var Me=Array.isArray,Y=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,de=a.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Re={pending:!1,data:null,method:null,action:null},Qe=[],re=-1;function V(s){return{current:s}}function ie(s){0>re||(s.current=Qe[re],Qe[re]=null,re--)}function fe(s,l){re++,Qe[re]=s.current,s.current=l}var be=V(null),ee=V(null),Se=V(null),_e=V(null);function Be(s,l){switch(fe(Se,l),fe(ee,s),fe(be,null),l.nodeType){case 9:case 11:s=(s=l.documentElement)&&(s=s.namespaceURI)?UC(s):0;break;default:if(s=l.tagName,l=l.namespaceURI)l=UC(l),s=HC(l,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}ie(be),fe(be,s)}function Ge(){ie(be),ie(ee),ie(Se)}function Ft(s){s.memoizedState!==null&&fe(_e,s);var l=be.current,p=HC(l,s.type);l!==p&&(fe(ee,s),fe(be,p))}function Ot(s){ee.current===s&&(ie(be),ie(ee)),_e.current===s&&(ie(_e),Wd._currentValue=Re)}var wt,sa;function nt(s){if(wt===void 0)try{throw Error()}catch(p){var l=p.stack.trim().match(/\n( *(at )?)/);wt=l&&l[1]||"",sa=-1<p.stack.indexOf(`
3
3
  at`)?" (<anonymous>)":-1<p.stack.indexOf("@")?"@unknown:0:0":""}return`
4
4
  `+wt+s+sa}var za=!1;function ft(s,l){if(!s||za)return"";za=!0;var p=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var g={DetermineComponentFrameRoot:function(){try{if(l){var Te=function(){throw Error()};if(Object.defineProperty(Te.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Te,[])}catch(ge){var ce=ge}Reflect.construct(s,[],Te)}else{try{Te.call()}catch(ge){ce=ge}s.call(Te.prototype)}}else{try{throw Error()}catch(ge){ce=ge}(Te=s())&&typeof Te.catch=="function"&&Te.catch(function(){})}}catch(ge){if(ge&&ce&&typeof ge.stack=="string")return[ge.stack,ce.stack]}return[null,null]}};g.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var M=Object.getOwnPropertyDescriptor(g.DetermineComponentFrameRoot,"name");M&&M.configurable&&Object.defineProperty(g.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var A=g.DetermineComponentFrameRoot(),D=A[0],L=A[1];if(D&&L){var G=D.split(`
@@ -80,7 +80,7 @@ ${a.slice(0,5).join(`
80
80
  })`,{filename:N,importModuleDynamically:E.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER??bc});let q;q=(await bc("node:module")).createRequire(f.protocol==="file:"||f.protocol==="node:"?f.href:x.join(process.cwd(),"__mf_require_base__.js")),j.runInThisContext()(R.exports,R.module,q,T,N);const B=R.module.exports||R.exports;if(a&&B&&a.globalName){t(void 0,B[a.globalName]||B);return}t(void 0,B)}catch(k){t(k instanceof Error?k:new Error(`Script execution error: ${k}`))}};m().then(async h=>{if(a?.type==="esm"||a?.type==="module")return FS(c.href,{fetch:h,vm:await bc("vm")}).then(async f=>{await f.evaluate(),t(void 0,f.namespace)}).catch(f=>{t(f instanceof Error?f:new Error(`Script execution error: ${f}`))});d(h,c)}).catch(h=>{t(h)})}:(e,t,a,r)=>{t(new Error("createScriptNode is disabled in non-Node.js environment"))},vRe=typeof ENV_TARGET>"u"||ENV_TARGET!=="web"?(e,t)=>new Promise((a,r)=>{gRe(e,(c,m)=>{if(c)r(c);else{const d=t?.attrs?.globalName||`__FEDERATION_${t?.attrs?.name}:custom__`;a(globalThis[d]=m)}},t.attrs,t.loaderHook)}):(e,t)=>{throw new Error("loadScriptNode is disabled in non-Node.js environment")},k1=new Map;async function FS(e,t){if(k1.has(e))return k1.get(e);const{fetch:a,vm:r}=t,c=await(await a(e)).text(),m=new r.SourceTextModule(c,{importModuleDynamically:async(d,h)=>{const f=new URL(d,e).href;return FS(f,t)}});return k1.set(e,m),await m.link(async d=>{const h=new URL(d,e).href;return await FS(h,t)}),m}var yRe=e=>`View the docs to see how to solve: https://module-federation.io/guide/troubleshooting/${e.split("-")[0].toLowerCase()}#${e.toLowerCase()}`,E6=(e,t,a,r)=>{const c=[`${[t[e]]} #${e}`];return a&&c.push(`args: ${JSON.stringify(a)}`),c.push(yRe(e)),r&&c.push(`Original Error Message:
81
81
  ${r}`),c.join(`
82
82
  `)};function bRe(e,t,a,r,c,m){return r(E6(e,t,a,c))}var el="[ Federation Runtime ]",$S=uRe(el);function lo(e,t,a,r,c){e||ka(t)}function ka(e,t,a,r,c){if(t!==void 0)return bRe(e,t,a??{},d=>{throw new Error(`${el}: ${d}`)},r);const m=e;throw m instanceof Error?(m.message.startsWith(el)||(m.message=`${el}: ${m.message}`),m):new Error(`${el}: ${m}`)}function cm(e){e instanceof Error&&(e.message.startsWith(el)||(e.message=`${el}: ${e.message}`)),$S.warn(e)}function kRe(e,t){return e.findIndex(a=>a===t)===-1&&e.push(t),e}function Zf(e){return"version"in e&&e.version?`${e.name}:${e.version}`:"entry"in e&&e.entry?`${e.name}:${e.entry}`:`${e.name}`}function fx(e){return typeof e.entry<"u"}function R6(e){return!e.entry.includes(".json")}function gx(e){return e&&typeof e=="object"}var SRe=Object.prototype.toString;function wRe(e){return SRe.call(e)==="[object Object]"}function T6(e){return Array.isArray(e)?e:[e]}function _6(e){const t={url:"",type:"global",globalName:""};return ks||b6()||!("ssrRemoteEntry"in e)?"remoteEntry"in e?{url:e.remoteEntry,type:e.remoteEntryType,globalName:e.globalName}:t:"ssrRemoteEntry"in e?{url:e.ssrRemoteEntry||t.url,type:e.ssrRemoteEntryType||t.type,globalName:e.globalName}:t}var xRe=(e,t)=>{let a;return e.endsWith("/")?a=e.slice(0,-1):a=e,t.startsWith(".")&&(t=t.slice(1)),a=a+t,a},hn=typeof globalThis=="object"?globalThis:window,er=(()=>{try{return document.defaultView}catch{return hn}})(),dm=er;function cf(e,t,a){Object.defineProperty(e,t,{value:a,configurable:!1,writable:!0})}function df(e,t){return Object.hasOwnProperty.call(e,t)}df(hn,"__GLOBAL_LOADING_REMOTE_ENTRY__")||cf(hn,"__GLOBAL_LOADING_REMOTE_ENTRY__",{});var Ic=hn.__GLOBAL_LOADING_REMOTE_ENTRY__;function P6(e){df(e,"__VMOK__")&&!df(e,"__FEDERATION__")&&cf(e,"__FEDERATION__",e.__VMOK__),df(e,"__FEDERATION__")||(cf(e,"__FEDERATION__",{__GLOBAL_PLUGIN__:[],__INSTANCES__:[],moduleInfo:{},__SHARE__:{},__MANIFEST_LOADING__:{},__PRELOADED_MAP__:new Map}),cf(e,"__VMOK__",e.__FEDERATION__)),e.__FEDERATION__.__GLOBAL_PLUGIN__??=[],e.__FEDERATION__.__INSTANCES__??=[],e.__FEDERATION__.moduleInfo??={},e.__FEDERATION__.__SHARE__??={},e.__FEDERATION__.__MANIFEST_LOADING__??={},e.__FEDERATION__.__PRELOADED_MAP__??=new Map}P6(hn);P6(er);function MRe(e,t=qS()){t&&(hn.__FEDERATION__.__DEBUG_CONSTRUCTOR__=e,hn.__FEDERATION__.__DEBUG_CONSTRUCTOR_VERSION__="2.5.1")}function Xc(e,t){if(typeof t=="string"){if(e[t])return{value:e[t],key:t};{const a=Object.keys(e);for(const r of a){const[c,m]=r.split(":"),d=`${c}:${t}`,h=e[d];if(h)return{value:h,key:d}}return{value:void 0,key:t}}}else ka(`getInfoWithoutType: "key" must be a string, got ${typeof t} (${JSON.stringify(t)}).`)}var h4=()=>er.__FEDERATION__.moduleInfo,CRe=(e,t)=>{const a=Xc(t,Zf(e)).value;if(a&&!a.version&&"version"in e&&e.version&&(a.version=e.version),a)return a;if("version"in e&&e.version){const{version:r,...c}=e,m=Zf(c),d=Xc(er.__FEDERATION__.moduleInfo,m).value;if(d?.version===r)return d}},uf=e=>CRe(e,er.__FEDERATION__.moduleInfo),f4=(e,t)=>{const a=Zf(e);return er.__FEDERATION__.moduleInfo[a]=t,er.__FEDERATION__.moduleInfo},ARe=e=>(er.__FEDERATION__.moduleInfo={...er.__FEDERATION__.moduleInfo,...e},()=>{const t=Object.keys(e);for(const a of t)delete er.__FEDERATION__.moduleInfo[a]}),vx=(e,t)=>{const a=t||`__FEDERATION_${e}:custom__`;return{remoteEntryKey:a,entryExports:hn[a]}},IRe=()=>er.__FEDERATION__.__GLOBAL_PLUGIN__,ERe=e=>hn.__FEDERATION__.__PRELOADED_MAP__.get(e),RRe=e=>hn.__FEDERATION__.__PRELOADED_MAP__.set(e,!0),g4="[0-9A-Za-z-]+",yx=`(?:\\+(${g4}(?:\\.${g4})*))`,Bu="0|[1-9]\\d*",mf="[0-9]+",N6="\\d*[a-zA-Z-][a-zA-Z0-9-]*",v4=`(?:${mf}|${N6})`,TRe=`(?:-?(${v4}(?:\\.${v4})*))`,y4=`(?:${Bu}|${N6})`,O6=`(?:-(${y4}(?:\\.${y4})*))`,S1=`${Bu}|x|X|\\*`,Jc=`[v=\\s]*(${S1})(?:\\.(${S1})(?:\\.(${S1})(?:${O6})?${yx}?)?)?`,_Re=`^\\s*(${Jc})\\s+-\\s+(${Jc})\\s*$`,PRe=`[v=\\s]*${`(${mf})\\.(${mf})\\.(${mf})`}${TRe}?${yx}?`,bx="((?:<|>)?=?)",NRe=`(\\s*)${bx}\\s*(${PRe}|${Jc})`,D6="(?:~>?)",ORe=`(\\s*)${D6}\\s+`,j6="(?:\\^)",DRe=`(\\s*)${j6}\\s+`,jRe="(<|>)?=?\\s*\\*",zRe=`^${j6}${Jc}$`,qRe=`v?${`(${Bu})\\.(${Bu})\\.(${Bu})`}${O6}?${yx}?`,LRe=`^${D6}${Jc}$`,BRe=`^${bx}\\s*${Jc}$`,FRe=`^${bx}\\s*(${qRe})$|^$`,$Re="^\\s*>=\\s*0.0.0\\s*$";function xr(e){return new RegExp(e)}function Tn(e){return!e||e.toLowerCase()==="x"||e==="*"}function z6(...e){return t=>e.reduce((a,r)=>r(a),t)}function b4(e){return e.match(xr(FRe))}function k4(e,t,a,r){const c=`${e}.${t}.${a}`;return r?`${c}-${r}`:c}function URe(e){return e.replace(xr(_Re),(t,a,r,c,m,d,h,f,k,x,E,R)=>(Tn(r)?a="":Tn(c)?a=`>=${r}.0.0`:Tn(m)?a=`>=${r}.${c}.0`:a=`>=${a}`,Tn(k)?f="":Tn(x)?f=`<${Number(k)+1}.0.0-0`:Tn(E)?f=`<${k}.${Number(x)+1}.0-0`:R?f=`<=${k}.${x}.${E}-${R}`:f=`<=${f}`,`${a} ${f}`.trim()))}function HRe(e){return e.replace(xr(NRe),"$1$2$3")}function QRe(e){return e.replace(xr(ORe),"$1~")}function VRe(e){return e.replace(xr(DRe),"$1^")}function KRe(e){return e.trim().split(/\s+/).map(t=>t.replace(xr(zRe),(a,r,c,m,d)=>Tn(r)?"":Tn(c)?`>=${r}.0.0 <${Number(r)+1}.0.0-0`:Tn(m)?r==="0"?`>=${r}.${c}.0 <${r}.${Number(c)+1}.0-0`:`>=${r}.${c}.0 <${Number(r)+1}.0.0-0`:d?r==="0"?c==="0"?`>=${r}.${c}.${m}-${d} <${r}.${c}.${Number(m)+1}-0`:`>=${r}.${c}.${m}-${d} <${r}.${Number(c)+1}.0-0`:`>=${r}.${c}.${m}-${d} <${Number(r)+1}.0.0-0`:r==="0"?c==="0"?`>=${r}.${c}.${m} <${r}.${c}.${Number(m)+1}-0`:`>=${r}.${c}.${m} <${r}.${Number(c)+1}.0-0`:`>=${r}.${c}.${m} <${Number(r)+1}.0.0-0`)).join(" ")}function GRe(e){return e.trim().split(/\s+/).map(t=>t.replace(xr(LRe),(a,r,c,m,d)=>Tn(r)?"":Tn(c)?`>=${r}.0.0 <${Number(r)+1}.0.0-0`:Tn(m)?`>=${r}.${c}.0 <${r}.${Number(c)+1}.0-0`:d?`>=${r}.${c}.${m}-${d} <${r}.${Number(c)+1}.0-0`:`>=${r}.${c}.${m} <${r}.${Number(c)+1}.0-0`)).join(" ")}function WRe(e){return e.split(/\s+/).map(t=>t.trim().replace(xr(BRe),(a,r,c,m,d,h)=>{const f=Tn(c),k=f||Tn(m),x=k||Tn(d);return r==="="&&x&&(r=""),h="",f?r===">"||r==="<"?"<0.0.0-0":"*":r&&x?(k&&(m=0),d=0,r===">"?(r=">=",k?(c=Number(c)+1,m=0,d=0):(m=Number(m)+1,d=0)):r==="<="&&(r="<",k?c=Number(c)+1:m=Number(m)+1),r==="<"&&(h="-0"),`${r+c}.${m}.${d}${h}`):k?`>=${c}.0.0${h} <${Number(c)+1}.0.0-0`:x?`>=${c}.${m}.0${h} <${c}.${Number(m)+1}.0-0`:a})).join(" ")}function ZRe(e){return e.trim().replace(xr(jRe),"")}function YRe(e){return e.trim().replace(xr($Re),"")}function pf(e,t){return e=Number(e)||e,t=Number(t)||t,e>t?1:e===t?0:-1}function XRe(e,t){const{preRelease:a}=e,{preRelease:r}=t;if(a===void 0&&r)return 1;if(a&&r===void 0)return-1;if(a===void 0&&r===void 0)return 0;for(let c=0,m=a.length;c<=m;c++){const d=a[c],h=r[c];if(d!==h)return d===void 0&&h===void 0?0:d?h?pf(d,h):-1:1}return 0}function Oh(e,t){return pf(e.major,t.major)||pf(e.minor,t.minor)||pf(e.patch,t.patch)||XRe(e,t)}function w1(e,t){return e.version===t.version}function JRe(e,t){switch(e.operator){case"":case"=":return w1(e,t);case">":return Oh(e,t)<0;case">=":return w1(e,t)||Oh(e,t)<0;case"<":return Oh(e,t)>0;case"<=":return w1(e,t)||Oh(e,t)>0;case void 0:return!0;default:return!1}}function e4e(e){return z6(KRe,GRe,WRe,ZRe)(e)}function t4e(e){return z6(URe,HRe,QRe,VRe)(e.trim()).split(/\s+/).join(" ")}function Ru(e,t){if(!e)return!1;const a=b4(e);if(!a)return!1;const[,r,,c,m,d,h]=a,f={operator:r,version:k4(c,m,d,h),major:c,minor:m,patch:d,preRelease:h?.split(".")},k=t.split("||");for(const x of k){const E=x.trim();if(!E||E==="*"||E==="x")return!0;try{const R=t4e(E);if(!R.trim())return!0;const T=R.split(" ").map(q=>e4e(q)).join(" ");if(!T.trim())return!0;const N=T.split(/\s+/).map(q=>YRe(q)).filter(Boolean);if(N.length===0)continue;let j=!0;for(const q of N){const B=b4(q);if(!B){j=!1;break}const[,F,,U,H,Q,te]=B;if(!JRe({operator:F,version:k4(U,H,Q,te),major:U,minor:H,patch:Q,preRelease:te?.split(".")},f)){j=!1;break}}if(j)return!0}catch(R){console.error(`[semver] Error processing range part "${E}":`,R);continue}}return!1}var Hg="default",a4e="global";function n4e(e,t,a,r){let c;return"get"in e?c=e.get:"lib"in e?c=()=>Promise.resolve(e.lib):c=()=>Promise.resolve(()=>{ka(`Cannot get shared "${a}" from "${t}": neither "get" nor "lib" is provided in the share config.`)}),e.shareConfig?.eager&&e.treeShaking?.mode&&ka(`Invalid shared config for "${a}" from "${t}": cannot use both "eager: true" and "treeShaking.mode" simultaneously. Choose one strategy.`),{deps:[],useIn:[],from:t,loading:null,...e,shareConfig:{requiredVersion:`^${e.version}`,singleton:!1,eager:!1,strictVersion:!1,...e.shareConfig},get:c,loaded:e?.loaded||"lib"in e?!0:void 0,version:e.version??"0",scope:Array.isArray(e.scope)?e.scope:[e.scope??"default"],strategy:(e.strategy??r)||"version-first",treeShaking:e.treeShaking?{...e.treeShaking,mode:e.treeShaking.mode??"server-calc",status:e.treeShaking.status??zS.UNKNOWN,useIn:[]}:void 0}}function q6(e,t){const a=t.shared||{},r=t.name,c=Object.keys(a).reduce((d,h)=>{const f=T6(a[h]);return d[h]=d[h]||[],f.forEach(k=>{d[h].push(n4e(k,r,h,t.shareStrategy))}),d},{}),m={...e.shared};return Object.keys(c).forEach(d=>{m[d]?c[d].forEach(h=>{m[d].find(f=>f.version===h.version)||m[d].push(h)}):m[d]=c[d]}),{allShareInfos:m,newShareInfos:c}}function um(e,t){if(!e)return!1;const{status:a,mode:r}=e;return a===zS.NO_USE?!1:a===zS.CALCULATED?!0:r==="runtime-infer"?t?r4e(e,t):!0:!1}function il(e,t){const a=r=>{if(!Number.isNaN(Number(r))){const c=r.split(".");let m=r;for(let d=0;d<3-c.length;d++)m+=".0";return m}return r};return!!Ru(a(e),`<=${a(t)}`)}var mm=(e,t)=>{const a=t||function(r,c){return il(r,c)};return Object.keys(e).reduce((r,c)=>!r||a(r,c)||r==="0"?c:r,0)},Yf=e=>!!e.loaded||typeof e.lib=="function",i4e=e=>!!e.loading,r4e=(e,t)=>{if(!e||!t)return!1;const{usedExports:a}=e;return a?!!t.every(r=>a.includes(r)):!1};function o4e(e,t,a,r){const c=e[t][a];let m="",d=um(r);const h=function(f,k){return d?c[f].treeShaking?c[k].treeShaking?!Yf(c[f].treeShaking)&&il(f,k):!1:!0:!Yf(c[f])&&il(f,k)};if(d){if(m=mm(e[t][a],h),m)return{version:m,useTreesShaking:d};d=!1}return{version:mm(e[t][a],h),useTreesShaking:d}}var dc=e=>Yf(e)||i4e(e);function s4e(e,t,a,r){const c=e[t][a];let m="",d=um(r);const h=function(f,k){if(d){if(!c[f].treeShaking)return!0;if(!c[k].treeShaking)return!1;if(dc(c[k].treeShaking))return dc(c[f].treeShaking)?!!il(f,k):!0;if(dc(c[f].treeShaking))return!1}return dc(c[k])?dc(c[f])?!!il(f,k):!0:dc(c[f])?!1:il(f,k)};if(d){if(m=mm(e[t][a],h),m)return{version:m,useTreesShaking:d};d=!1}return{version:mm(e[t][a],h),useTreesShaking:d}}function l4e(e){return e==="loaded-first"?s4e:o4e}function hf(e,t,a,r){if(!e)return;const{shareConfig:c,scope:m=Hg,strategy:d,treeShaking:h}=a,f=Array.isArray(m)?m:[m];for(const k of f)if(c&&e[k]&&e[k][t]){const{requiredVersion:x}=c,{version:E,useTreesShaking:R}=l4e(d)(e,k,t,h),T=()=>{const j=e[k][t][E];if(c.singleton){if(typeof x=="string"&&!Ru(E,x)){const q=`Version ${E} from ${E&&j.from} of shared singleton module ${t} does not satisfy the requirement of ${a.from} which needs ${x})`;c.strictVersion?ka(q):cm(q)}return{shared:j,useTreesShaking:R}}else{if(x===!1||x==="*")return{shared:j,useTreesShaking:R};if(Ru(E,x))return{shared:j,useTreesShaking:R};const q=um(h);if(q){for(const[B,F]of Object.entries(e[k][t]))if(um(F.treeShaking,h?.usedExports)&&Ru(B,x))return{shared:F,useTreesShaking:q}}for(const[B,F]of Object.entries(e[k][t]))if(Ru(B,x))return{shared:F,useTreesShaking:!1}}},N={shareScopeMap:e,scope:k,pkgName:t,version:E,GlobalFederation:dm.__FEDERATION__,shareInfo:a,resolver:T};return(r.emit(N)||N).resolver()}}function L6(){return dm.__FEDERATION__.__SHARE__}function S4(e){const{pkgName:t,extraOptions:a,shareInfos:r}=e,c=f=>{if(!f)return;const k={};return f.forEach(E=>{k[E.version]=E}),k[mm(k,function(E,R){return!Yf(k[E])&&il(E,R)})]},m=a?.resolver??c,d=f=>f!==null&&typeof f=="object"&&!Array.isArray(f),h=(...f)=>{const k={};for(const x of f)if(x)for(const[E,R]of Object.entries(x)){const T=k[E];d(T)&&d(R)?k[E]=h(T,R):R!==void 0&&(k[E]=R)}return k};return h(m(r[t]),a?.customShareInfo)}var uc=(e,t)=>{e.useIn||(e.useIn=[]),kRe(e.useIn,t)};function Dh(e,t){return t&&e.treeShaking?e.treeShaking:e}function kx(e,t){return!t||t==="."?e:`${e}/${t.replace(/^\.\//,"")}`}function w4(e,t){for(const a of e){const r=t.startsWith(a.name);let c=t.replace(a.name,"");if(r){if(c.startsWith("/")){const h=a.name;return c=`.${c}`,{pkgNameOrAlias:h,expose:c,remote:a}}else if(c==="")return{pkgNameOrAlias:a.name,expose:".",remote:a}}const m=a.alias&&t.startsWith(a.alias);let d=a.alias&&t.replace(a.alias,"");if(a.alias&&m){if(d&&d.startsWith("/")){const h=a.alias;return d=`.${d}`,{pkgNameOrAlias:h,expose:d,remote:a}}else if(d==="")return{pkgNameOrAlias:a.alias,expose:".",remote:a}}}}function c4e(e,t){for(const a of e)if(t===a.name||a.alias&&t===a.alias)return a}var B6="RUNTIME-001",F6="RUNTIME-002",$6="RUNTIME-003",U6="RUNTIME-004",H6="RUNTIME-005",US="RUNTIME-006",Q6="RUNTIME-007",V6="RUNTIME-008",d4e="RUNTIME-009",K6="RUNTIME-010",G6="RUNTIME-011",u4e="RUNTIME-012",W6="RUNTIME-013",Z6="RUNTIME-014",Y6="RUNTIME-015",Kn={[B6]:"Failed to get remoteEntry exports.",[F6]:'The remote entry interface does not contain "init"',[$6]:"Failed to get manifest.",[U6]:"Failed to locate remote.",[H6]:"Invalid loadShareSync function call from bundler runtime",[US]:"Invalid loadShareSync function call from runtime",[Q6]:"Failed to get remote snapshot.",[V6]:"Failed to load script resources.",[d4e]:"Please call createInstance first.",[K6]:'The name option cannot be changed after initialization. If you want to create a new instance with a different name, please use "createInstance" api.',[G6]:"The remoteEntry URL is missing from the remote snapshot.",[u4e]:'The getter for the shared module is not a function. This may be caused by setting "shared.import: false" without the host providing the corresponding lib.',[W6]:"The manifest is not a valid Module Federation manifest.",[Z6]:"The remote does not expose the requested module.",[Y6]:"Remote container initialization failed."};({...Kn});var X6=".then(callbacks[0]).catch(callbacks[1])";async function m4e({entry:e,remoteEntryExports:t}){return new Promise((a,r)=>{try{t?a(t):typeof FEDERATION_ALLOW_NEW_FUNCTION<"u"?new Function("callbacks",`import("${e}")${X6}`)([a,r]):import(e).then(a).catch(r)}catch(c){ka(`Failed to load ESM entry from "${e}". ${c instanceof Error?c.message:String(c)}`)}})}async function p4e({entry:e,remoteEntryExports:t}){return new Promise((a,r)=>{try{t?a(t):typeof __system_context__>"u"?System.import(e).then(a).catch(r):new Function("callbacks",`System.import("${e}")${X6}`)([a,r])}catch(c){ka(`Failed to load SystemJS entry from "${e}". ${c instanceof Error?c.message:String(c)}`)}})}function J6(e,t,a){const{remoteEntryKey:r,entryExports:c}=vx(e,t);return c||ka(B6,Kn,{remoteName:e,remoteEntryUrl:a,remoteEntryKey:r}),c}async function h4e({name:e,globalName:t,entry:a,remoteInfo:r,loaderHook:c,getEntryUrl:m,resourceContext:d}){const{entryExports:h}=vx(e,t);if(h)return h;const f=m?m(a):a;return hRe(f,{attrs:{},createScriptHook:(k,x)=>{const E=c.lifecycle.createScript.emit({url:k,attrs:x,remoteInfo:r,resourceContext:d?{...d,url:k}:void 0});if(E&&(E instanceof HTMLScriptElement||"script"in E||"timeout"in E))return E}}).then(()=>J6(e,t,a),k=>{const x=k instanceof Error?k.message:String(k);ka(V6,Kn,{remoteName:e,resourceUrl:f},x)})}async function f4e({remoteInfo:e,remoteEntryExports:t,loaderHook:a,getEntryUrl:r,resourceContext:c}){const{entry:m,entryGlobalName:d,name:h,type:f}=e;switch(f){case"esm":case"module":return m4e({entry:m,remoteEntryExports:t});case"system":return p4e({entry:m,remoteEntryExports:t});default:return h4e({entry:m,globalName:d,name:h,remoteInfo:e,loaderHook:a,getEntryUrl:r,resourceContext:c})}}async function g4e({remoteInfo:e,loaderHook:t,resourceContext:a}){const{entry:r,entryGlobalName:c,name:m,type:d}=e,{entryExports:h}=vx(m,c);return h||vRe(r,{attrs:{name:m,globalName:c,type:d},loaderHook:{createScriptHook:(f,k={})=>{const x=t.lifecycle.createScript.emit({url:f,attrs:k,remoteInfo:e,resourceContext:a?{...a,url:f}:void 0});if(x&&"url"in x)return x}}}).then(()=>J6(m,c,r)).catch(f=>{ka(`Failed to load Node.js entry for remote "${m}" from "${r}". ${f instanceof Error?f.message:String(f)}`)})}function HS(e){const{entry:t,name:a}=e;return k6(a,t)}async function Sx(e){const{origin:t,remoteEntryExports:a,remoteInfo:r,getEntryUrl:c,resourceContext:m,_inErrorHandling:d=!1}=e,h=HS(r);if(a)return a;if(!Ic[h]){const f=t.remoteHandler.hooks.lifecycle.loadEntry,k=t.loaderHook;Ic[h]=f.emit({origin:t,loaderHook:k,remoteInfo:r,remoteEntryExports:a}).then(x=>x||((typeof ENV_TARGET<"u"?ENV_TARGET==="web":ks)?f4e({remoteInfo:r,remoteEntryExports:a,loaderHook:k,getEntryUrl:c,resourceContext:m}):g4e({remoteInfo:r,loaderHook:k,resourceContext:m}))).then(async x=>(await t.loaderHook.lifecycle.afterLoadEntry.emit({origin:t,remoteInfo:r,remoteEntryExports:x}),x)).catch(async x=>{const E=HS(r),R=x instanceof Error&&x.message.includes("ScriptExecutionError");if(x instanceof Error&&x.message.includes("RUNTIME-008")&&!R&&!d){const T=j=>Sx({...j,_inErrorHandling:!0}),N=await t.loaderHook.lifecycle.loadEntryError.emit({getRemoteEntry:T,origin:t,remoteInfo:r,remoteEntryExports:a,globalLoading:Ic,uniqueKey:E});if(N)return await t.loaderHook.lifecycle.afterLoadEntry.emit({origin:t,remoteInfo:r,remoteEntryExports:N,recovered:!0}),N}throw await t.loaderHook.lifecycle.afterLoadEntry.emit({origin:t,remoteInfo:r,error:x}),x})}return Ic[h]}function Ec(e){return{...e,entry:"entry"in e?e.entry:"",type:e.type||"global",entryGlobalName:e.entryGlobalName||e.name,shareScope:e.shareScope||"default"}}function v4e(){return typeof FEDERATION_BUILD_IDENTIFIER<"u"?FEDERATION_BUILD_IDENTIFIER:""}function y4e(e,t){const a=IRe(),r=[t.hooks,t.remoteHandler.hooks,t.sharedHandler.hooks,t.snapshotHandler.hooks,t.loaderHook,t.bridgeHook];return a.length>0&&a.forEach(c=>{e?.find(m=>m.name!==c.name)&&e.push(c)}),e&&e.length>0&&e.forEach(c=>{r.forEach(m=>{m.applyPlugin(c,t)})}),e}function b4e(e){return{name:e.name,alias:e.alias,entry:"entry"in e?e.entry:void 0,version:"version"in e?e.version:void 0,type:e.type,entryGlobalName:e.entryGlobalName,shareScope:e.shareScope}}function uo(e){const t={};for(const[a,r]of Object.entries(e.shared)){const c=r[0];c&&(t[a]={version:c.version,singleton:c.shareConfig?.singleton,requiredVersion:c.shareConfig?.requiredVersion===!1?!1:c.shareConfig?.requiredVersion,eager:c.eager,strictVersion:c.shareConfig?.strictVersion})}return{project:{name:e.name,mfRole:e.remotes?.length>0?"host":"unknown"},mfConfig:{name:e.name,remotes:e.remotes?.map(b4e)??[],shared:t}}}function eL(e){return{resourceCategory:"sync",share:!0,depsRemote:!0,...e}}function k4e(e,t){return t.map(a=>{const r=c4e(e,a.nameOrAlias);return lo(r,`Unable to preload ${a.nameOrAlias} as it is not included in ${!r&&w6({remoteInfo:r,remotes:e})}`),{remote:r,preloadConfig:eL(a)}})}function S4e(e){return e?e.map(t=>t==="."?t:t.startsWith("./")?t.replace("./",""):t):[]}function wx(e){return e instanceof Error?e.message.includes("timed out")||e.name.includes("Timeout"):!1}function rl(e,t,a,r){return{url:t,status:a,resourceType:e.resourceType,initiator:e.initiator,id:e.id,error:r}}async function w4e(e,t,a,r){const c=e.moduleCache.get(a.name),m=a.entry;if(c?.remoteEntryExports)return rl(r,m,"cached");try{if(!await Sx({origin:e,remoteInfo:a,remoteEntryExports:c?.remoteEntryExports,resourceContext:{...r,url:m}}))throw new Error(`Failed to load remoteEntry "${m}".`);return rl(r,m,"success")}catch(d){return rl(r,m,wx(d)?"timeout":"error",d)}}function x1({host:e,remoteInfo:t,url:a,attrs:r,context:c,needDeleteLink:m}){return new Promise(d=>{const{link:h,needAttach:f}=pRe({url:a,cb:()=>{d(rl(c,a,f?"success":"cached"))},onErrorCallback:k=>{d(rl(c,a,wx(k)?"timeout":"error",k))},attrs:r,createLinkHook:(k,x)=>{const E=e.loaderHook.lifecycle.createLink.emit({url:k,attrs:x,remoteInfo:t,resourceContext:{...c,url:k}});return E instanceof HTMLLinkElement,E},needDeleteLink:m});f&&document.head.appendChild(h)})}function x4e({host:e,remoteInfo:t,url:a,attrs:r,context:c}){return new Promise(m=>{const{script:d,needAttach:h}=A6({url:a,cb:()=>{m(rl(c,a,h?"success":"cached"))},onErrorCallback:f=>{m(rl(c,a,wx(f)?"timeout":"error",f))},attrs:r,createScriptHook:(f,k)=>{const x=e.loaderHook.lifecycle.createScript.emit({url:f,attrs:k,remoteInfo:t,resourceContext:{...c,url:f}});return x instanceof HTMLScriptElement,x},needDeleteScript:!0});h&&document.head.appendChild(d)})}function vu(e,t){return{...e,resourceType:t}}function tL(e,t,a,r=!0,c={initiator:"preloadRemote",id:e.name}){const{cssAssets:m,jsAssetsWithoutEntry:d,entryAssets:h}=a,f=[];if(t.options.inBrowser){if(h.forEach(k=>{const{moduleInfo:x}=k;f.push(w4e(t,e,x,vu(c,"remoteEntry")))}),r){const k={rel:"preload",as:"style"};m.forEach(x=>{f.push(x1({host:t,remoteInfo:e,url:x,attrs:k,context:vu(c,"css")}))})}else{const k={rel:"stylesheet",type:"text/css"};m.forEach(x=>{f.push(x1({host:t,remoteInfo:e,url:x,attrs:k,needDeleteLink:!1,context:vu(c,"css")}))})}if(r){const k={rel:"preload",as:"script"};d.forEach(x=>{f.push(x1({host:t,remoteInfo:e,url:x,attrs:k,context:vu(c,"js")}))})}else{const k={fetchpriority:"high",type:e?.type==="module"?"module":"text/javascript"};d.forEach(x=>{f.push(x4e({host:t,remoteInfo:e,url:x,attrs:k,context:vu(c,"js")}))})}}return Promise.all(f)}function M4e(e){if(!e||!("modules"in e)||!Array.isArray(e.modules))return;const t=e.modules.map(a=>a.moduleName).filter(Boolean);return t.length?t.join(","):void 0}function C4e(e,t,a){const r=t,c=Array.isArray(e.shareScope)?e.shareScope:[e.shareScope];c.length||c.push("default"),c.forEach(d=>{r[d]||(r[d]={})});const m={version:e.version||"",shareScopeKeys:Array.isArray(e.shareScope)?c:e.shareScope||"default"};return Object.defineProperty(m,"shareScopeMap",{value:r,enumerable:!1}),{remoteEntryInitOptions:m,shareScope:r[c[0]],initScope:a??[]}}var aL=class{constructor({remoteInfo:e,host:t}){this.inited=!1,this.initing=!1,this.lib=void 0,this.remoteInfo=e,this.host=t}async getEntry(e){if(this.remoteEntryExports)return this.remoteEntryExports;const t=await Sx({origin:this.host,remoteInfo:this.remoteInfo,remoteEntryExports:this.remoteEntryExports,resourceContext:{initiator:"loadRemote",id:kx(this.remoteInfo.name,e),resourceType:"remoteEntry"}});return lo(t,`remoteEntryExports is undefined
83
- ${w6(this.remoteInfo)}`),this.remoteEntryExports=t,this.remoteEntryExports}async init(e,t,a,r){const c=await this.getEntry(r);if(this.inited)return await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:c,cached:!0,origin:this.host}),c;if(this.initPromise){try{await this.initPromise,await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:c,cached:!0,origin:this.host})}catch(m){throw await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:c,error:m,cached:!0,origin:this.host}),m}return c}this.initing=!0,this.initPromise=(async()=>{await this.host.loaderHook.lifecycle.beforeInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,origin:this.host});const{remoteEntryInitOptions:m,shareScope:d,initScope:h}=C4e(this.remoteInfo,this.host.shareScopeMap,a),f=await this.host.hooks.lifecycle.beforeInitContainer.emit({shareScope:d,remoteEntryInitOptions:m,initScope:h,remoteInfo:this.remoteInfo,origin:this.host});typeof c?.init>"u"&&ka(F6,Kn,{hostName:this.host.name,remoteName:this.remoteInfo.name,remoteEntryUrl:this.remoteInfo.entry,remoteEntryKey:this.remoteInfo.entryGlobalName},void 0,uo(this.host.options));try{await c.init(f.shareScope,f.initScope,f.remoteEntryInitOptions)}catch(k){ka(Y6,Kn,{hostName:this.host.name,remoteName:this.remoteInfo.name,remoteEntryUrl:this.remoteInfo.entry,remoteEntryKey:this.remoteInfo.entryGlobalName,shareScope:this.remoteInfo.shareScope},`${k}`,uo(this.host.options))}await this.host.hooks.lifecycle.initContainer.emit({...f,id:e,remoteSnapshot:t,remoteEntryExports:c}),this.inited=!0})();try{await this.initPromise,await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:c,origin:this.host})}catch(m){throw await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:c,error:m,origin:this.host}),m}finally{this.initing=!1,this.initPromise=void 0}return c}async get(e,t,a,r){const{loadFactory:c=!0}=a||{loadFactory:!0},m=await this.init(e,r,void 0,t);this.lib=m,await this.host.loaderHook.lifecycle.beforeGetExpose.emit({id:e,expose:t,moduleInfo:this.remoteInfo,remoteEntryExports:m,origin:this.host});let d;try{const k=await this.host.loaderHook.lifecycle.getModuleFactory.emit({remoteEntryExports:m,expose:t,moduleInfo:this.remoteInfo});d=typeof k=="function"?k:void 0,d||(d=await m.get(t)),d||ka(Z6,Kn,{hostName:this.host.name,remoteName:this.remoteInfo.name,remoteEntryUrl:this.remoteInfo.entry,expose:t,requestId:e,availableExposes:M4e(r)},void 0,uo(this.host.options)),await this.host.loaderHook.lifecycle.afterGetExpose.emit({id:e,expose:t,moduleInfo:this.remoteInfo,remoteEntryExports:m,moduleFactory:d,origin:this.host})}catch(k){throw await this.host.loaderHook.lifecycle.afterGetExpose.emit({id:e,expose:t,moduleInfo:this.remoteInfo,remoteEntryExports:m,error:k,origin:this.host}),k}const h=xRe(this.remoteInfo.name,t),f=this.wraperFactory(d,h);if(!c)return f;await this.host.loaderHook.lifecycle.beforeExecuteFactory.emit({id:e,expose:t,moduleInfo:this.remoteInfo,loadFactory:c,origin:this.host});try{const k=await f();return await this.host.loaderHook.lifecycle.afterExecuteFactory.emit({id:e,expose:t,moduleInfo:this.remoteInfo,loadFactory:c,exposeModule:k,origin:this.host}),k}catch(k){throw await this.host.loaderHook.lifecycle.afterExecuteFactory.emit({id:e,expose:t,moduleInfo:this.remoteInfo,loadFactory:c,error:k,origin:this.host}),k}}wraperFactory(e,t){function a(r,c){r&&typeof r=="object"&&Object.isExtensible(r)&&!Object.getOwnPropertyDescriptor(r,Symbol.for("mf_module_id"))&&Object.defineProperty(r,Symbol.for("mf_module_id"),{value:c,enumerable:!1})}return()=>{const r=e();return r instanceof Promise?r.then(c=>(a(c,t),c)):(a(r,t),r)}}},Qn=class{constructor(e){this.type="",this.listeners=new Set,e&&(this.type=e)}on(e){typeof e=="function"&&this.listeners.add(e)}once(e){const t=this;this.on(function a(...r){return t.remove(a),e.apply(null,r)})}emit(...e){let t;return this.listeners.size>0&&this.listeners.forEach(a=>{const r=a(...e);r!==void 0&&(t=r)}),t}remove(e){this.listeners.delete(e)}removeAll(){this.listeners.clear()}},Ja=class extends Qn{emit(...e){let t;const a=Array.from(this.listeners);if(a.length>0){let r=0;const c=m=>m===!1?!1:r<a.length?Promise.resolve(a[r++].apply(null,e)).then(d=>d===void 0||e.length===1&&d===e[0]?c(m):c(d)):m;t=c()}return Promise.resolve(t)}};function nL(e,t){if(!gx(t))return!1;if(e!==t){for(const a in e)if(!(a in t))return!1}return!0}var jc=class extends Qn{constructor(e){super(),this.onerror=ka,this.type=e}emit(e){gx(e)||ka(`The data for the "${this.type}" hook should be an object.`);for(const t of this.listeners)try{const a=t(e);if(a===void 0)continue;if(nL(e,a))e=a;else{this.onerror(`A plugin returned an unacceptable value for the "${this.type}" type.`);break}}catch(a){cm(a),this.onerror(a)}return e}},ls=class extends Qn{constructor(e){super(),this.onerror=ka,this.type=e}emit(e){gx(e)||ka(`The response data for the "${this.type}" hook must be an object.`);const t=Array.from(this.listeners);if(t.length>0){let a=0;const r=m=>(cm(m),this.onerror(m),e),c=m=>{if(m!==void 0&&nL(e,m))e=m;else if(m!==void 0)return this.onerror(`A plugin returned an incorrect value for the "${this.type}" type.`),e;if(a<t.length)try{return Promise.resolve(t[a++](e)).then(c,r)}catch(d){return r(d)}return e};return Promise.resolve(c(e))}return Promise.resolve(e)}},zc=class{constructor(e){this.registerPlugins={},this.lifecycle=e,this.lifecycleKeys=Object.keys(e)}applyPlugin(e,t){lo(wRe(e),"Plugin configuration is invalid.");const a=e.name;lo(a,"A name must be provided by the plugin."),this.registerPlugins[a]||(this.registerPlugins[a]=e,e.apply?.(t),Object.keys(this.lifecycle).forEach(r=>{const c=e[r];c&&this.lifecycle[r].on(c)}))}removePlugin(e){lo(e,"A name is required.");const t=this.registerPlugins[e];lo(t,`The plugin "${e}" is not registered.`),Object.keys(t).forEach(a=>{a!=="name"&&this.lifecycle[a].remove(t[a])})}};function iL(e,t){const a=_6(t);a.url||ka(G6,Kn,{remoteName:e.name});let r=LS(t,a.url);!ks&&!r.startsWith("http")&&(r=`https:${r}`),e.type=a.type,e.entryGlobalName=a.globalName,e.entry=r,e.version=t.version,e.buildVersion=t.buildVersion}function A4e(){return{name:"snapshot-plugin",async afterResolve(e){const{remote:t,pkgNameOrAlias:a,expose:r,origin:c,remoteInfo:m,id:d}=e;if(!fx(t)||!R6(t)){const{remoteSnapshot:h,globalSnapshot:f}=await c.snapshotHandler.loadRemoteSnapshotInfo({moduleInfo:t,id:kx(t.name,r)});iL(m,h);const k={remote:t,preloadConfig:{nameOrAlias:a,exposes:[r],resourceCategory:"sync",share:!1,depsRemote:!1}},x=await c.remoteHandler.hooks.lifecycle.generatePreloadAssets.emit({origin:c,preloadOptions:k,remoteInfo:m,remote:t,remoteSnapshot:h,globalSnapshot:f});return x&&tL(m,c,x,!1,{initiator:"loadRemote",id:d}).catch(()=>{}),{...e,remoteSnapshot:h}}return e}}}function I4e(e){const t=e.split(":");return t.length===1?{name:t[0],version:void 0}:t.length===2?{name:t[0],version:t[1]}:{name:t[1],version:t[2]}}function rL(e,t,a,r,c={},m){const{value:d}=Xc(e,Zf(t)),h=m||d;if(h&&!x6(h)&&(a(h,t,r),h.remotesInfo)){const f=Object.keys(h.remotesInfo);for(const k of f){if(c[k])continue;c[k]=!0;const x=I4e(k),E=h.remotesInfo[k];rL(e,{name:x.name,version:E.matchedVersion},a,!1,c,void 0)}}}var M1=(e,t)=>document.querySelector(`${e}[${e==="link"?"href":"src"}="${t}"]`);function E4e(e,t,a,r,c){const m=[],d=[],h=[],f=new Set,k=new Set,{options:x}=e,{preloadConfig:E}=t,{depsRemote:R}=E;if(rL(r,a,(N,j,q)=>{let B;if(q)B=E;else if(Array.isArray(R)){const te=R.find(K=>K.nameOrAlias===j.name||K.nameOrAlias===j.alias);if(!te)return;B=eL(te)}else if(R===!0)B=E;else return;const F=LS(N,_6(N).url);F&&h.push({name:j.name,moduleInfo:{name:j.name,entry:F,type:"remoteEntryType"in N?N.remoteEntryType:"global",entryGlobalName:"globalName"in N?N.globalName:j.name,shareScope:"",version:"version"in N?N.version:void 0},url:F});let U="modules"in N?N.modules:[];const H=S4e(B.exposes);H.length&&"modules"in N&&(U=N?.modules?.reduce((te,K)=>(H?.indexOf(K.moduleName)!==-1&&te.push(K),te),[]));function Q(te){const K=te.map(W=>LS(N,W));return B.filter?K.filter(B.filter):K}if(U){const te=U.length;for(let K=0;K<te;K++){const W=U[K],oe=`${j.name}/${W.moduleName}`;e.remoteHandler.hooks.lifecycle.handlePreloadModule.emit({id:W.moduleName==="."?j.name:oe,name:j.name,remoteSnapshot:N,preloadConfig:B,remote:j,origin:e}),!ERe(oe)&&(B.resourceCategory==="all"?(m.push(...Q(W.assets.css.async)),m.push(...Q(W.assets.css.sync)),d.push(...Q(W.assets.js.async)),d.push(...Q(W.assets.js.sync))):B.resourceCategory==="sync"&&(m.push(...Q(W.assets.css.sync)),d.push(...Q(W.assets.js.sync))),RRe(oe))}}},!0,{},c),c.shared&&c.shared.length>0){const N=(j,q)=>{const{shared:B}=hf(e.shareScopeMap,q.sharedName,j,e.sharedHandler.hooks.lifecycle.resolveShare)||{};B&&typeof B.lib=="function"&&(q.assets.js.sync.forEach(F=>{f.add(F)}),q.assets.css.sync.forEach(F=>{k.add(F)}))};c.shared.forEach(j=>{const q=x.shared?.[j.sharedName];if(!q)return;const B=j.version?q.find(F=>F.version===j.version):q;B&&T6(B).forEach(F=>{N(F,j)})})}const T=d.filter(N=>!f.has(N)&&!M1("script",N));return{cssAssets:m.filter(N=>!k.has(N)&&!M1("link",N)),jsAssetsWithoutEntry:T,entryAssets:h.filter(N=>!M1("script",N.url))}}var R4e=function(){return{name:"generate-preload-assets-plugin",async generatePreloadAssets(e){const{origin:t,preloadOptions:a,remoteInfo:r,remote:c,globalSnapshot:m,remoteSnapshot:d}=e;return ks?fx(c)&&R6(c)?{cssAssets:[],jsAssetsWithoutEntry:[],entryAssets:[{name:c.name,url:c.entry,moduleInfo:{name:r.name,entry:c.entry,type:r.type||"global",entryGlobalName:"",shareScope:""}}]}:(iL(r,d),E4e(t,a,r,m,d)):{cssAssets:[],jsAssetsWithoutEntry:[],entryAssets:[]}}}};function oL(e,t){const a=uf({name:t.name,version:t.options.version}),r=a&&"remotesInfo"in a&&a.remotesInfo&&Xc(a.remotesInfo,e.name).value;return r&&r.matchedVersion?{hostGlobalSnapshot:a,globalSnapshot:h4(),remoteSnapshot:uf({name:e.name,version:r.matchedVersion})}:{hostGlobalSnapshot:void 0,globalSnapshot:h4(),remoteSnapshot:uf({name:e.name,version:"version"in e?e.version:void 0})}}var T4e=class{constructor(e){this.loadingHostSnapshot=null,this.manifestCache=new Map,this.hooks=new zc({beforeLoadRemoteSnapshot:new Ja("beforeLoadRemoteSnapshot"),loadSnapshot:new ls("loadGlobalSnapshot"),loadRemoteSnapshot:new ls("loadRemoteSnapshot"),afterLoadSnapshot:new ls("afterLoadSnapshot")}),this.manifestLoading=dm.__FEDERATION__.__MANIFEST_LOADING__,this.HostInstance=e,this.loaderHook=e.loaderHook}async loadRemoteSnapshotInfo({moduleInfo:e,id:t,initiator:a="loadRemote"}){const{options:r}=this.HostInstance;await this.hooks.lifecycle.beforeLoadRemoteSnapshot.emit({options:r,moduleInfo:e,origin:this.HostInstance});let c=uf({name:this.HostInstance.options.name,version:this.HostInstance.options.version});c||(c={version:this.HostInstance.options.version||"",remoteEntry:"",remotesInfo:{}},ARe({[this.HostInstance.options.name]:c})),c&&"remotesInfo"in c&&!Xc(c.remotesInfo,e.name).value&&("version"in e||"entry"in e)&&(c.remotesInfo={...c?.remotesInfo,[e.name]:{matchedVersion:"version"in e?e.version:e.entry}});const{hostGlobalSnapshot:m,remoteSnapshot:d,globalSnapshot:h}=this.getGlobalRemoteInfo(e),{remoteSnapshot:f,globalSnapshot:k}=await this.hooks.lifecycle.loadSnapshot.emit({options:r,moduleInfo:e,hostGlobalSnapshot:m,remoteSnapshot:d,globalSnapshot:h});let x,E;if(f)if(x6(f)){const R=ks?f.remoteEntry:f.ssrRemoteEntry||f.remoteEntry||"",T=await this.loadManifestSnapshot(R,e,{},{initiator:a,id:t||e.name}),N=f4({...e,entry:R},T);x=T,E=N}else{const{remoteSnapshot:R}=await this.hooks.lifecycle.loadRemoteSnapshot.emit({options:this.HostInstance.options,moduleInfo:e,remoteSnapshot:f,from:"global"});x=R,E=k}else if(fx(e)){const R=await this.loadManifestSnapshot(e.entry,e,{},{initiator:a,id:t||e.name}),T=f4(e,R);x=R,E=T}else ka(Q6,Kn,{remoteName:e.name,remoteVersion:e.version,hostName:this.HostInstance.options.name,globalSnapshot:JSON.stringify(k)},void 0,uo(this.HostInstance.options));return await this.hooks.lifecycle.afterLoadSnapshot.emit({id:t,host:this.HostInstance,options:r,moduleInfo:e,remoteSnapshot:x}),{remoteSnapshot:x,globalSnapshot:E}}getGlobalRemoteInfo(e){return oL(e,this.HostInstance)}async getManifestJson(e,t,a,r){return(async()=>{const m=Ec(t);let d=this.manifestCache.get(e);if(d)return d;try{let f=await this.loaderHook.lifecycle.fetch.emit(e,{},m,r?{...r,url:e,resourceType:"manifest"}:void 0);(!f||!(f instanceof Response))&&(f=await fetch(e,{})),d=await f.json()}catch(f){d=await this.HostInstance.remoteHandler.hooks.lifecycle.errorLoadRemote.emit({id:e,error:f,from:"runtime",lifecycle:"afterResolve",remote:m,origin:this.HostInstance}),d||(delete this.manifestLoading[e],ka($6,Kn,{manifestUrl:e,moduleName:t.name,hostName:this.HostInstance.options.name},`${f}`,uo(this.HostInstance.options)))}const h=[!d.metaData&&"metaData",!d.exposes&&"exposes",!d.shared&&"shared"].filter(Boolean);return h.length>0&&await this.HostInstance.remoteHandler.hooks.lifecycle.errorLoadRemote.emit({id:e,error:new Error(`"${e}" is not a valid federation manifest for remote "${t.name}". Missing required fields: ${h.join(", ")}.`),from:"runtime",lifecycle:"afterResolve",remote:m,origin:this.HostInstance}),h.length>0&&ka(W6,Kn,{manifestUrl:e,moduleName:t.name,hostName:this.HostInstance.options.name,missingFields:h.join(",")},void 0,uo(this.HostInstance.options)),this.manifestCache.set(e,d),d})()}async loadManifestSnapshot(e,t,a,r){const c=async()=>{const m=await this.getManifestJson(e,t,a,r),d=sRe(m,{version:e}),{remoteSnapshot:h}=await this.hooks.lifecycle.loadRemoteSnapshot.emit({options:this.HostInstance.options,moduleInfo:t,manifestJson:m,remoteSnapshot:d,manifestUrl:e,from:"manifest"});return h};return this.manifestLoading[e]||(this.manifestLoading[e]=c().then(m=>m)),this.manifestLoading[e]}},_4e=class{constructor(e){this.hooks=new zc({beforeRegisterShare:new jc("beforeRegisterShare"),afterResolve:new ls("afterResolve"),beforeLoadShare:new ls("beforeLoadShare"),loadShare:new Ja,afterLoadShare:new Qn("afterLoadShare"),errorLoadShare:new Qn("errorLoadShare"),resolveShare:new jc("resolveShare"),initContainerShareScopeMap:new jc("initContainerShareScopeMap")}),this.host=e,this.shareScopeMap={},this.initTokens={},this._setGlobalShareScopeMap(e.options)}emitAfterLoadShare({lifecycle:e,pkgName:t,shareInfo:a,selectedShared:r}){try{this.hooks.lifecycle.afterLoadShare.emit({pkgName:t,shareInfo:a,selectedShared:r,shared:this.host.options.shared,shareScopeMap:this.shareScopeMap,lifecycle:e,origin:this.host})}catch(c){cm(c)}}emitErrorLoadShare({lifecycle:e,pkgName:t,shareInfo:a,error:r,recovered:c}){try{this.hooks.lifecycle.errorLoadShare.emit({pkgName:t,shareInfo:a,shared:this.host.options.shared,shareScopeMap:this.shareScopeMap,lifecycle:e,origin:this.host,error:r,recovered:c})}catch(m){cm(m)}}registerShared(e,t){const{newShareInfos:a,allShareInfos:r}=q6(e,t);return Object.keys(a).forEach(c=>{a[c].forEach(m=>{m.scope.forEach(d=>{this.hooks.lifecycle.beforeRegisterShare.emit({origin:this.host,pkgName:c,shared:m}),this.shareScopeMap[d]?.[c]||this.setShared({pkgName:c,lib:m.lib,get:m.get,loaded:m.loaded||!!m.lib,shared:m,from:t.name})})})}),{newShareInfos:a,allShareInfos:r}}async loadShare(e,t){const{host:a}=this,r=S4({pkgName:e,extraOptions:t,shareInfos:a.options.shared});let c=r;try{r?.scope&&await Promise.all(r.scope.map(async f=>{await Promise.all(this.initializeSharing(f,{strategy:r.strategy}))})),c=(await this.hooks.lifecycle.beforeLoadShare.emit({pkgName:e,shareInfo:r,shared:a.options.shared,origin:a})).shareInfo,lo(c,`Cannot find shared "${e}" in host "${a.options.name}". Ensure the shared config for "${e}" is declared in the federation plugin options and the host has been initialized before loading shares.`);const m=c,{shared:d,useTreesShaking:h}=hf(this.shareScopeMap,e,c,this.hooks.lifecycle.resolveShare)||{};if(d){const f=Dh(d,h);if(f.lib)return uc(f,a.options.name),this.emitAfterLoadShare({lifecycle:"loadShare",pkgName:e,shareInfo:m,selectedShared:d}),f.lib;if(f.loading&&!f.loaded){const k=await f.loading;return f.loaded=!0,f.lib||(f.lib=k),uc(f,a.options.name),this.emitAfterLoadShare({lifecycle:"loadShare",pkgName:e,shareInfo:m,selectedShared:d}),k}else{const x=(async()=>{const R=await f.get();return uc(f,a.options.name),f.loaded=!0,f.lib=R,R})();this.setShared({pkgName:e,loaded:!1,shared:d,from:a.options.name,lib:null,loading:x,treeShaking:h?f:void 0});const E=await x;return this.emitAfterLoadShare({lifecycle:"loadShare",pkgName:e,shareInfo:m,selectedShared:d}),E}}else{if(t?.customShareInfo)return this.emitErrorLoadShare({lifecycle:"loadShare",pkgName:e,shareInfo:m,recovered:!0}),!1;const f=um(m.treeShaking),k=Dh(m,f),E=(async()=>{const T=await k.get();k.lib=T,k.loaded=!0,uc(k,a.options.name);const{shared:N,useTreesShaking:j}=hf(this.shareScopeMap,e,m,this.hooks.lifecycle.resolveShare)||{};if(N){const q=Dh(N,j);q.lib=T,q.loaded=!0,N.from=m.from}return T})();this.setShared({pkgName:e,loaded:!1,shared:m,from:a.options.name,lib:null,loading:E,treeShaking:f?k:void 0});const R=await E;return this.emitAfterLoadShare({lifecycle:"loadShare",pkgName:e,shareInfo:m,selectedShared:m}),R}}catch(m){throw this.emitErrorLoadShare({lifecycle:"loadShare",pkgName:e,shareInfo:c,error:m}),m}}initializeSharing(e=Hg,t){const{host:a}=this,r=t?.from,c=t?.strategy;let m=t?.initScope;const d=[];if(r!=="build"){const{initTokens:R}=this;m||(m=[]);let T=R[e];if(T||(T=R[e]={from:this.host.name}),m.indexOf(T)>=0)return d;m.push(T)}const h=this.shareScopeMap,f=a.options.name;h[e]||(h[e]={});const k=h[e],x=(R,T)=>{const{version:N,eager:j}=T;k[R]=k[R]||{};const q=k[R],B=q[N]&&Dh(q[N]),F=!!(B&&("eager"in B&&B.eager||"shareConfig"in B&&B.shareConfig?.eager));(!B||B.strategy!=="loaded-first"&&!B.loaded&&(!j!=!F?j:f>q[N].from))&&(q[N]=T)},E=async R=>{const{module:T}=await a.remoteHandler.getRemoteModuleAndOptions({id:R});let N;try{N=await T.getEntry()}catch(j){if(N=await a.remoteHandler.hooks.lifecycle.errorLoadRemote.emit({id:R,error:j,from:"runtime",lifecycle:"beforeLoadShare",remote:T.remoteInfo,origin:a}),!N)return}finally{N?.init&&!T.initing&&(T.remoteEntryExports=N,await T.init(void 0,void 0,m))}};return Object.keys(a.options.shared).forEach(R=>{a.options.shared[R].forEach(T=>{T.scope.includes(e)&&x(R,T)})}),(a.options.shareStrategy==="version-first"||c==="version-first")&&a.options.remotes.forEach(R=>{R.shareScope===e&&d.push(E(R.name))}),d}loadShareSync(e,t){const{host:a}=this,r=S4({pkgName:e,extraOptions:t,shareInfos:a.options.shared});try{r?.scope&&r.scope.forEach(m=>{this.initializeSharing(m,{strategy:r.strategy})});const{shared:c}=hf(this.shareScopeMap,e,r,this.hooks.lifecycle.resolveShare)||{};if(c){if(typeof c.lib=="function")return uc(c,a.options.name),c.loaded||(c.loaded=!0,c.from===a.options.name&&(r.loaded=!0)),this.emitAfterLoadShare({lifecycle:"loadShareSync",pkgName:e,shareInfo:r,selectedShared:c}),c.lib;if(typeof c.get=="function"){const m=c.get();if(!(m instanceof Promise))return uc(c,a.options.name),this.setShared({pkgName:e,loaded:!0,from:a.options.name,lib:m,shared:c}),this.emitAfterLoadShare({lifecycle:"loadShareSync",pkgName:e,shareInfo:r,selectedShared:c}),m}}if(r.lib)return r.loaded||(r.loaded=!0),this.emitAfterLoadShare({lifecycle:"loadShareSync",pkgName:e,shareInfo:r,selectedShared:r}),r.lib;if(r.get){const m=r.get();return m instanceof Promise&&ka(t?.from==="build"?H6:US,Kn,{hostName:a.options.name,sharedPkgName:e},void 0,uo(a.options)),r.lib=m,this.setShared({pkgName:e,loaded:!0,from:a.options.name,lib:r.lib,shared:r}),this.emitAfterLoadShare({lifecycle:"loadShareSync",pkgName:e,shareInfo:r,selectedShared:r}),r.lib}ka(US,Kn,{hostName:a.options.name,sharedPkgName:e},void 0,uo(a.options))}catch(c){throw this.emitErrorLoadShare({lifecycle:"loadShareSync",pkgName:e,shareInfo:r,error:c}),c}}initShareScopeMap(e,t,a={}){const{host:r}=this;this.shareScopeMap[e]=t,this.hooks.lifecycle.initContainerShareScopeMap.emit({shareScope:t,options:r.options,origin:r,scopeName:e,hostShareScopeMap:a.hostShareScopeMap})}setShared({pkgName:e,shared:t,from:a,lib:r,loading:c,loaded:m,get:d,treeShaking:h}){const{version:f,scope:k="default",...x}=t,E=Array.isArray(k)?k:[k],R=T=>{const N=(q,B,F)=>{F&&!q[B]&&(q[B]=F)},j=h?T.treeShaking:T;N(j,"loaded",m),N(j,"loading",c),N(j,"get",d)};E.forEach(T=>{this.shareScopeMap[T]||(this.shareScopeMap[T]={}),this.shareScopeMap[T][e]||(this.shareScopeMap[T][e]={}),this.shareScopeMap[T][e][f]||(this.shareScopeMap[T][e][f]={version:f,scope:[T],...x,lib:r});const N=this.shareScopeMap[T][e][f];R(N),a&&N.from!==a&&(N.from=a)})}_setGlobalShareScopeMap(e){const t=L6(),a=e.id||e.name;a&&!t[a]&&(t[a]=this.shareScopeMap)}},P4e=class{constructor(e){this.hooks=new zc({beforeRegisterRemote:new jc("beforeRegisterRemote"),registerRemote:new jc("registerRemote"),beforeRequest:new ls("beforeRequest"),afterMatchRemote:new Ja("afterMatchRemote"),onLoad:new Ja("onLoad"),afterLoadRemote:new Ja("afterLoadRemote"),handlePreloadModule:new Qn("handlePreloadModule"),errorLoadRemote:new Ja("errorLoadRemote"),beforePreloadRemote:new Ja("beforePreloadRemote"),generatePreloadAssets:new Ja("generatePreloadAssets"),afterPreloadRemote:new Ja("afterPreloadRemote"),loadEntry:new Ja}),this.host=e,this.idToRemoteMap={}}formatAndRegisterRemote(e,t){return(t.remotes||[]).reduce((a,r)=>(this.registerRemote(r,a,{force:!1}),a),e.remotes)}setIdToRemoteMap(e,t){const{remote:a,expose:r}=t,{name:c,alias:m}=a;if(this.idToRemoteMap[e]={name:a.name,expose:r},m&&e.startsWith(c)){const d=e.replace(c,m);this.idToRemoteMap[d]={name:a.name,expose:r};return}if(m&&e.startsWith(m)){const d=e.replace(m,c);this.idToRemoteMap[d]={name:a.name,expose:r}}}async loadRemote(e,t){const{host:a}=this,r=w4(a.options.remotes,e);let c=e,m=r?.expose,d=r?Ec(r.remote):void 0,h;try{const{loadFactory:f=!0}=t||{loadFactory:!0},{module:k,moduleOptions:x,remoteMatchInfo:E}=await this.getRemoteModuleAndOptions({id:e}),{pkgNameOrAlias:R,remote:T,expose:N,id:j,remoteSnapshot:q}=E;c=j,m=N,d=Ec(T);const B=await k.get(j,N,t,q),F=await this.hooks.lifecycle.onLoad.emit({id:j,pkgNameOrAlias:R,expose:N,exposeModule:f?B:void 0,exposeModuleFactory:f?void 0:B,remote:T,options:x,moduleInstance:k,origin:a});return this.setIdToRemoteMap(e,E),h={id:c,expose:m,remote:d,options:t,origin:a},typeof F=="function"?F:B}catch(f){const{from:k="runtime"}=t||{from:"runtime"};let x;try{x=await this.hooks.lifecycle.errorLoadRemote.emit({id:e,error:f,from:k,lifecycle:"onLoad",expose:m,remote:d,origin:a})}catch(E){throw h={id:c,expose:m,remote:d,options:t,error:E,origin:a},E}if(!x)throw h={id:c,expose:m,remote:d,options:t,error:f,origin:a},f;return h={id:c,expose:m,remote:d,options:t,error:f,origin:a,recovered:!0},x}finally{h&&await this.hooks.lifecycle.afterLoadRemote.emit(h)}}async preloadRemote(e){const{host:t}=this,a=[];await this.hooks.lifecycle.beforePreloadRemote.emit({preloadOps:e,options:t.options,origin:t});const r=k4e(t.options.remotes,e),c=h=>{const{preloadConfig:f,remote:k}=h,x=f.exposes||[];return x.length?x.map(E=>({ops:{...h,preloadConfig:{...f,exposes:[E]}},id:kx(k.name,E)})):[{ops:h,id:`${k.name}/*`}]};let m;await Promise.all(r.flatMap(c).map(async h=>{const{ops:f,id:k}=h,{remote:x,preloadConfig:E}=f,R=Ec(x);try{const{globalSnapshot:T,remoteSnapshot:N}=await t.snapshotHandler.loadRemoteSnapshotInfo({moduleInfo:x,id:k,initiator:"preloadRemote"}),j=await this.hooks.lifecycle.generatePreloadAssets.emit({origin:t,preloadOptions:f,remote:x,remoteInfo:R,globalSnapshot:T,remoteSnapshot:N});if(!j)return;const q=await tL(R,t,j,!0,{initiator:"preloadRemote",id:k});a.push({remote:x,remoteInfo:R,preloadConfig:E,id:k,results:q})}catch(T){a.push({remote:x,remoteInfo:R,preloadConfig:E,id:k,results:[{url:R.entry,status:"error",resourceType:/\.json(?:$|[?#])/i.test(R.entry)?"manifest":"remoteEntry",initiator:"preloadRemote",id:k,error:T}]})}}));const d=a.flatMap(h=>h.results.filter(f=>f.status==="error"||f.status==="timeout"));if(d.length>0&&(m=new Error(`preloadRemote failed to load ${d.length} resource(s).`),Object.assign(m,{results:a,failedResults:d})),await this.hooks.lifecycle.afterPreloadRemote.emit({preloadOps:e,options:t.options,origin:t,results:a,error:m}),m)throw m}registerRemotes(e,t){const{host:a}=this;e.forEach(r=>{this.registerRemote(r,a.options.remotes,{force:t?.force})})}async getRemoteModuleAndOptions(e){const{host:t}=this,{id:a}=e;let r;try{r=await this.hooks.lifecycle.beforeRequest.emit({id:a,options:t.options,origin:t})}catch(T){if(r=await this.hooks.lifecycle.errorLoadRemote.emit({id:a,options:t.options,origin:t,from:"runtime",error:T,lifecycle:"beforeRequest"}),!r)throw T}const{id:c}=r,m=w4(t.options.remotes,c);if(!m)try{ka(U6,Kn,{hostName:t.options.name,requestId:c},void 0,uo(t.options))}catch(T){throw await this.hooks.lifecycle.afterMatchRemote.emit({id:c,options:t.options,error:T,origin:t}),T}const{remote:d}=m,h=Ec(d);await this.hooks.lifecycle.afterMatchRemote.emit({id:c,...m,options:t.options,remoteInfo:h,origin:t});const f=await t.sharedHandler.hooks.lifecycle.afterResolve.emit({id:c,...m,options:t.options,origin:t,remoteInfo:h}),{remote:k,expose:x}=f;lo(k&&x,`The 'beforeRequest' hook was executed, but it failed to return the correct 'remote' and 'expose' values while loading ${c}.`);let E=t.moduleCache.get(k.name);const R={host:t,remoteInfo:h};return E||(E=new aL(R),t.moduleCache.set(k.name,E)),{module:E,moduleOptions:R,remoteMatchInfo:f}}registerRemote(e,t,a){const{host:r}=this,c=()=>{if(e.alias){const d=t.find(h=>e.alias&&(h.name.startsWith(e.alias)||h.alias?.startsWith(e.alias)));lo(!d,`The alias ${e.alias} of remote ${e.name} is not allowed to be the prefix of ${d&&d.name} name or alias`)}"entry"in e&&ks&&typeof window<"u"&&!e.entry.startsWith("http")&&(e.entry=new URL(e.entry,window.location.origin).href),e.shareScope||(e.shareScope=Hg),e.type||(e.type=a4e)};this.hooks.lifecycle.beforeRegisterRemote.emit({remote:e,origin:r});const m=t.find(d=>d.name===e.name);if(!m)c(),t.push(e),this.hooks.lifecycle.registerRemote.emit({remote:e,origin:r});else{const d=[`The remote "${e.name}" is already registered.`,"Please note that overriding it may cause unexpected errors."];a?.force&&(this.removeRemote(m),c(),t.push(e),this.hooks.lifecycle.registerRemote.emit({remote:e,origin:r}),S6(d.join(" ")))}}removeRemote(e){try{const{host:t}=this,{name:a}=e,r=t.options.remotes.findIndex(m=>m.name===a);r!==-1&&t.options.remotes.splice(r,1);const c=t.moduleCache.get(e.name);if(c){const m=c.remoteInfo,d=m.entryGlobalName;hn[d]&&(Object.getOwnPropertyDescriptor(hn,d)?.configurable?delete hn[d]:hn[d]=void 0);const h=HS(c.remoteInfo);Ic[h]&&delete Ic[h],t.snapshotHandler.manifestCache.delete(m.entry);let f=m.buildVersion?k6(m.name,m.buildVersion):m.name;const k=hn.__FEDERATION__.__INSTANCES__.findIndex(E=>m.buildVersion?E.options.id===f:E.name===f);if(k!==-1){const E=hn.__FEDERATION__.__INSTANCES__[k];f=E.options.id||f;const R=L6();let T=!0;const N=[];Object.keys(R).forEach(j=>{const q=R[j];q&&Object.keys(q).forEach(B=>{const F=q[B];F&&Object.keys(F).forEach(U=>{const H=F[U];H&&Object.keys(H).forEach(Q=>{const te=H[Q];te&&typeof te=="object"&&te.from===m.name&&(te.loaded||te.loading?(te.useIn=te.useIn.filter(K=>K!==m.name),te.useIn.length?T=!1:N.push([j,B,U,Q])):N.push([j,B,U,Q]))})})})}),T&&(E.shareScopeMap={},delete R[f]),N.forEach(([j,q,B,F])=>{delete R[j]?.[q]?.[B]?.[F]}),hn.__FEDERATION__.__INSTANCES__.splice(k,1)}const{hostGlobalSnapshot:x}=oL(e,t);if(x){const E=x&&"remotesInfo"in x&&x.remotesInfo&&Xc(x.remotesInfo,e.name).key;E&&(delete x.remotesInfo[E],dm.__FEDERATION__.__MANIFEST_LOADING__[E]&&delete dm.__FEDERATION__.__MANIFEST_LOADING__[E])}t.moduleCache.delete(e.name)}}catch(t){$S.error(`removeRemote failed: ${t instanceof Error?t.message:String(t)}`)}}},N4e=typeof FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN=="boolean"?!FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN:!0,O4e=class{constructor(e){this.hooks=new zc({beforeInit:new jc("beforeInit"),init:new Qn,beforeInitContainer:new ls("beforeInitContainer"),initContainer:new ls("initContainer")}),this.version="2.5.1",this.moduleCache=new Map,this.loaderHook=new zc({getModuleInfo:new Qn,createScript:new Qn,createLink:new Qn,fetch:new Ja,loadEntryError:new Ja,afterLoadEntry:new Ja("afterLoadEntry"),beforeInitRemote:new Ja("beforeInitRemote"),afterInitRemote:new Ja("afterInitRemote"),beforeGetExpose:new Ja("beforeGetExpose"),afterGetExpose:new Ja("afterGetExpose"),beforeExecuteFactory:new Ja("beforeExecuteFactory"),afterExecuteFactory:new Ja("afterExecuteFactory"),getModuleFactory:new Ja}),this.bridgeHook=new zc({beforeBridgeRender:new Qn,afterBridgeRender:new Qn,beforeBridgeDestroy:new Qn,afterBridgeDestroy:new Qn});const t=N4e?[A4e(),R4e()]:[],a={id:v4e(),name:e.name,plugins:t,remotes:[],shared:{},inBrowser:ks};this.name=e.name,this.options=a,this.snapshotHandler=new T4e(this),this.sharedHandler=new _4e(this),this.remoteHandler=new P4e(this),this.shareScopeMap=this.sharedHandler.shareScopeMap,this.registerPlugins([...a.plugins,...e.plugins||[]]),this.options=this.formatOptions(a,e)}initOptions(e){e.name&&e.name!==this.options.name&&ka(E6(K6,Kn)),this.registerPlugins(e.plugins);const t=this.formatOptions(this.options,e);return this.options=t,t}async loadShare(e,t){return this.sharedHandler.loadShare(e,t)}loadShareSync(e,t){return this.sharedHandler.loadShareSync(e,t)}initializeSharing(e=Hg,t){return this.sharedHandler.initializeSharing(e,t)}initRawContainer(e,t,a){const r=Ec({name:e,entry:t}),c=new aL({host:this,remoteInfo:r});return c.remoteEntryExports=a,this.moduleCache.set(e,c),c}async loadRemote(e,t){return this.remoteHandler.loadRemote(e,t)}async preloadRemote(e){return this.remoteHandler.preloadRemote(e)}initShareScopeMap(e,t,a={}){this.sharedHandler.initShareScopeMap(e,t,a)}formatOptions(e,t){const{allShareInfos:a}=q6(e,t),{userOptions:r,options:c}=this.hooks.lifecycle.beforeInit.emit({origin:this,userOptions:t,options:e,shareInfo:a}),m=this.remoteHandler.formatAndRegisterRemote(c,r),{allShareInfos:d}=this.sharedHandler.registerShared(c,r),h=[...c.plugins];r.plugins&&r.plugins.forEach(k=>{h.includes(k)||h.push(k)});const f={...e,...t,plugins:h,remotes:m,shared:d,id:r.id||e.id};return this.hooks.lifecycle.init.emit({origin:this,options:f}),f}registerPlugins(e){const t=y4e(e,this);this.options.plugins=this.options.plugins.reduce((a,r)=>(r&&a&&!a.find(c=>c.name===r.name)&&a.push(r),a),t||[])}registerRemotes(e,t){return this.remoteHandler.registerRemotes(e,t)}registerShared(e){this.sharedHandler.registerShared(this.options,{...this.options,shared:e})}};MRe(O4e);var D4e="camstack-mount",j4e=/^\/(?:[A-Za-z0-9_\-.]+\/)*$/,C1=null;function x4(e){if(e==null||e==="")return null;const t=e.endsWith("/")?e:`${e}/`;return!j4e.test(t)||t.includes("/../")||t.includes("/./")?null:t}function z4e(){if(typeof document>"u")return"/";const e=x4(document.querySelector(`meta[name="${D4e}"]`)?.getAttribute("content"));if(e!==null)return e;if(document.querySelector("base[href]")!==null)try{const t=new URL(document.baseURI);if(t.origin===window.location.origin){const a=x4(t.pathname);if(a!==null)return a}}catch{}return"/"}function sL(){return C1===null&&(C1=z4e()),C1}function xx(){return sL().replace(/\/$/,"")}function q4e(e){return/^[a-z][a-z0-9+.-]*:/i.test(e)||e.startsWith("//")}function I8e(e){if(q4e(e))return e;const t=sL(),a=e.replace(/^\/+/,"");return t!=="/"&&(e===xx()||e.startsWith(t))?e:`${t}${a}`}function L4e(){return`${typeof window<"u"?window.location.origin:""}${xx()}`}Oi("camstack:widget-registry",null);function E8e({title:e,icon:t,headerRight:a,collapsible:r=!1,defaultOpen:c=!0,bodyClassName:m="p-3",children:d}){const[h,f]=P.useState(c),k=!r||h,x=v.jsxs(v.Fragment,{children:[v.jsxs("span",{className:"flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-foreground",children:[t,e]}),r?h?v.jsx(gl,{className:"h-3.5 w-3.5 text-foreground-subtle"}):v.jsx(H3e,{className:"h-3.5 w-3.5 text-foreground-subtle"}):a]}),E=`px-4 py-2 flex items-center justify-between ${k?"border-b border-border":""}`;return v.jsxs("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[r?v.jsx("button",{type:"button",onClick:()=>f(R=>!R),className:`w-full text-left ${E}`,children:x}):v.jsx("div",{className:E,children:x}),k?v.jsx("div",{className:m,children:d}):null]})}var B4e="capability.binding-changed";function Vm(e,t){const[a,r]=P.useState(null);return P.useEffect(()=>{if(t===null){r(null);return}let c=!1;const m=async()=>{try{const h=await e.deviceManager.getBindings.query({deviceId:t});c||r(h)}catch{c||r(h=>h)}};m();const d=e.live?.onEvent.subscribe({category:B4e},{onData:h=>{const f=h.data?.source;if(!f){m();return}f.type==="device"&&f.id===t&&m()}});return()=>{c=!0,d?.unsubscribe()}},[e,t]),P.useMemo(()=>a?tJ(e,a):null,[e,a])}function cs(e){const t=P.useCallback(r=>e?e.subscribe(()=>r()):()=>{},[e]),a=P.useCallback(()=>e?.value,[e]);return P.useSyncExternalStore(t,a,a)}var F4e="/addon/snapshot/media";function R8e(e,t={}){const{width:a,baseUrl:r}=t,[c,m]=P.useState(0);return{src:P.useMemo(()=>{if(e===null||e<=0)return null;const d=r!==void 0?r.replace(/\/+$/,""):xx(),h=new URLSearchParams;a!==void 0&&Number.isInteger(a)&&a>0&&h.set("w",String(a)),c>0&&(h.set("force","1"),h.set("r",String(c)));const f=h.toString();return`${d}${F4e}/${String(e)}.jpg${f.length>0?`?${f}`:""}`},[e,a,r,c]),loading:!1,refresh:P.useCallback(()=>{m(d=>d+1)},[])}}O.Camera;function Nt(e){const t=Vm(e.trpc,e.deviceId),a=cs(t!==null?e.slice(t):void 0),r=t!==null?e.cap(t):void 0,c=cs(t!==null?t.state.deviceStatus:void 0),m=c?.online??!0,d=m?null:c?.lastChangedAt??null;return{dev:t,cap:r,slice:a,available:(e.requireFeature===void 0||(e.deviceFeatures??[]).includes(e.requireFeature))&&r!==void 0&&a!==void 0&&m,online:m,offlineSince:d}}var $4e=bl("inline-flex items-center justify-center rounded-md font-medium transition-colors cursor-pointer disabled:opacity-50 disabled:pointer-events-none",{variants:{variant:{primary:"bg-primary text-primary-foreground hover:bg-primary/90",secondary:"bg-surface text-foreground hover:bg-surface-hover",ghost:"hover:bg-surface-hover text-foreground-muted",danger:"bg-danger text-white hover:bg-danger/90",outline:"border border-border bg-transparent text-foreground hover:bg-surface-hover"},size:{sm:"h-7 px-2.5 text-xs gap-1.5",md:"h-8 px-3 text-sm gap-2",lg:"h-9 px-4 text-sm gap-2"}},defaultVariants:{variant:"primary",size:"sm"}}),pm=P.forwardRef(({className:e,variant:t,size:a,...r},c)=>v.jsx("button",{ref:c,className:ne($4e({variant:t,size:a}),e),...r}));pm.displayName="Button";var U4e=P.forwardRef(({className:e,...t},a)=>v.jsx("div",{ref:a,className:ne("animate-pulse bg-surface-hover rounded-md h-4 w-full",e),...t}));U4e.displayName="Skeleton";Oi("camstack:vod-playback",{request:null,play:()=>{},clear:()=>{}});var H4e=bl("rounded-lg p-3",{variants:{variant:{flat:"bg-surface",bordered:"bg-surface border border-border"}},defaultVariants:{variant:"bordered"}}),Q4e=P.forwardRef(({className:e,variant:t,...a},r)=>v.jsx("div",{ref:r,className:ne(H4e({variant:t}),e),...a}));Q4e.displayName="Card";function V4e(e){if(e==null||typeof e!="object")return null;const t=Reflect.get(e,"data");if(t!=null&&typeof t=="object"){const a=Reflect.get(t,"capRouteReason");if(typeof a=="string")return a}return null}function T8e(e){const t=V4e(e);return t!==null?t==="no-provider"||t==="node-offline":(e instanceof Error?e.message:String(e)).includes("provider not available")}Oi("camstack:recorded-playback",{bindControlChannel:null,channelOpen:!1,mode:"live",positionMs:null,send:()=>!1});var lL=P.createContext(null);function K4e(){const e=P.useContext(lL);if(!e)throw new Error("Dialog compound components must be used within <Dialog>");return e}function cL({children:e,open:t,onOpenChange:a}){const[r,c]=P.useState(!1),m=t??r,d=P.useId(),h=P.useCallback(f=>{a?.(f),t===void 0&&c(f)},[t,a]);return v.jsx(lL.Provider,{value:{open:m,setOpen:h,contentId:d},children:e})}var G4e=bl("relative fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 m-0 w-[calc(100vw-2rem)] bg-background-elevated text-foreground border border-border rounded-lg p-4 backdrop:bg-black/50 backdrop:backdrop-blur-sm max-h-[calc(100dvh-2rem-2*max(env(safe-area-inset-top),env(safe-area-inset-bottom)))] [&:not([open])]:hidden",{variants:{width:{sm:"max-w-sm",md:"max-w-md",lg:"max-w-lg",xl:"max-w-4xl"},scroll:{content:"overflow-y-auto",body:"flex flex-col overflow-hidden"},placement:{center:"","sheet-on-mobile":"bottom-0 left-0 right-0 top-auto w-full max-w-full translate-x-0 translate-y-0 rounded-b-none max-h-[92dvh] pb-[calc(1rem+env(safe-area-inset-bottom))] md:left-1/2 md:top-1/2 md:-translate-x-1/2 md:-translate-y-1/2 md:rounded-lg md:bottom-auto md:pb-4 md:max-h-[calc(100dvh-2rem-2*max(env(safe-area-inset-top),env(safe-area-inset-bottom)))]"}},compoundVariants:[{placement:"sheet-on-mobile",width:"sm",class:"md:w-[calc(100vw-2rem)] md:max-w-sm"},{placement:"sheet-on-mobile",width:"md",class:"md:w-[calc(100vw-2rem)] md:max-w-md"},{placement:"sheet-on-mobile",width:"lg",class:"md:w-[calc(100vw-2rem)] md:max-w-lg"},{placement:"sheet-on-mobile",width:"xl",class:"md:w-[calc(100vw-2rem)] md:max-w-4xl"},{scroll:"body",placement:"sheet-on-mobile",class:"h-[92dvh] md:h-auto"},{scroll:"body",placement:"center",class:"h-[calc(100dvh-2rem-2*max(env(safe-area-inset-top),env(safe-area-inset-bottom)))] md:h-auto"}],defaultVariants:{width:"md",placement:"center",scroll:"content"}}),Mx=P.forwardRef(({className:e,width:t,placement:a,scroll:r,children:c,...m},d)=>{const{open:h,setOpen:f,contentId:k}=K4e(),x=P.useRef(null),E=d??x;return P.useEffect(()=>{const R=E.current;R&&(h&&!R.open&&R.showModal(),!h&&R.open&&R.close())},[h,E]),v.jsxs("dialog",{ref:E,id:k,className:ne(G4e({width:t,placement:a,scroll:r}),e),onClose:()=>f(!1),...m,children:[v.jsx(hx,{type:"button",variant:"ghost",size:"sm",icon:Kq,"aria-label":"Close",className:"absolute right-4 top-4 z-10 shrink-0",onClick:()=>f(!1)}),c]})});Mx.displayName="DialogContent";function W4e({className:e,...t}){return v.jsx("div",{className:ne("flex flex-col gap-1 mb-3 shrink-0 pr-10",e),...t})}function Z4e({className:e,...t}){return v.jsx("div",{className:ne("flex justify-end gap-2 mt-4 shrink-0",e),...t})}function Y4e({className:e,...t}){return v.jsx("h2",{className:ne("text-sm font-semibold text-foreground",e),...t})}function X4e({className:e,...t}){return v.jsx("p",{className:ne("text-xs text-foreground-muted",e),...t})}P.lazy(()=>Hc(()=>import("./MotionZonesSettings-CiYjd-yl-Djy2GKmM.js"),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.MotionZonesSettings}))),P.lazy(()=>Hc(()=>import("./PrivacyMaskSettings-BmRdUrPp-DpHYAfGf.js"),__vite__mapDeps([2,1]),import.meta.url).then(e=>({default:e.PrivacyMaskSettings})));var J4e=Object.defineProperty,Xf=Object.getOwnPropertySymbols,dL=Object.prototype.hasOwnProperty,uL=Object.prototype.propertyIsEnumerable,M4=(e,t,a)=>t in e?J4e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a,QS=(e,t)=>{for(var a in t||(t={}))dL.call(t,a)&&M4(e,a,t[a]);if(Xf)for(var a of Xf(t))uL.call(t,a)&&M4(e,a,t[a]);return e},VS=(e,t)=>{var a={};for(var r in e)dL.call(e,r)&&t.indexOf(r)<0&&(a[r]=e[r]);if(e!=null&&Xf)for(var r of Xf(e))t.indexOf(r)<0&&uL.call(e,r)&&(a[r]=e[r]);return a};var ll;(e=>{const t=class _t{constructor(f,k,x,E){if(this.version=f,this.errorCorrectionLevel=k,this.modules=[],this.isFunction=[],f<_t.MIN_VERSION||f>_t.MAX_VERSION)throw new RangeError("Version value out of range");if(E<-1||E>7)throw new RangeError("Mask value out of range");this.size=f*4+17;let R=[];for(let N=0;N<this.size;N++)R.push(!1);for(let N=0;N<this.size;N++)this.modules.push(R.slice()),this.isFunction.push(R.slice());this.drawFunctionPatterns();const T=this.addEccAndInterleave(x);if(this.drawCodewords(T),E==-1){let N=1e9;for(let j=0;j<8;j++){this.applyMask(j),this.drawFormatBits(j);const q=this.getPenaltyScore();q<N&&(E=j,N=q),this.applyMask(j)}}c(0<=E&&E<=7),this.mask=E,this.applyMask(E),this.drawFormatBits(E),this.isFunction=[]}static encodeText(f,k){const x=e.QrSegment.makeSegments(f);return _t.encodeSegments(x,k)}static encodeBinary(f,k){const x=e.QrSegment.makeBytes(f);return _t.encodeSegments([x],k)}static encodeSegments(f,k,x=1,E=40,R=-1,T=!0){if(!(_t.MIN_VERSION<=x&&x<=E&&E<=_t.MAX_VERSION)||R<-1||R>7)throw new RangeError("Invalid value");let N,j;for(N=x;;N++){const U=_t.getNumDataCodewords(N,k)*8,H=d.getTotalBits(f,N);if(H<=U){j=H;break}if(N>=E)throw new RangeError("Data too long")}for(const U of[_t.Ecc.MEDIUM,_t.Ecc.QUARTILE,_t.Ecc.HIGH])T&&j<=_t.getNumDataCodewords(N,U)*8&&(k=U);let q=[];for(const U of f){a(U.mode.modeBits,4,q),a(U.numChars,U.mode.numCharCountBits(N),q);for(const H of U.getData())q.push(H)}c(q.length==j);const B=_t.getNumDataCodewords(N,k)*8;c(q.length<=B),a(0,Math.min(4,B-q.length),q),a(0,(8-q.length%8)%8,q),c(q.length%8==0);for(let U=236;q.length<B;U^=253)a(U,8,q);let F=[];for(;F.length*8<q.length;)F.push(0);return q.forEach((U,H)=>F[H>>>3]|=U<<7-(H&7)),new _t(N,k,F,R)}getModule(f,k){return 0<=f&&f<this.size&&0<=k&&k<this.size&&this.modules[k][f]}getModules(){return this.modules}drawFunctionPatterns(){for(let x=0;x<this.size;x++)this.setFunctionModule(6,x,x%2==0),this.setFunctionModule(x,6,x%2==0);this.drawFinderPattern(3,3),this.drawFinderPattern(this.size-4,3),this.drawFinderPattern(3,this.size-4);const f=this.getAlignmentPatternPositions(),k=f.length;for(let x=0;x<k;x++)for(let E=0;E<k;E++)x==0&&E==0||x==0&&E==k-1||x==k-1&&E==0||this.drawAlignmentPattern(f[x],f[E]);this.drawFormatBits(0),this.drawVersion()}drawFormatBits(f){const k=this.errorCorrectionLevel.formatBits<<3|f;let x=k;for(let R=0;R<10;R++)x=x<<1^(x>>>9)*1335;const E=(k<<10|x)^21522;c(E>>>15==0);for(let R=0;R<=5;R++)this.setFunctionModule(8,R,r(E,R));this.setFunctionModule(8,7,r(E,6)),this.setFunctionModule(8,8,r(E,7)),this.setFunctionModule(7,8,r(E,8));for(let R=9;R<15;R++)this.setFunctionModule(14-R,8,r(E,R));for(let R=0;R<8;R++)this.setFunctionModule(this.size-1-R,8,r(E,R));for(let R=8;R<15;R++)this.setFunctionModule(8,this.size-15+R,r(E,R));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let f=this.version;for(let x=0;x<12;x++)f=f<<1^(f>>>11)*7973;const k=this.version<<12|f;c(k>>>18==0);for(let x=0;x<18;x++){const E=r(k,x),R=this.size-11+x%3,T=Math.floor(x/3);this.setFunctionModule(R,T,E),this.setFunctionModule(T,R,E)}}drawFinderPattern(f,k){for(let x=-4;x<=4;x++)for(let E=-4;E<=4;E++){const R=Math.max(Math.abs(E),Math.abs(x)),T=f+E,N=k+x;0<=T&&T<this.size&&0<=N&&N<this.size&&this.setFunctionModule(T,N,R!=2&&R!=4)}}drawAlignmentPattern(f,k){for(let x=-2;x<=2;x++)for(let E=-2;E<=2;E++)this.setFunctionModule(f+E,k+x,Math.max(Math.abs(E),Math.abs(x))!=1)}setFunctionModule(f,k,x){this.modules[k][f]=x,this.isFunction[k][f]=!0}addEccAndInterleave(f){const k=this.version,x=this.errorCorrectionLevel;if(f.length!=_t.getNumDataCodewords(k,x))throw new RangeError("Invalid argument");const E=_t.NUM_ERROR_CORRECTION_BLOCKS[x.ordinal][k],R=_t.ECC_CODEWORDS_PER_BLOCK[x.ordinal][k],T=Math.floor(_t.getNumRawDataModules(k)/8),N=E-T%E,j=Math.floor(T/E);let q=[];const B=_t.reedSolomonComputeDivisor(R);for(let U=0,H=0;U<E;U++){let Q=f.slice(H,H+j-R+(U<N?0:1));H+=Q.length;const te=_t.reedSolomonComputeRemainder(Q,B);U<N&&Q.push(0),q.push(Q.concat(te))}let F=[];for(let U=0;U<q[0].length;U++)q.forEach((H,Q)=>{(U!=j-R||Q>=N)&&F.push(H[U])});return c(F.length==T),F}drawCodewords(f){if(f.length!=Math.floor(_t.getNumRawDataModules(this.version)/8))throw new RangeError("Invalid argument");let k=0;for(let x=this.size-1;x>=1;x-=2){x==6&&(x=5);for(let E=0;E<this.size;E++)for(let R=0;R<2;R++){const T=x-R,N=(x+1&2)==0?this.size-1-E:E;!this.isFunction[N][T]&&k<f.length*8&&(this.modules[N][T]=r(f[k>>>3],7-(k&7)),k++)}}c(k==f.length*8)}applyMask(f){if(f<0||f>7)throw new RangeError("Mask value out of range");for(let k=0;k<this.size;k++)for(let x=0;x<this.size;x++){let E;switch(f){case 0:E=(x+k)%2==0;break;case 1:E=k%2==0;break;case 2:E=x%3==0;break;case 3:E=(x+k)%3==0;break;case 4:E=(Math.floor(x/3)+Math.floor(k/2))%2==0;break;case 5:E=x*k%2+x*k%3==0;break;case 6:E=(x*k%2+x*k%3)%2==0;break;case 7:E=((x+k)%2+x*k%3)%2==0;break;default:throw new Error("Unreachable")}!this.isFunction[k][x]&&E&&(this.modules[k][x]=!this.modules[k][x])}}getPenaltyScore(){let f=0;for(let R=0;R<this.size;R++){let T=!1,N=0,j=[0,0,0,0,0,0,0];for(let q=0;q<this.size;q++)this.modules[R][q]==T?(N++,N==5?f+=_t.PENALTY_N1:N>5&&f++):(this.finderPenaltyAddHistory(N,j),T||(f+=this.finderPenaltyCountPatterns(j)*_t.PENALTY_N3),T=this.modules[R][q],N=1);f+=this.finderPenaltyTerminateAndCount(T,N,j)*_t.PENALTY_N3}for(let R=0;R<this.size;R++){let T=!1,N=0,j=[0,0,0,0,0,0,0];for(let q=0;q<this.size;q++)this.modules[q][R]==T?(N++,N==5?f+=_t.PENALTY_N1:N>5&&f++):(this.finderPenaltyAddHistory(N,j),T||(f+=this.finderPenaltyCountPatterns(j)*_t.PENALTY_N3),T=this.modules[q][R],N=1);f+=this.finderPenaltyTerminateAndCount(T,N,j)*_t.PENALTY_N3}for(let R=0;R<this.size-1;R++)for(let T=0;T<this.size-1;T++){const N=this.modules[R][T];N==this.modules[R][T+1]&&N==this.modules[R+1][T]&&N==this.modules[R+1][T+1]&&(f+=_t.PENALTY_N2)}let k=0;for(const R of this.modules)k=R.reduce((T,N)=>T+(N?1:0),k);const x=this.size*this.size,E=Math.ceil(Math.abs(k*20-x*10)/x)-1;return c(0<=E&&E<=9),f+=E*_t.PENALTY_N4,c(0<=f&&f<=2568888),f}getAlignmentPatternPositions(){if(this.version==1)return[];{const f=Math.floor(this.version/7)+2,k=this.version==32?26:Math.ceil((this.version*4+4)/(f*2-2))*2;let x=[6];for(let E=this.size-7;x.length<f;E-=k)x.splice(1,0,E);return x}}static getNumRawDataModules(f){if(f<_t.MIN_VERSION||f>_t.MAX_VERSION)throw new RangeError("Version number out of range");let k=(16*f+128)*f+64;if(f>=2){const x=Math.floor(f/7)+2;k-=(25*x-10)*x-55,f>=7&&(k-=36)}return c(208<=k&&k<=29648),k}static getNumDataCodewords(f,k){return Math.floor(_t.getNumRawDataModules(f)/8)-_t.ECC_CODEWORDS_PER_BLOCK[k.ordinal][f]*_t.NUM_ERROR_CORRECTION_BLOCKS[k.ordinal][f]}static reedSolomonComputeDivisor(f){if(f<1||f>255)throw new RangeError("Degree out of range");let k=[];for(let E=0;E<f-1;E++)k.push(0);k.push(1);let x=1;for(let E=0;E<f;E++){for(let R=0;R<k.length;R++)k[R]=_t.reedSolomonMultiply(k[R],x),R+1<k.length&&(k[R]^=k[R+1]);x=_t.reedSolomonMultiply(x,2)}return k}static reedSolomonComputeRemainder(f,k){let x=k.map(E=>0);for(const E of f){const R=E^x.shift();x.push(0),k.forEach((T,N)=>x[N]^=_t.reedSolomonMultiply(T,R))}return x}static reedSolomonMultiply(f,k){if(f>>>8||k>>>8)throw new RangeError("Byte out of range");let x=0;for(let E=7;E>=0;E--)x=x<<1^(x>>>7)*285,x^=(k>>>E&1)*f;return c(x>>>8==0),x}finderPenaltyCountPatterns(f){const k=f[1];c(k<=this.size*3);const x=k>0&&f[2]==k&&f[3]==k*3&&f[4]==k&&f[5]==k;return(x&&f[0]>=k*4&&f[6]>=k?1:0)+(x&&f[6]>=k*4&&f[0]>=k?1:0)}finderPenaltyTerminateAndCount(f,k,x){return f&&(this.finderPenaltyAddHistory(k,x),k=0),k+=this.size,this.finderPenaltyAddHistory(k,x),this.finderPenaltyCountPatterns(x)}finderPenaltyAddHistory(f,k){k[0]==0&&(f+=this.size),k.pop(),k.unshift(f)}};t.MIN_VERSION=1,t.MAX_VERSION=40,t.PENALTY_N1=3,t.PENALTY_N2=3,t.PENALTY_N3=40,t.PENALTY_N4=10,t.ECC_CODEWORDS_PER_BLOCK=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],t.NUM_ERROR_CORRECTION_BLOCKS=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],e.QrCode=t;function a(h,f,k){if(f<0||f>31||h>>>f)throw new RangeError("Value out of range");for(let x=f-1;x>=0;x--)k.push(h>>>x&1)}function r(h,f){return(h>>>f&1)!=0}function c(h){if(!h)throw new Error("Assertion error")}const m=class Na{constructor(f,k,x){if(this.mode=f,this.numChars=k,this.bitData=x,k<0)throw new RangeError("Invalid argument");this.bitData=x.slice()}static makeBytes(f){let k=[];for(const x of f)a(x,8,k);return new Na(Na.Mode.BYTE,f.length,k)}static makeNumeric(f){if(!Na.isNumeric(f))throw new RangeError("String contains non-numeric characters");let k=[];for(let x=0;x<f.length;){const E=Math.min(f.length-x,3);a(parseInt(f.substring(x,x+E),10),E*3+1,k),x+=E}return new Na(Na.Mode.NUMERIC,f.length,k)}static makeAlphanumeric(f){if(!Na.isAlphanumeric(f))throw new RangeError("String contains unencodable characters in alphanumeric mode");let k=[],x;for(x=0;x+2<=f.length;x+=2){let E=Na.ALPHANUMERIC_CHARSET.indexOf(f.charAt(x))*45;E+=Na.ALPHANUMERIC_CHARSET.indexOf(f.charAt(x+1)),a(E,11,k)}return x<f.length&&a(Na.ALPHANUMERIC_CHARSET.indexOf(f.charAt(x)),6,k),new Na(Na.Mode.ALPHANUMERIC,f.length,k)}static makeSegments(f){return f==""?[]:Na.isNumeric(f)?[Na.makeNumeric(f)]:Na.isAlphanumeric(f)?[Na.makeAlphanumeric(f)]:[Na.makeBytes(Na.toUtf8ByteArray(f))]}static makeEci(f){let k=[];if(f<0)throw new RangeError("ECI assignment value out of range");if(f<128)a(f,8,k);else if(f<16384)a(2,2,k),a(f,14,k);else if(f<1e6)a(6,3,k),a(f,21,k);else throw new RangeError("ECI assignment value out of range");return new Na(Na.Mode.ECI,0,k)}static isNumeric(f){return Na.NUMERIC_REGEX.test(f)}static isAlphanumeric(f){return Na.ALPHANUMERIC_REGEX.test(f)}getData(){return this.bitData.slice()}static getTotalBits(f,k){let x=0;for(const E of f){const R=E.mode.numCharCountBits(k);if(E.numChars>=1<<R)return 1/0;x+=4+R+E.bitData.length}return x}static toUtf8ByteArray(f){f=encodeURI(f);let k=[];for(let x=0;x<f.length;x++)f.charAt(x)!="%"?k.push(f.charCodeAt(x)):(k.push(parseInt(f.substring(x+1,x+3),16)),x+=2);return k}};m.NUMERIC_REGEX=/^[0-9]*$/,m.ALPHANUMERIC_REGEX=/^[A-Z0-9 $%*+.\/:-]*$/,m.ALPHANUMERIC_CHARSET="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";let d=m;e.QrSegment=m})(ll||(ll={}));(e=>{(t=>{const a=class{constructor(c,m){this.ordinal=c,this.formatBits=m}};a.LOW=new a(0,1),a.MEDIUM=new a(1,0),a.QUARTILE=new a(2,3),a.HIGH=new a(3,2),t.Ecc=a})(e.QrCode||(e.QrCode={}))})(ll||(ll={}));(e=>{(t=>{const a=class{constructor(c,m){this.modeBits=c,this.numBitsCharCount=m}numCharCountBits(c){return this.numBitsCharCount[Math.floor((c+7)/17)]}};a.NUMERIC=new a(1,[10,12,14]),a.ALPHANUMERIC=new a(2,[9,11,13]),a.BYTE=new a(4,[8,16,16]),a.KANJI=new a(8,[8,10,12]),a.ECI=new a(7,[0,0,0]),t.Mode=a})(e.QrSegment||(e.QrSegment={}))})(ll||(ll={}));var Rc=ll;var eTe={L:Rc.QrCode.Ecc.LOW,M:Rc.QrCode.Ecc.MEDIUM,Q:Rc.QrCode.Ecc.QUARTILE,H:Rc.QrCode.Ecc.HIGH},mL=128,pL="L",hL="#FFFFFF",fL="#000000",gL=!1,vL=1,tTe=4,aTe=0,nTe=.1;function yL(e,t=0){const a=[];return e.forEach(function(r,c){let m=null;r.forEach(function(d,h){if(!d&&m!==null){a.push(`M${m+t} ${c+t}h${h-m}v1H${m+t}z`),m=null;return}if(h===r.length-1){if(!d)return;m===null?a.push(`M${h+t},${c+t} h1v1H${h+t}z`):a.push(`M${m+t},${c+t} h${h+1-m}v1H${m+t}z`);return}d&&m===null&&(m=h)})}),a.join("")}function bL(e,t){return e.slice().map((a,r)=>r<t.y||r>=t.y+t.h?a:a.map((c,m)=>m<t.x||m>=t.x+t.w?c:!1))}function iTe(e,t,a,r){if(r==null)return null;const c=e.length+a*2,m=Math.floor(t*nTe),d=c/t,h=(r.width||m)*d,f=(r.height||m)*d,k=r.x==null?e.length/2-h/2:r.x*d,x=r.y==null?e.length/2-f/2:r.y*d,E=r.opacity==null?1:r.opacity;let R=null;if(r.excavate){let N=Math.floor(k),j=Math.floor(x);R={x:N,y:j,w:Math.ceil(h+k-N),h:Math.ceil(f+x-j)}}const T=r.crossOrigin;return{x:k,y:x,h:f,w:h,excavation:R,opacity:E,crossOrigin:T}}function rTe(e,t){return t!=null?Math.max(Math.floor(t),0):e?tTe:aTe}function kL({value:e,level:t,minVersion:a,includeMargin:r,marginSize:c,imageSettings:m,size:d,boostLevel:h}){let f=Xa.useMemo(()=>{const T=(Array.isArray(e)?e:[e]).reduce((N,j)=>(N.push(...Rc.QrSegment.makeSegments(j)),N),[]);return Rc.QrCode.encodeSegments(T,eTe[t],a,void 0,void 0,h)},[e,t,a,h]);const{cells:k,margin:x,numCells:E,calculatedImageSettings:R}=Xa.useMemo(()=>{let T=f.getModules();const N=rTe(r,c);return{cells:T,margin:N,numCells:T.length+N*2,calculatedImageSettings:iTe(T,d,N,m)}},[f,d,m,r,c]);return{qrcode:f,margin:x,cells:k,numCells:E,calculatedImageSettings:R}}var oTe=(function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0})(),sTe=Xa.forwardRef(function(t,a){const r=t,{value:c,size:m=mL,level:d=pL,bgColor:h=hL,fgColor:f=fL,includeMargin:k=gL,minVersion:x=vL,boostLevel:E,marginSize:R,imageSettings:T}=r,N=VS(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:j}=N,q=VS(N,["style"]),B=T?.src,F=Xa.useRef(null),U=Xa.useRef(null),H=Xa.useCallback(Ee=>{F.current=Ee,typeof a=="function"?a(Ee):a&&(a.current=Ee)},[a]),[Q,te]=Xa.useState(!1),{margin:K,cells:W,numCells:oe,calculatedImageSettings:he}=kL({value:c,level:d,minVersion:x,boostLevel:E,includeMargin:k,marginSize:R,imageSettings:T,size:m});Xa.useEffect(()=>{if(F.current!=null){const Ee=F.current,Ie=Ee.getContext("2d");if(!Ie)return;let Me=W;const Y=U.current,de=he!=null&&Y!==null&&Y.complete&&Y.naturalHeight!==0&&Y.naturalWidth!==0;de&&he.excavation!=null&&(Me=bL(W,he.excavation));const Re=window.devicePixelRatio||1;Ee.height=Ee.width=m*Re;const Qe=m/oe*Re;Ie.scale(Qe,Qe),Ie.fillStyle=h,Ie.fillRect(0,0,oe,oe),Ie.fillStyle=f,oTe?Ie.fill(new Path2D(yL(Me,K))):W.forEach(function(re,V){re.forEach(function(ie,fe){ie&&Ie.fillRect(fe+K,V+K,1,1)})}),he&&(Ie.globalAlpha=he.opacity),de&&Ie.drawImage(Y,he.x+K,he.y+K,he.w,he.h)}}),Xa.useEffect(()=>{te(!1)},[B]);const Ae=QS({height:m,width:m},j);let we=null;return B!=null&&(we=Xa.createElement("img",{src:B,key:B,style:{display:"none"},onLoad:()=>{te(!0)},ref:U,crossOrigin:he?.crossOrigin})),Xa.createElement(Xa.Fragment,null,Xa.createElement("canvas",QS({style:Ae,height:m,width:m,ref:H,role:"img"},q)),we)});sTe.displayName="QRCodeCanvas";var lTe=Xa.forwardRef(function(t,a){const r=t,{value:c,size:m=mL,level:d=pL,bgColor:h=hL,fgColor:f=fL,includeMargin:k=gL,minVersion:x=vL,boostLevel:E,title:R,marginSize:T,imageSettings:N}=r,j=VS(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:q,cells:B,numCells:F,calculatedImageSettings:U}=kL({value:c,level:d,minVersion:x,boostLevel:E,includeMargin:k,marginSize:T,imageSettings:N,size:m});let H=B,Q=null;N!=null&&U!=null&&(U.excavation!=null&&(H=bL(B,U.excavation)),Q=Xa.createElement("image",{href:N.src,height:U.h,width:U.w,x:U.x+q,y:U.y+q,preserveAspectRatio:"none",opacity:U.opacity,crossOrigin:U.crossOrigin}));const te=yL(H,q);return Xa.createElement("svg",QS({height:m,width:m,viewBox:`0 0 ${F} ${F}`,ref:a,role:"img"},j),!!R&&Xa.createElement("title",null,R),Xa.createElement("path",{fill:h,d:`M0,0 h${F}v${F}H0z`,shapeRendering:"crispEdges"}),Xa.createElement("path",{fill:f,d:te,shapeRendering:"crispEdges"}),Q)});lTe.displayName="QRCodeSVG";var N8e="text-[10px] text-foreground-subtle",cTe="inline-flex items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-medium transition-colors",dTe="border-primary/50 bg-primary/15 text-primary",uTe=P.forwardRef(({className:e,...t},a)=>v.jsx("label",{ref:a,className:ne("text-[10px] uppercase tracking-wider text-foreground-muted font-medium",e),...t}));uTe.displayName="Label";var mTe=bl("",{variants:{orientation:{horizontal:"h-px w-full bg-border-subtle",vertical:"w-px h-full bg-border-subtle"}},defaultVariants:{orientation:"horizontal"}}),pTe=P.forwardRef(({className:e,orientation:t,...a},r)=>v.jsx("div",{ref:r,role:"separator","aria-orientation":t??"horizontal",className:ne(mTe({orientation:t}),e),...a}));pTe.displayName="Separator";var hTe=P.forwardRef(({className:e,...t},a)=>v.jsx("input",{ref:a,type:"checkbox",className:ne("w-3.5 h-3.5 rounded-sm border border-border accent-primary",e),...t}));hTe.displayName="Checkbox";var fTe=P.forwardRef(({className:e,checked:t,onCheckedChange:a,label:r,...c},m)=>v.jsxs("button",{ref:m,role:"switch","aria-checked":t,type:"button",onClick:()=>a(!t),className:ne("inline-flex items-center gap-2",e),...c,children:[v.jsx("span",{className:ne("w-8 h-4 rounded-full transition-colors",t?"bg-primary":"bg-surface-hover"),children:v.jsx("span",{className:ne("block w-3.5 h-3.5 rounded-full bg-white transition-transform",t?"translate-x-4":"translate-x-0.5")})}),r&&v.jsx("span",{className:"text-xs text-foreground",children:r})]}));fTe.displayName="Switch";P.createContext(null);var gTe=P.forwardRef(({className:e,...t},a)=>v.jsx("div",{ref:a,className:ne("overflow-auto [&::-webkit-scrollbar]:w-1 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-thumb]:bg-surface-hover [&::-webkit-scrollbar-thumb]:rounded-full",e),...t}));gTe.displayName="ScrollArea";var A1={baseDelayMs:1500,maxDelayMs:15e3,maxAttempts:40};function vTe(e,t=Math.random){if(e>=A1.maxAttempts)return{kind:"exhausted",attempts:e};const a=Math.min(A1.maxDelayMs,A1.baseDelayMs*2**e);return{kind:"retry",delayMs:Math.round(a*(.8+t()*.4))}}var yTe="/adaptive-probe",bTe=2500,kTe=15e3,STe=250,wTe=2;function SL(e){return e>=8?"high":e>=2.5?"mid":"low"}function xTe(e){const{downlinkMbps:t,...a}=e;return a}function C4(e){return SL(e)!=="low"}function A4(e){if(e===void 0||e==="")return null;let t;try{t=new URL(e)}catch{return null}return t.protocol!=="http:"&&t.protocol!=="https:"?null:`${t.origin}${t.pathname.replace(/\/+$/,"")}`}function MTe(e,t){return A4(e)??A4(t)}function CTe(e){const t=e.downlinkMbps===void 0?"none":SL(e.downlinkMbps);return[e.phase,e.viewportWidth??"-",e.viewportHeight??"-",e.devicePixelRatio??"-",t,e.prefersTier??"-",e.probeOrigin??"unreachable",e.probeStatus??"-",e.probeAnswer??"-"].join("|")}function wL(e,t){return e<65536||!(t>0)?null:e*8/t/1e3}async function ATe(e,t){let a=null,r=0,c=0;try{for(;;){const m=await e.read();if(m.done)break;const d=m.value?.byteLength??0,h=t();a===null?a=h:c+=d,r=h}}catch{e.cancel().catch(()=>{})}return a===null?null:wL(c,r-a)}async function ITe(e,t){const a=e.replace(/\/+$/,""),r=new AbortController,c=setTimeout(()=>r.abort(),bTe);try{const m=await t.fetchImpl(`${a}${yTe}`,{signal:r.signal});if(!m.ok)return m.status!==void 0&&t.onRefused?.(m.status),null;const d=m.body?.getReader()??null;if(d!==null)return await ATe(d,t.now);const h=t.now();return wL((await m.arrayBuffer()).byteLength,t.now()-h)}catch{return null}finally{clearTimeout(c)}}async function ETe(e,t=kTe){const a=e.now()+t;for(;;){if(e.signal.aborted)return"aborted";if((e.readyState()??0)>=wTe)return"frame";if(e.now()>=a)return"timeout";await e.sleep(STe)}}async function RTe(e){if(await e.waitFrame()==="frame")return e.measure()}function TTe(e){const t=new Map,a=new Map,r=new Set,c=m=>{const d=t.get(m);return d!==void 0&&e.now()-d.at<=e.ttlMs?d.mbps:void 0};return{cached:c,firstRefusal:(m,d)=>{const h=`${m}|${String(d)}`;return r.has(h)?!1:(r.add(h),!0)},latest:m=>{const d=t.get(m);return d===void 0?null:{mbps:d.mbps,ageMs:Math.max(0,e.now()-d.at)}},measured:(m,d)=>{const h=c(m);if(h!==void 0)return Promise.resolve(h);const f=a.get(m);if(f!==void 0)return f;const k=d().then(x=>{if(!(x===null||!Number.isFinite(x)))return t.set(m,{mbps:x,at:e.now()}),x}).catch(()=>{}).finally(()=>{a.delete(m)});return a.set(m,k),k}}}async function _Te(e,t,a){if(e===void 0)return{kind:"unsupported",why:"no-wiring"};if(t===null)return{kind:"unsupported",why:"no-session"};try{return{kind:"answered",answer:await e(t,a)}}catch{return{kind:"unsupported",why:"call-failed"}}}var PTe=100;function NTe(e,t,a){if(a.renegotiating)return{baseline:null,sample:null};if(e===null||e.pc!==t.pc||t.ts<=e.ts)return{baseline:t,sample:null};const r=Math.max(0,t.lost-e.lost),c=r+Math.max(0,t.recv-e.recv),m=c>0?Math.min(PTe,r/c*100):0,d=Math.max(0,Math.round((t.bytes-e.bytes)*8/(t.ts-e.ts)));return{baseline:t,sample:{rttMs:Math.round(t.rttS*1e3),jitterMs:Math.round(t.jitterS*1e3),estimatedBandwidthKbps:d,packetLossPercent:m,...a.probe!==null?{downlinkMbps:a.probe.mbps,downlinkAgeMs:a.probe.ageMs}:{}}}}var OTe={urls:"stun:stun.l.google.com:19302"};function I1(e,t){const a=[...e??[],OTe];return t===void 0?{iceServers:a}:{iceServers:a,iceTransportPolicy:t}}var I4=8;function pn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Ji(e){return typeof e=="string"&&e.length>0?e:null}function Zi(e,t){if(e===null||t===null)return null;const a=e-t;return a<0?null:a}function xL(e,t){if(e===null||t===null)return null;const a=e+t;return a<=0?null:e/a*100}function DTe(e){return e===null?null:/profile-level-id=([0-9a-fA-F]+)/.exec(e)?.[1]??null}function jTe(e){const t={inbound:null,codecs:new Map,candidates:new Map,pair:null,selectedPairId:null},a=[];e.forEach(c=>{const m=c,d=Ji(m.id);switch(m.type){case"inbound-rtp":(m.kind??m.mediaType)==="video"&&(t.inbound=m);break;case"codec":d!==null&&t.codecs.set(d,m);break;case"local-candidate":case"remote-candidate":d!==null&&t.candidates.set(d,m);break;case"candidate-pair":a.push(m);break;case"transport":t.selectedPairId=Ji(m.selectedCandidatePairId);break}});const r=t.selectedPairId;return t.pair=a.find(c=>Ji(c.id)===r)??a.find(c=>c.selected===!0)??a.find(c=>c.nominated===!0&&c.state==="succeeded")??a.find(c=>c.nominated===!0)??a.find(c=>c.state==="succeeded")??null,t}function zTe(e){return e===null?{timestamp:null,bytesReceived:null,packetsReceived:null,packetsLost:null,framesDecoded:null,framesDropped:null,freezeCount:null,totalFreezesDurationS:null,totalDecodeTimeS:null,nackCount:null,pliCount:null}:{timestamp:pn(e.timestamp),bytesReceived:pn(e.bytesReceived),packetsReceived:pn(e.packetsReceived),packetsLost:pn(e.packetsLost),framesDecoded:pn(e.framesDecoded),framesDropped:pn(e.framesDropped),freezeCount:pn(e.freezeCount),totalFreezesDurationS:pn(e.totalFreezesDuration),totalDecodeTimeS:pn(e.totalDecodeTime),nackCount:pn(e.nackCount),pliCount:pn(e.pliCount)}}var E4={spanMs:null,kbps:null,packetsReceived:null,packetsLost:null,lossPercent:null,framesDecoded:null,framesDropped:null,freezeCount:null,freezeMs:null,nackCount:null,pliCount:null,decodeMs:null};function qTe(e,t){if(t===null)return E4;const a=Zi(e.timestamp,t.timestamp);if(a===null||a<=0)return E4;const r=Zi(e.bytesReceived,t.bytesReceived),c=Zi(e.packetsLost,t.packetsLost),m=Zi(e.packetsReceived,t.packetsReceived),d=Zi(e.framesDecoded,t.framesDecoded),h=Zi(e.totalDecodeTimeS,t.totalDecodeTimeS),f=Zi(e.totalFreezesDurationS,t.totalFreezesDurationS);return{spanMs:a,kbps:r===null?null:Math.round(r*8/a),packetsReceived:m,packetsLost:c,lossPercent:xL(c,m),framesDecoded:d,framesDropped:Zi(e.framesDropped,t.framesDropped),freezeCount:Zi(e.freezeCount,t.freezeCount),freezeMs:f===null?null:Math.round(f*1e3),nackCount:Zi(e.nackCount,t.nackCount),pliCount:Zi(e.pliCount,t.pliCount),decodeMs:h===null||d===null||d<=0?null:h/d*1e3}}function LTe(e,t,a,r){if(t===null||a===null)return e;const c=e.at(-1);if(c!==void 0&&c.width===t&&c.height===a)return e;const m=[...e,{width:t,height:a,at:r}];return m.length>I4?m.slice(m.length-I4):m}function BTe(e){const{inbound:t,codecs:a,candidates:r,pair:c}=jTe(e.report),m=zTe(t),d=t!==null?a.get(Ji(t.codecId)??""):void 0,h=Ji(d?.mimeType),f=Ji(d?.sdpFmtpLine),k=c!==null?r.get(Ji(c.localCandidateId)??""):void 0,x=c!==null?r.get(Ji(c.remoteCandidateId)??""):void 0,E=Ji(k?.candidateType),R=Ji(x?.candidateType),T=pn(t?.frameWidth),N=pn(t?.frameHeight),j=m.totalFreezesDurationS,q=m.totalDecodeTimeS,B=m.framesDecoded;return{at:e.now,hasInboundVideo:t!==null,width:T,height:N,fps:pn(t?.framesPerSecond),codec:h===null?null:h.split("/")[1]??h,codecProfileLevelId:DTe(f),jitterMs:FTe(t),packetsReceived:m.packetsReceived,packetsLost:m.packetsLost,lossPercent:xL(m.packetsLost,m.packetsReceived),nackCount:m.nackCount,pliCount:m.pliCount,framesDecoded:B,framesDropped:m.framesDropped,freezeCount:m.freezeCount,totalFreezeMs:j===null?null:Math.round(j*1e3),avgDecodeMs:q===null||B===null||B<=0?null:q/B*1e3,rttMs:$Te(c),availableIncomingKbps:UTe(c),localCandidateType:E,remoteCandidateType:R,candidatePairType:E===null&&R===null?null:`${E??"?"}/${R??"?"}`,candidateProtocol:Ji(k?.protocol),iceConnectionState:e.iceConnectionState,dtlsState:e.dtlsState,window:qTe(m,e.prev?.raw??null),resolutionLog:LTe(e.prev?.resolutionLog??[],T,N,e.now),raw:m}}function FTe(e){const t=pn(e?.jitter);return t===null?null:t*1e3}function $Te(e){const t=pn(e?.currentRoundTripTime);return t===null?null:t*1e3}function UTe(e){const t=pn(e?.availableIncomingBitrate);return t===null?null:Math.round(t/1e3)}var HTe={unknown:"no window yet",decoding:"decoding","decoder-stall":"DECODER STALL — bytes arriving, no frames out","transport-stall":"TRANSPORT STALL — nothing arriving","frozen-unknown":"frames stopped — byte rate unknown"};function ML(e){const t=QTe(e);return{kind:t,label:HTe[t]}}function QTe(e){if(e===null||!e.hasInboundVideo)return"unknown";const t=e.window.framesDecoded;if(t===null)return"unknown";if(t>0)return"decoding";const a=e.window.kbps;return a===null?"frozen-unknown":a>0?"decoder-stall":"transport-stall"}var ol="—";function ia(e,t){if(e==null||!Number.isFinite(e))return ol;const a=t?.digits??0;return`${e.toFixed(a)}${t?.suffix??""}`}function Yi(e){return e==null||e===""?ol:e}function jh(e){return e==null?ol:e?"yes":"no"}function KS(e,t){if(e===null)return ol;const a=Math.max(0,t-e);return a<1e3?`${a}ms ago`:a<6e4?`${(a/1e3).toFixed(1)}s ago`:`${Math.floor(a/6e4)}m${Math.floor(a%6e4/1e3)}s ago`}var CL=3e3,VTe={unknown:"bg-white/15 text-white/70",decoding:"bg-emerald-500/25 text-emerald-200","decoder-stall":"bg-amber-500/30 text-amber-100","transport-stall":"bg-rose-500/30 text-rose-100","frozen-unknown":"bg-white/15 text-white/70"};function yt({label:e,value:t,window:a,strong:r=!1}){return v.jsxs("div",{className:"flex items-baseline justify-between gap-2 leading-[1.25]",children:[v.jsx("span",{className:"text-white/55 shrink-0",children:e}),v.jsxs("span",{className:"flex items-baseline gap-1 text-right",children:[v.jsx("span",{className:r?"text-white font-semibold tabular-nums":"text-white/90 tabular-nums",children:t}),a!==void 0&&v.jsx("span",{className:"text-sky-300/80 tabular-nums",children:a})]})]})}function zh({title:e,measuredAt:t,now:a}){const r=t!==null&&a-t>CL;return v.jsxs("div",{className:"flex items-baseline justify-between gap-3 mt-2 first:mt-0 pb-0.5 border-b border-white/20",children:[v.jsx("span",{className:"text-white/80 font-semibold tracking-wide uppercase text-[9px]",children:e}),v.jsxs("span",{className:r?"text-amber-300 text-[9px]":"text-white/45 text-[9px]",children:[r?"STALE · ":"",KS(t,a)]})]})}var KTe={unknown:"bg-white/50",decoding:"bg-emerald-400","decoder-stall":"bg-amber-400","transport-stall":"bg-rose-400","frozen-unknown":"bg-white/50"};function GTe(e){const{stats:t,server:a,serverError:r,serverWired:c,now:m,sessionId:d}=e,h=ML(t),f=t?.window,[k,x]=P.useState(!1),E=t!==null&&m-t.at>CL;return k?v.jsxs("div",{className:"absolute bottom-10 left-2 z-20 transform-gpu w-[13.5rem] max-h-[70%] overflow-y-auto rounded-md bg-neutral-950/95 ring-1 ring-white/25 shadow-lg px-1.5 py-1 text-[9px] font-mono text-white/90 select-text","data-testid":"stream-debug-overlay",children:[v.jsx("button",{type:"button",onClick:()=>x(!1),className:`w-full text-left rounded px-1.5 py-0.5 mb-1 text-[9px] font-semibold ${VTe[h.kind]}`,children:h.label}),v.jsx(zh,{title:"decode",measuredAt:t?.at??null,now:m}),v.jsx(yt,{label:"framesDecoded",value:ia(t?.framesDecoded),window:f?.framesDecoded===null?void 0:`+${ia(f?.framesDecoded)}`,strong:!0}),v.jsx(yt,{label:"freezeCount",value:ia(t?.freezeCount),strong:!0}),v.jsx(yt,{label:"frozen",value:ia(t?.totalFreezeMs,{suffix:"ms"}),window:f?.freezeMs===null?void 0:`+${ia(f?.freezeMs)}ms`,strong:!0}),v.jsx(yt,{label:"pliCount",value:ia(t?.pliCount),window:f?.pliCount===null?void 0:`+${ia(f?.pliCount)}`,strong:!0}),v.jsx(yt,{label:"framesDropped",value:ia(t?.framesDropped)}),v.jsx(yt,{label:"decode",value:ia(t?.avgDecodeMs,{digits:1,suffix:"ms"}),window:f?.decodeMs===null?void 0:`${ia(f?.decodeMs,{digits:1})}ms`}),v.jsx(zh,{title:"picture",measuredAt:t?.at??null,now:m}),v.jsx(yt,{label:"resolution",value:t?.width!==null&&t?.width!==void 0&&t.height!==null?`${t.width}×${t.height}`:ol}),v.jsx(yt,{label:"fps",value:ia(t?.fps)}),v.jsx(yt,{label:"codec",value:t?.codec===null||t?.codec===void 0?ol:`${t.codec}${t.codecProfileLevelId!==null?` ${t.codecProfileLevelId}`:""}`}),(t?.resolutionLog.length??0)>1&&v.jsx("div",{className:"mt-0.5 text-white/60 leading-tight",children:t?.resolutionLog.map(R=>v.jsxs("div",{className:"flex justify-between",children:[v.jsxs("span",{children:[R.width,"×",R.height]}),v.jsx("span",{className:"text-white/40",children:KS(R.at,m)})]},`${R.at}-${R.width}x${R.height}`))}),v.jsx(zh,{title:"transport",measuredAt:t?.at??null,now:m}),v.jsx(yt,{label:"bitrate",value:ia(f?.kbps,{suffix:" kbps"})}),v.jsx(yt,{label:"rtt",value:ia(t?.rttMs,{digits:0,suffix:"ms"})}),v.jsx(yt,{label:"jitter",value:ia(t?.jitterMs,{digits:1,suffix:"ms"})}),v.jsx(yt,{label:"packetsLost",value:ia(t?.packetsLost),window:f?.packetsLost===null?void 0:`+${ia(f?.packetsLost)}`}),v.jsx(yt,{label:"loss",value:ia(t?.lossPercent,{digits:2,suffix:"%"}),window:f?.lossPercent===null?void 0:ia(f?.lossPercent,{digits:2,suffix:"%"})}),v.jsx(yt,{label:"nackCount",value:ia(t?.nackCount),window:f?.nackCount===null?void 0:`+${ia(f?.nackCount)}`}),v.jsx(yt,{label:"candidate pair",value:Yi(t?.candidatePairType)}),v.jsx(yt,{label:"protocol",value:Yi(t?.candidateProtocol)}),v.jsx(yt,{label:"ice",value:Yi(t?.iceConnectionState)}),v.jsx(yt,{label:"dtls",value:Yi(t?.dtlsState)}),v.jsx(zh,{title:"server",measuredAt:a?.observedAt??null,now:m}),c?r!==null?v.jsx("div",{className:"text-rose-300 leading-tight py-0.5 break-words",children:r}):a===null?v.jsx("div",{className:"text-white/50 leading-tight py-0.5",children:"waiting for the first answer…"}):a.alive?v.jsxs(v.Fragment,{children:[v.jsx(yt,{label:"served rung",value:Yi(a.servedTier),strong:!0}),v.jsx(yt,{label:"adaptive",value:jh(a.adaptive)}),v.jsx(yt,{label:"source",value:Yi(a.camStreamId)}),v.jsx(yt,{label:"source kind",value:a.sourceKind}),v.jsx(yt,{label:"ingest node",value:Yi(a.ingestNodeId)}),v.jsx(yt,{label:"· remote",value:jh(a.ingestIsRemote)}),v.jsx(yt,{label:"egress leg",value:a.egressLeg,strong:!0}),v.jsx(yt,{label:"codec src→out",value:`${Yi(a.sourceCodec)}→${Yi(a.negotiatedCodec)}`}),v.jsx(yt,{label:"broker",value:Yi(a.brokerStatus)}),v.jsx(yt,{label:"· bitrate",value:ia(a.brokerBitrateKbps,{suffix:" kbps"})}),v.jsx(yt,{label:"· input fps",value:ia(a.brokerInputFps)}),v.jsx(yt,{label:"rtp sent",value:ia(a.rtpPacketsSent)}),v.jsx(yt,{label:"track mode",value:Yi(a.trackMode)}),a.lastDecision===null?v.jsx(yt,{label:"ladder",value:a.climbHold?"held":"never moved"}):v.jsxs(v.Fragment,{children:[v.jsx(yt,{label:"ladder move",value:`${a.lastDecision.causeDetail??a.lastDecision.cause}${a.lastDecision.tier!==null?` → ${a.lastDecision.tier}`:""}`,strong:!0}),v.jsx(yt,{label:"· when",value:KS(a.lastDecision.at,m)}),v.jsx(yt,{label:"· lossRatio",value:ia(a.lastDecision.lossRatio,{digits:4})}),v.jsx(yt,{label:"· clientKbps",value:ia(a.lastDecision.clientKbps,{suffix:" kbps"})}),v.jsx(yt,{label:"· stalledFor",value:ia(a.lastDecision.stalledForMs,{suffix:"ms"})}),v.jsx(yt,{label:"· serverSending",value:jh(a.lastDecision.serverSending)}),v.jsx(yt,{label:"· transcode-down",value:jh(a.lastDecision.forcedTranscodeDown)})]}),a.climbHold?v.jsx(yt,{label:"climb",value:a.climbHold.summary}):null,v.jsx(yt,{label:"promotions",value:ia(a.upgradeCount)}),a.tierFailures.length>0&&v.jsx(yt,{label:"tier failures",value:a.tierFailures.map(R=>`${R.tier}:${R.failures}`).join(" ")})]}):v.jsx("div",{className:"text-amber-300 leading-tight py-0.5",children:"session not found on the server — it ended, or this node never had it"}):v.jsxs("div",{className:"text-amber-300/90 leading-tight py-0.5",children:["not wired on this surface — this player was mounted without",v.jsx("span",{className:"text-white/80",children:" getSessionDebug"}),", so the server half cannot be asked"]}),d!==null&&v.jsx("div",{className:"mt-1 pt-0.5 border-t border-white/15 text-white/40 break-all leading-tight",children:d})]}):v.jsxs("button",{type:"button",onClick:()=>x(!0),className:"absolute bottom-10 left-2 z-20 transform-gpu flex items-center gap-1.5 rounded bg-neutral-950/90 ring-1 ring-white/20 px-1.5 py-0.5 text-[9px] font-mono text-white/85 tabular-nums select-text","data-testid":"stream-debug-pill",title:h.label,children:[v.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${KTe[h.kind]}`}),v.jsx("span",{children:t?.width!==null&&t?.width!==void 0?`${t.width}×${t.height}`:ol}),v.jsxs("span",{children:[ia(t?.fps),"fps"]}),v.jsxs("span",{children:[ia(f?.kbps),"k"]}),E&&v.jsx("span",{className:"text-amber-300",children:"stale"})]})}function Gs(e,t){e.muted=t;const a=e.srcObject;if(a instanceof MediaStream)for(const r of a.getAudioTracks())r.enabled=!t}function WTe(){return typeof window>"u"?!1:window.matchMedia("(hover: none) and (pointer: coarse)").matches||typeof navigator<"u"&&navigator.maxTouchPoints>0||"ontouchstart"in window}function ZTe(e,t,a){let d=0;for(let h=0;h<8;h++)for(let f=0;f<8;f++){const k=Math.min(t-1,Math.floor((f+.5)/8*t)),x=Math.min(a-1,Math.floor((h+.5)/8*a)),{data:E}=e.getImageData(k,x,1,1);.2126*(E[0]??0)+.7152*(E[1]??0)+.0722*(E[2]??0)>12&&d++}return d<=1}function E1(e){const t={};if(typeof window<"u"){const a=window.devicePixelRatio||1;if(e){const r=e.getBoundingClientRect();r.width>0&&r.height>0&&(t.viewportWidth=Math.round(r.width*a),t.viewportHeight=Math.round(r.height*a))}t.viewportWidth===void 0&&(t.viewportWidth=Math.round(window.innerWidth*a),t.viewportHeight=Math.round(window.innerHeight*a)),t.devicePixelRatio=a}return t}var Jf=TTe({now:()=>Date.now(),ttlMs:3e4});function tl(e){return MTe(e,typeof window<"u"?L4e():void 0)}function GS(e,t,a){const r=tl(e);return r===null?Promise.resolve(void 0):Jf.measured(r,()=>ITe(r,{onRefused:c=>{Jf.firstRefusal(r,c)&&a(r,c)},fetchImpl:(c,m)=>fetch(c,{...m,...t!==null?{headers:{authorization:`Bearer ${t}`}}:{}}),now:()=>Date.now()}))}function YTe(e){const t=tl(e);return t===null?void 0:Jf.cached(t)}function XTe(e){const t=tl(e);return t===null?null:Jf.latest(t)}function R4(e){return RTe({waitFrame:()=>ETe({readyState:()=>{const t=e.video();return t!==null&&t.srcObject===e.stream?t.readyState:null},signal:e.signal,sleep:t=>new Promise(a=>setTimeout(a,t)),now:()=>Date.now()}),measure:()=>GS(e.serverUrl,e.authToken,e.onRefused)})}function T4(e,t,a,r){const c={...e,...a!==void 0?{downlinkMbps:a}:{},...t};return r?xTe(c):c}var JTe=8e3;function AL({serverUrl:e,streamKey:t,label:a,autoPlay:r=!0,muted:c=!0,showControls:m=!0,showStats:d=!1,onDebugStats:h,onPlaybackStats:f,onClientNetworkSample:k,probeAuthToken:x,onConnectTiming:E,className:R="",onStateChange:T,onError:N,onReconnectAttempt:j,overlay:q,createSession:B,sendAnswer:F,handleOffer:U,getIceServers:H,addIceCandidate:Q,getIceCandidates:te,closeSession:K,getSessionState:W,getSessionDebug:oe,applyDownlinkProbe:he,reoffer:Ae,posterUrl:we,hintsOverride:Ee,onAdaptiveHints:Ie,reconnectSignal:Me,onControlChannel:Y,onVideoElement:de,iceTransportPolicy:Re,onPeerConnection:Qe}){const re=P.useRef(null),V=P.useRef(null),ie=P.useRef(null),fe=P.useRef(new Set),be=P.useRef(null),ee=P.useRef(null),Se=P.useRef(0),_e=P.useRef(!0),Be=P.useRef(Y);Be.current=Y;const Ge=P.useRef(Re);Ge.current=Re;const Ft=P.useRef(Qe);Ft.current=Qe;const Ot=P.useRef(de);Ot.current=de,P.useEffect(()=>(Ot.current?.(re.current),()=>Ot.current?.(null)),[]);const wt=P.useRef(Ie);wt.current=Ie;const sa=P.useRef(null),nt=P.useCallback((me,Ve,u)=>{const dt=wt.current;if(!dt)return;const tt={phase:me,probeOrigin:u,...Ve},pt=CTe(tt);pt!==sa.current&&(sa.current=pt,dt(tt))},[]),za=P.useRef(he);za.current=he;const ft=P.useCallback(async(me,Ve,u)=>{const dt=await _Te(za.current,me,Ve);if(!_e.current)return;if(dt.kind==="unsupported"){u();return}const{outcome:tt,tier:pt,reason:at}=dt.answer;wt.current?.({phase:"probe-in-session",probeOrigin:tl(e),downlinkMbps:Ve,probeAnswer:`${tt}:${pt??"-"}:${at}`})},[e]),lt=P.useCallback((me,Ve)=>{wt.current?.({phase:"probe-refused",probeOrigin:me,probeStatus:Ve})},[]),Dt=P.useRef(null),bt=P.useRef(null),ve=P.useRef(0),Fe=P.useRef(!1),Le=P.useRef(!1),ot=P.useRef(async()=>{}),[He,ea]=P.useState("idle"),[$t,ze]=P.useState(""),[st,Lt]=P.useState(c),Kt=P.useRef(st);Kt.current=st;const[qa,fn]=P.useState(!1),[ct,Ut]=P.useState(!1),La=WTe(),[Sa,Di]=P.useState(!0),Zn=P.useRef(null),ji=P.useRef(!1);(F||B)&&(ji.current=!0);const gn=ji.current,Pn=P.useRef(!1);U&&(Pn.current=!0);const vn=Pn.current,[xe,Oe]=P.useState(!1),xt=P.useRef(null),[ha,xn]=P.useState(null),[Yn,gi]=P.useState(!1),Mr=P.useCallback(()=>{const me=re.current;if(!(!me||me.readyState<2||!me.videoWidth||!me.videoHeight))try{const Ve=document.createElement("canvas");Ve.width=me.videoWidth,Ve.height=me.videoHeight;const u=Ve.getContext("2d");if(!u||(u.drawImage(me,0,0),ZTe(u,Ve.width,Ve.height)))return;xt.current=Ve.toDataURL("image/jpeg",.6)}catch{}},[]),fa=P.useCallback(me=>{ea(me),me==="playing"&&Oe(!0),T?.(me)},[T]),Mn=P.useCallback(()=>{if(be.current?.abort(),be.current=null,ee.current&&(clearTimeout(ee.current),ee.current=null),bt.current&&(clearTimeout(bt.current),bt.current=null),Dt.current=null,Le.current=!1,ve.current=0,ie.current&&(ie.current.close(),ie.current=null),K&&fe.current.size>0){for(const me of fe.current)K(me).catch(()=>{});fe.current.clear()}},[K]),zi=P.useCallback(()=>{be.current?.abort(),be.current=null,ee.current&&(clearTimeout(ee.current),ee.current=null),bt.current&&(clearTimeout(bt.current),bt.current=null),Dt.current=null,Le.current=!1,ve.current=0},[]),nr=1e3,Xn=P.useCallback(me=>{if(!W||!Ae)return;bt.current&&(clearTimeout(bt.current),bt.current=null);const Ve=async()=>{if(_e.current&&Dt.current===me){if(!Le.current)try{const{pendingRenegotiation:u}=await W(me);if(_e.current&&Dt.current===me&&u&&u.epoch>ve.current&&!Le.current){ve.current=u.epoch,await ot.current(me,u.target);return}}catch{}!_e.current||Dt.current!==me||(bt.current=setTimeout(()=>{Ve()},nr))}};bt.current=setTimeout(()=>{Ve()},nr)},[W,Ae]),ir=P.useCallback(async(me=!1,Ve=me,u)=>{if(!_e.current||!B||!F)return;const dt=me?ie.current:null,tt=me?new Set(fe.current):null;me?zi():Mn(),fa("connecting");const pt=new AbortController;be.current=pt;try{const at=T4(E1(V.current),Ee,Ve?u??await GS(e,x??null,lt):void 0,!Ve);nt(Ve?"probe-climb":"cold-start",at,tl(e));const{sessionId:At,sdpOffer:It,iceServers:Fa}=await B(at);if(fe.current.add(At),!_e.current||pt.signal.aborted){K?.(At).catch(()=>{}),fe.current.delete(At);return}const mt=new RTCPeerConnection(I1(Fa,Ge.current));Ft.current?.(mt),me||(ie.current=mt);const Va=new MediaStream;Ve||R4({video:()=>re.current,stream:Va,signal:pt.signal,serverUrl:e,authToken:x??null,onRefused:lt}).then(gt=>{gt===void 0||!C4(gt)||!_e.current||pt.signal.aborted||Fe.current||(Fe.current=!0,ft(At,gt,()=>{!_e.current||pt.signal.aborted||ir(!0,!0,gt)}))});let Vt=!1;const Aa=()=>{if(!(Vt||!_e.current)){if(Vt=!0,ie.current=mt,re.current&&(re.current.srcObject=Va,Gs(re.current,Kt.current),re.current.play().catch(()=>{})),dt&&dt!==mt)try{dt.close()}catch{}if(tt)for(const gt of tt)fe.current.delete(gt),K?.(gt).catch(()=>{})}};mt.ontrack=gt=>{if(console.debug("[WebRTC] ontrack",gt.track.kind,gt.track.readyState),Va.addTrack(gt.track),me){Aa();return}re.current&&(re.current.srcObject=Va,Gs(re.current,Kt.current),re.current.play().catch(()=>{}))},mt.oniceconnectionstatechange=()=>{if(!_e.current)return;const gt=mt.iceConnectionState;if(console.debug("[WebRTC] ICE state:",gt),gt==="connected"||gt==="completed")Se.current=0,me&&Aa(),fa("playing"),re.current?.paused&&(console.debug("[WebRTC] video was paused at ICE connected — calling play()"),re.current.play().catch(()=>{}));else if(gt==="failed"||gt==="disconnected"||gt==="closed"){if(me&&!Vt)try{mt.close()}catch{}fa("disconnected"),Nn()}},mt.onicecandidateerror=gt=>{console.debug("[WebRTC] ICE candidate error:",gt)},console.debug("[WebRTC] Setting remote description (server offer)..."),await mt.setRemoteDescription({type:"offer",sdp:It});const Dn=await mt.createAnswer();if(await mt.setLocalDescription(Dn),console.debug("[WebRTC] Local description set, waiting for ICE gathering..."),await _4(mt),!_e.current)return;const Ka=(mt.localDescription?.sdp??"").split(`
83
+ ${w6(this.remoteInfo)}`),this.remoteEntryExports=t,this.remoteEntryExports}async init(e,t,a,r){const c=await this.getEntry(r);if(this.inited)return await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:c,cached:!0,origin:this.host}),c;if(this.initPromise){try{await this.initPromise,await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:c,cached:!0,origin:this.host})}catch(m){throw await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:c,error:m,cached:!0,origin:this.host}),m}return c}this.initing=!0,this.initPromise=(async()=>{await this.host.loaderHook.lifecycle.beforeInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,origin:this.host});const{remoteEntryInitOptions:m,shareScope:d,initScope:h}=C4e(this.remoteInfo,this.host.shareScopeMap,a),f=await this.host.hooks.lifecycle.beforeInitContainer.emit({shareScope:d,remoteEntryInitOptions:m,initScope:h,remoteInfo:this.remoteInfo,origin:this.host});typeof c?.init>"u"&&ka(F6,Kn,{hostName:this.host.name,remoteName:this.remoteInfo.name,remoteEntryUrl:this.remoteInfo.entry,remoteEntryKey:this.remoteInfo.entryGlobalName},void 0,uo(this.host.options));try{await c.init(f.shareScope,f.initScope,f.remoteEntryInitOptions)}catch(k){ka(Y6,Kn,{hostName:this.host.name,remoteName:this.remoteInfo.name,remoteEntryUrl:this.remoteInfo.entry,remoteEntryKey:this.remoteInfo.entryGlobalName,shareScope:this.remoteInfo.shareScope},`${k}`,uo(this.host.options))}await this.host.hooks.lifecycle.initContainer.emit({...f,id:e,remoteSnapshot:t,remoteEntryExports:c}),this.inited=!0})();try{await this.initPromise,await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:c,origin:this.host})}catch(m){throw await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:c,error:m,origin:this.host}),m}finally{this.initing=!1,this.initPromise=void 0}return c}async get(e,t,a,r){const{loadFactory:c=!0}=a||{loadFactory:!0},m=await this.init(e,r,void 0,t);this.lib=m,await this.host.loaderHook.lifecycle.beforeGetExpose.emit({id:e,expose:t,moduleInfo:this.remoteInfo,remoteEntryExports:m,origin:this.host});let d;try{const k=await this.host.loaderHook.lifecycle.getModuleFactory.emit({remoteEntryExports:m,expose:t,moduleInfo:this.remoteInfo});d=typeof k=="function"?k:void 0,d||(d=await m.get(t)),d||ka(Z6,Kn,{hostName:this.host.name,remoteName:this.remoteInfo.name,remoteEntryUrl:this.remoteInfo.entry,expose:t,requestId:e,availableExposes:M4e(r)},void 0,uo(this.host.options)),await this.host.loaderHook.lifecycle.afterGetExpose.emit({id:e,expose:t,moduleInfo:this.remoteInfo,remoteEntryExports:m,moduleFactory:d,origin:this.host})}catch(k){throw await this.host.loaderHook.lifecycle.afterGetExpose.emit({id:e,expose:t,moduleInfo:this.remoteInfo,remoteEntryExports:m,error:k,origin:this.host}),k}const h=xRe(this.remoteInfo.name,t),f=this.wraperFactory(d,h);if(!c)return f;await this.host.loaderHook.lifecycle.beforeExecuteFactory.emit({id:e,expose:t,moduleInfo:this.remoteInfo,loadFactory:c,origin:this.host});try{const k=await f();return await this.host.loaderHook.lifecycle.afterExecuteFactory.emit({id:e,expose:t,moduleInfo:this.remoteInfo,loadFactory:c,exposeModule:k,origin:this.host}),k}catch(k){throw await this.host.loaderHook.lifecycle.afterExecuteFactory.emit({id:e,expose:t,moduleInfo:this.remoteInfo,loadFactory:c,error:k,origin:this.host}),k}}wraperFactory(e,t){function a(r,c){r&&typeof r=="object"&&Object.isExtensible(r)&&!Object.getOwnPropertyDescriptor(r,Symbol.for("mf_module_id"))&&Object.defineProperty(r,Symbol.for("mf_module_id"),{value:c,enumerable:!1})}return()=>{const r=e();return r instanceof Promise?r.then(c=>(a(c,t),c)):(a(r,t),r)}}},Qn=class{constructor(e){this.type="",this.listeners=new Set,e&&(this.type=e)}on(e){typeof e=="function"&&this.listeners.add(e)}once(e){const t=this;this.on(function a(...r){return t.remove(a),e.apply(null,r)})}emit(...e){let t;return this.listeners.size>0&&this.listeners.forEach(a=>{const r=a(...e);r!==void 0&&(t=r)}),t}remove(e){this.listeners.delete(e)}removeAll(){this.listeners.clear()}},Ja=class extends Qn{emit(...e){let t;const a=Array.from(this.listeners);if(a.length>0){let r=0;const c=m=>m===!1?!1:r<a.length?Promise.resolve(a[r++].apply(null,e)).then(d=>d===void 0||e.length===1&&d===e[0]?c(m):c(d)):m;t=c()}return Promise.resolve(t)}};function nL(e,t){if(!gx(t))return!1;if(e!==t){for(const a in e)if(!(a in t))return!1}return!0}var jc=class extends Qn{constructor(e){super(),this.onerror=ka,this.type=e}emit(e){gx(e)||ka(`The data for the "${this.type}" hook should be an object.`);for(const t of this.listeners)try{const a=t(e);if(a===void 0)continue;if(nL(e,a))e=a;else{this.onerror(`A plugin returned an unacceptable value for the "${this.type}" type.`);break}}catch(a){cm(a),this.onerror(a)}return e}},ls=class extends Qn{constructor(e){super(),this.onerror=ka,this.type=e}emit(e){gx(e)||ka(`The response data for the "${this.type}" hook must be an object.`);const t=Array.from(this.listeners);if(t.length>0){let a=0;const r=m=>(cm(m),this.onerror(m),e),c=m=>{if(m!==void 0&&nL(e,m))e=m;else if(m!==void 0)return this.onerror(`A plugin returned an incorrect value for the "${this.type}" type.`),e;if(a<t.length)try{return Promise.resolve(t[a++](e)).then(c,r)}catch(d){return r(d)}return e};return Promise.resolve(c(e))}return Promise.resolve(e)}},zc=class{constructor(e){this.registerPlugins={},this.lifecycle=e,this.lifecycleKeys=Object.keys(e)}applyPlugin(e,t){lo(wRe(e),"Plugin configuration is invalid.");const a=e.name;lo(a,"A name must be provided by the plugin."),this.registerPlugins[a]||(this.registerPlugins[a]=e,e.apply?.(t),Object.keys(this.lifecycle).forEach(r=>{const c=e[r];c&&this.lifecycle[r].on(c)}))}removePlugin(e){lo(e,"A name is required.");const t=this.registerPlugins[e];lo(t,`The plugin "${e}" is not registered.`),Object.keys(t).forEach(a=>{a!=="name"&&this.lifecycle[a].remove(t[a])})}};function iL(e,t){const a=_6(t);a.url||ka(G6,Kn,{remoteName:e.name});let r=LS(t,a.url);!ks&&!r.startsWith("http")&&(r=`https:${r}`),e.type=a.type,e.entryGlobalName=a.globalName,e.entry=r,e.version=t.version,e.buildVersion=t.buildVersion}function A4e(){return{name:"snapshot-plugin",async afterResolve(e){const{remote:t,pkgNameOrAlias:a,expose:r,origin:c,remoteInfo:m,id:d}=e;if(!fx(t)||!R6(t)){const{remoteSnapshot:h,globalSnapshot:f}=await c.snapshotHandler.loadRemoteSnapshotInfo({moduleInfo:t,id:kx(t.name,r)});iL(m,h);const k={remote:t,preloadConfig:{nameOrAlias:a,exposes:[r],resourceCategory:"sync",share:!1,depsRemote:!1}},x=await c.remoteHandler.hooks.lifecycle.generatePreloadAssets.emit({origin:c,preloadOptions:k,remoteInfo:m,remote:t,remoteSnapshot:h,globalSnapshot:f});return x&&tL(m,c,x,!1,{initiator:"loadRemote",id:d}).catch(()=>{}),{...e,remoteSnapshot:h}}return e}}}function I4e(e){const t=e.split(":");return t.length===1?{name:t[0],version:void 0}:t.length===2?{name:t[0],version:t[1]}:{name:t[1],version:t[2]}}function rL(e,t,a,r,c={},m){const{value:d}=Xc(e,Zf(t)),h=m||d;if(h&&!x6(h)&&(a(h,t,r),h.remotesInfo)){const f=Object.keys(h.remotesInfo);for(const k of f){if(c[k])continue;c[k]=!0;const x=I4e(k),E=h.remotesInfo[k];rL(e,{name:x.name,version:E.matchedVersion},a,!1,c,void 0)}}}var M1=(e,t)=>document.querySelector(`${e}[${e==="link"?"href":"src"}="${t}"]`);function E4e(e,t,a,r,c){const m=[],d=[],h=[],f=new Set,k=new Set,{options:x}=e,{preloadConfig:E}=t,{depsRemote:R}=E;if(rL(r,a,(N,j,q)=>{let B;if(q)B=E;else if(Array.isArray(R)){const te=R.find(K=>K.nameOrAlias===j.name||K.nameOrAlias===j.alias);if(!te)return;B=eL(te)}else if(R===!0)B=E;else return;const F=LS(N,_6(N).url);F&&h.push({name:j.name,moduleInfo:{name:j.name,entry:F,type:"remoteEntryType"in N?N.remoteEntryType:"global",entryGlobalName:"globalName"in N?N.globalName:j.name,shareScope:"",version:"version"in N?N.version:void 0},url:F});let U="modules"in N?N.modules:[];const H=S4e(B.exposes);H.length&&"modules"in N&&(U=N?.modules?.reduce((te,K)=>(H?.indexOf(K.moduleName)!==-1&&te.push(K),te),[]));function Q(te){const K=te.map(W=>LS(N,W));return B.filter?K.filter(B.filter):K}if(U){const te=U.length;for(let K=0;K<te;K++){const W=U[K],oe=`${j.name}/${W.moduleName}`;e.remoteHandler.hooks.lifecycle.handlePreloadModule.emit({id:W.moduleName==="."?j.name:oe,name:j.name,remoteSnapshot:N,preloadConfig:B,remote:j,origin:e}),!ERe(oe)&&(B.resourceCategory==="all"?(m.push(...Q(W.assets.css.async)),m.push(...Q(W.assets.css.sync)),d.push(...Q(W.assets.js.async)),d.push(...Q(W.assets.js.sync))):B.resourceCategory==="sync"&&(m.push(...Q(W.assets.css.sync)),d.push(...Q(W.assets.js.sync))),RRe(oe))}}},!0,{},c),c.shared&&c.shared.length>0){const N=(j,q)=>{const{shared:B}=hf(e.shareScopeMap,q.sharedName,j,e.sharedHandler.hooks.lifecycle.resolveShare)||{};B&&typeof B.lib=="function"&&(q.assets.js.sync.forEach(F=>{f.add(F)}),q.assets.css.sync.forEach(F=>{k.add(F)}))};c.shared.forEach(j=>{const q=x.shared?.[j.sharedName];if(!q)return;const B=j.version?q.find(F=>F.version===j.version):q;B&&T6(B).forEach(F=>{N(F,j)})})}const T=d.filter(N=>!f.has(N)&&!M1("script",N));return{cssAssets:m.filter(N=>!k.has(N)&&!M1("link",N)),jsAssetsWithoutEntry:T,entryAssets:h.filter(N=>!M1("script",N.url))}}var R4e=function(){return{name:"generate-preload-assets-plugin",async generatePreloadAssets(e){const{origin:t,preloadOptions:a,remoteInfo:r,remote:c,globalSnapshot:m,remoteSnapshot:d}=e;return ks?fx(c)&&R6(c)?{cssAssets:[],jsAssetsWithoutEntry:[],entryAssets:[{name:c.name,url:c.entry,moduleInfo:{name:r.name,entry:c.entry,type:r.type||"global",entryGlobalName:"",shareScope:""}}]}:(iL(r,d),E4e(t,a,r,m,d)):{cssAssets:[],jsAssetsWithoutEntry:[],entryAssets:[]}}}};function oL(e,t){const a=uf({name:t.name,version:t.options.version}),r=a&&"remotesInfo"in a&&a.remotesInfo&&Xc(a.remotesInfo,e.name).value;return r&&r.matchedVersion?{hostGlobalSnapshot:a,globalSnapshot:h4(),remoteSnapshot:uf({name:e.name,version:r.matchedVersion})}:{hostGlobalSnapshot:void 0,globalSnapshot:h4(),remoteSnapshot:uf({name:e.name,version:"version"in e?e.version:void 0})}}var T4e=class{constructor(e){this.loadingHostSnapshot=null,this.manifestCache=new Map,this.hooks=new zc({beforeLoadRemoteSnapshot:new Ja("beforeLoadRemoteSnapshot"),loadSnapshot:new ls("loadGlobalSnapshot"),loadRemoteSnapshot:new ls("loadRemoteSnapshot"),afterLoadSnapshot:new ls("afterLoadSnapshot")}),this.manifestLoading=dm.__FEDERATION__.__MANIFEST_LOADING__,this.HostInstance=e,this.loaderHook=e.loaderHook}async loadRemoteSnapshotInfo({moduleInfo:e,id:t,initiator:a="loadRemote"}){const{options:r}=this.HostInstance;await this.hooks.lifecycle.beforeLoadRemoteSnapshot.emit({options:r,moduleInfo:e,origin:this.HostInstance});let c=uf({name:this.HostInstance.options.name,version:this.HostInstance.options.version});c||(c={version:this.HostInstance.options.version||"",remoteEntry:"",remotesInfo:{}},ARe({[this.HostInstance.options.name]:c})),c&&"remotesInfo"in c&&!Xc(c.remotesInfo,e.name).value&&("version"in e||"entry"in e)&&(c.remotesInfo={...c?.remotesInfo,[e.name]:{matchedVersion:"version"in e?e.version:e.entry}});const{hostGlobalSnapshot:m,remoteSnapshot:d,globalSnapshot:h}=this.getGlobalRemoteInfo(e),{remoteSnapshot:f,globalSnapshot:k}=await this.hooks.lifecycle.loadSnapshot.emit({options:r,moduleInfo:e,hostGlobalSnapshot:m,remoteSnapshot:d,globalSnapshot:h});let x,E;if(f)if(x6(f)){const R=ks?f.remoteEntry:f.ssrRemoteEntry||f.remoteEntry||"",T=await this.loadManifestSnapshot(R,e,{},{initiator:a,id:t||e.name}),N=f4({...e,entry:R},T);x=T,E=N}else{const{remoteSnapshot:R}=await this.hooks.lifecycle.loadRemoteSnapshot.emit({options:this.HostInstance.options,moduleInfo:e,remoteSnapshot:f,from:"global"});x=R,E=k}else if(fx(e)){const R=await this.loadManifestSnapshot(e.entry,e,{},{initiator:a,id:t||e.name}),T=f4(e,R);x=R,E=T}else ka(Q6,Kn,{remoteName:e.name,remoteVersion:e.version,hostName:this.HostInstance.options.name,globalSnapshot:JSON.stringify(k)},void 0,uo(this.HostInstance.options));return await this.hooks.lifecycle.afterLoadSnapshot.emit({id:t,host:this.HostInstance,options:r,moduleInfo:e,remoteSnapshot:x}),{remoteSnapshot:x,globalSnapshot:E}}getGlobalRemoteInfo(e){return oL(e,this.HostInstance)}async getManifestJson(e,t,a,r){return(async()=>{const m=Ec(t);let d=this.manifestCache.get(e);if(d)return d;try{let f=await this.loaderHook.lifecycle.fetch.emit(e,{},m,r?{...r,url:e,resourceType:"manifest"}:void 0);(!f||!(f instanceof Response))&&(f=await fetch(e,{})),d=await f.json()}catch(f){d=await this.HostInstance.remoteHandler.hooks.lifecycle.errorLoadRemote.emit({id:e,error:f,from:"runtime",lifecycle:"afterResolve",remote:m,origin:this.HostInstance}),d||(delete this.manifestLoading[e],ka($6,Kn,{manifestUrl:e,moduleName:t.name,hostName:this.HostInstance.options.name},`${f}`,uo(this.HostInstance.options)))}const h=[!d.metaData&&"metaData",!d.exposes&&"exposes",!d.shared&&"shared"].filter(Boolean);return h.length>0&&await this.HostInstance.remoteHandler.hooks.lifecycle.errorLoadRemote.emit({id:e,error:new Error(`"${e}" is not a valid federation manifest for remote "${t.name}". Missing required fields: ${h.join(", ")}.`),from:"runtime",lifecycle:"afterResolve",remote:m,origin:this.HostInstance}),h.length>0&&ka(W6,Kn,{manifestUrl:e,moduleName:t.name,hostName:this.HostInstance.options.name,missingFields:h.join(",")},void 0,uo(this.HostInstance.options)),this.manifestCache.set(e,d),d})()}async loadManifestSnapshot(e,t,a,r){const c=async()=>{const m=await this.getManifestJson(e,t,a,r),d=sRe(m,{version:e}),{remoteSnapshot:h}=await this.hooks.lifecycle.loadRemoteSnapshot.emit({options:this.HostInstance.options,moduleInfo:t,manifestJson:m,remoteSnapshot:d,manifestUrl:e,from:"manifest"});return h};return this.manifestLoading[e]||(this.manifestLoading[e]=c().then(m=>m)),this.manifestLoading[e]}},_4e=class{constructor(e){this.hooks=new zc({beforeRegisterShare:new jc("beforeRegisterShare"),afterResolve:new ls("afterResolve"),beforeLoadShare:new ls("beforeLoadShare"),loadShare:new Ja,afterLoadShare:new Qn("afterLoadShare"),errorLoadShare:new Qn("errorLoadShare"),resolveShare:new jc("resolveShare"),initContainerShareScopeMap:new jc("initContainerShareScopeMap")}),this.host=e,this.shareScopeMap={},this.initTokens={},this._setGlobalShareScopeMap(e.options)}emitAfterLoadShare({lifecycle:e,pkgName:t,shareInfo:a,selectedShared:r}){try{this.hooks.lifecycle.afterLoadShare.emit({pkgName:t,shareInfo:a,selectedShared:r,shared:this.host.options.shared,shareScopeMap:this.shareScopeMap,lifecycle:e,origin:this.host})}catch(c){cm(c)}}emitErrorLoadShare({lifecycle:e,pkgName:t,shareInfo:a,error:r,recovered:c}){try{this.hooks.lifecycle.errorLoadShare.emit({pkgName:t,shareInfo:a,shared:this.host.options.shared,shareScopeMap:this.shareScopeMap,lifecycle:e,origin:this.host,error:r,recovered:c})}catch(m){cm(m)}}registerShared(e,t){const{newShareInfos:a,allShareInfos:r}=q6(e,t);return Object.keys(a).forEach(c=>{a[c].forEach(m=>{m.scope.forEach(d=>{this.hooks.lifecycle.beforeRegisterShare.emit({origin:this.host,pkgName:c,shared:m}),this.shareScopeMap[d]?.[c]||this.setShared({pkgName:c,lib:m.lib,get:m.get,loaded:m.loaded||!!m.lib,shared:m,from:t.name})})})}),{newShareInfos:a,allShareInfos:r}}async loadShare(e,t){const{host:a}=this,r=S4({pkgName:e,extraOptions:t,shareInfos:a.options.shared});let c=r;try{r?.scope&&await Promise.all(r.scope.map(async f=>{await Promise.all(this.initializeSharing(f,{strategy:r.strategy}))})),c=(await this.hooks.lifecycle.beforeLoadShare.emit({pkgName:e,shareInfo:r,shared:a.options.shared,origin:a})).shareInfo,lo(c,`Cannot find shared "${e}" in host "${a.options.name}". Ensure the shared config for "${e}" is declared in the federation plugin options and the host has been initialized before loading shares.`);const m=c,{shared:d,useTreesShaking:h}=hf(this.shareScopeMap,e,c,this.hooks.lifecycle.resolveShare)||{};if(d){const f=Dh(d,h);if(f.lib)return uc(f,a.options.name),this.emitAfterLoadShare({lifecycle:"loadShare",pkgName:e,shareInfo:m,selectedShared:d}),f.lib;if(f.loading&&!f.loaded){const k=await f.loading;return f.loaded=!0,f.lib||(f.lib=k),uc(f,a.options.name),this.emitAfterLoadShare({lifecycle:"loadShare",pkgName:e,shareInfo:m,selectedShared:d}),k}else{const x=(async()=>{const R=await f.get();return uc(f,a.options.name),f.loaded=!0,f.lib=R,R})();this.setShared({pkgName:e,loaded:!1,shared:d,from:a.options.name,lib:null,loading:x,treeShaking:h?f:void 0});const E=await x;return this.emitAfterLoadShare({lifecycle:"loadShare",pkgName:e,shareInfo:m,selectedShared:d}),E}}else{if(t?.customShareInfo)return this.emitErrorLoadShare({lifecycle:"loadShare",pkgName:e,shareInfo:m,recovered:!0}),!1;const f=um(m.treeShaking),k=Dh(m,f),E=(async()=>{const T=await k.get();k.lib=T,k.loaded=!0,uc(k,a.options.name);const{shared:N,useTreesShaking:j}=hf(this.shareScopeMap,e,m,this.hooks.lifecycle.resolveShare)||{};if(N){const q=Dh(N,j);q.lib=T,q.loaded=!0,N.from=m.from}return T})();this.setShared({pkgName:e,loaded:!1,shared:m,from:a.options.name,lib:null,loading:E,treeShaking:f?k:void 0});const R=await E;return this.emitAfterLoadShare({lifecycle:"loadShare",pkgName:e,shareInfo:m,selectedShared:m}),R}}catch(m){throw this.emitErrorLoadShare({lifecycle:"loadShare",pkgName:e,shareInfo:c,error:m}),m}}initializeSharing(e=Hg,t){const{host:a}=this,r=t?.from,c=t?.strategy;let m=t?.initScope;const d=[];if(r!=="build"){const{initTokens:R}=this;m||(m=[]);let T=R[e];if(T||(T=R[e]={from:this.host.name}),m.indexOf(T)>=0)return d;m.push(T)}const h=this.shareScopeMap,f=a.options.name;h[e]||(h[e]={});const k=h[e],x=(R,T)=>{const{version:N,eager:j}=T;k[R]=k[R]||{};const q=k[R],B=q[N]&&Dh(q[N]),F=!!(B&&("eager"in B&&B.eager||"shareConfig"in B&&B.shareConfig?.eager));(!B||B.strategy!=="loaded-first"&&!B.loaded&&(!j!=!F?j:f>q[N].from))&&(q[N]=T)},E=async R=>{const{module:T}=await a.remoteHandler.getRemoteModuleAndOptions({id:R});let N;try{N=await T.getEntry()}catch(j){if(N=await a.remoteHandler.hooks.lifecycle.errorLoadRemote.emit({id:R,error:j,from:"runtime",lifecycle:"beforeLoadShare",remote:T.remoteInfo,origin:a}),!N)return}finally{N?.init&&!T.initing&&(T.remoteEntryExports=N,await T.init(void 0,void 0,m))}};return Object.keys(a.options.shared).forEach(R=>{a.options.shared[R].forEach(T=>{T.scope.includes(e)&&x(R,T)})}),(a.options.shareStrategy==="version-first"||c==="version-first")&&a.options.remotes.forEach(R=>{R.shareScope===e&&d.push(E(R.name))}),d}loadShareSync(e,t){const{host:a}=this,r=S4({pkgName:e,extraOptions:t,shareInfos:a.options.shared});try{r?.scope&&r.scope.forEach(m=>{this.initializeSharing(m,{strategy:r.strategy})});const{shared:c}=hf(this.shareScopeMap,e,r,this.hooks.lifecycle.resolveShare)||{};if(c){if(typeof c.lib=="function")return uc(c,a.options.name),c.loaded||(c.loaded=!0,c.from===a.options.name&&(r.loaded=!0)),this.emitAfterLoadShare({lifecycle:"loadShareSync",pkgName:e,shareInfo:r,selectedShared:c}),c.lib;if(typeof c.get=="function"){const m=c.get();if(!(m instanceof Promise))return uc(c,a.options.name),this.setShared({pkgName:e,loaded:!0,from:a.options.name,lib:m,shared:c}),this.emitAfterLoadShare({lifecycle:"loadShareSync",pkgName:e,shareInfo:r,selectedShared:c}),m}}if(r.lib)return r.loaded||(r.loaded=!0),this.emitAfterLoadShare({lifecycle:"loadShareSync",pkgName:e,shareInfo:r,selectedShared:r}),r.lib;if(r.get){const m=r.get();return m instanceof Promise&&ka(t?.from==="build"?H6:US,Kn,{hostName:a.options.name,sharedPkgName:e},void 0,uo(a.options)),r.lib=m,this.setShared({pkgName:e,loaded:!0,from:a.options.name,lib:r.lib,shared:r}),this.emitAfterLoadShare({lifecycle:"loadShareSync",pkgName:e,shareInfo:r,selectedShared:r}),r.lib}ka(US,Kn,{hostName:a.options.name,sharedPkgName:e},void 0,uo(a.options))}catch(c){throw this.emitErrorLoadShare({lifecycle:"loadShareSync",pkgName:e,shareInfo:r,error:c}),c}}initShareScopeMap(e,t,a={}){const{host:r}=this;this.shareScopeMap[e]=t,this.hooks.lifecycle.initContainerShareScopeMap.emit({shareScope:t,options:r.options,origin:r,scopeName:e,hostShareScopeMap:a.hostShareScopeMap})}setShared({pkgName:e,shared:t,from:a,lib:r,loading:c,loaded:m,get:d,treeShaking:h}){const{version:f,scope:k="default",...x}=t,E=Array.isArray(k)?k:[k],R=T=>{const N=(q,B,F)=>{F&&!q[B]&&(q[B]=F)},j=h?T.treeShaking:T;N(j,"loaded",m),N(j,"loading",c),N(j,"get",d)};E.forEach(T=>{this.shareScopeMap[T]||(this.shareScopeMap[T]={}),this.shareScopeMap[T][e]||(this.shareScopeMap[T][e]={}),this.shareScopeMap[T][e][f]||(this.shareScopeMap[T][e][f]={version:f,scope:[T],...x,lib:r});const N=this.shareScopeMap[T][e][f];R(N),a&&N.from!==a&&(N.from=a)})}_setGlobalShareScopeMap(e){const t=L6(),a=e.id||e.name;a&&!t[a]&&(t[a]=this.shareScopeMap)}},P4e=class{constructor(e){this.hooks=new zc({beforeRegisterRemote:new jc("beforeRegisterRemote"),registerRemote:new jc("registerRemote"),beforeRequest:new ls("beforeRequest"),afterMatchRemote:new Ja("afterMatchRemote"),onLoad:new Ja("onLoad"),afterLoadRemote:new Ja("afterLoadRemote"),handlePreloadModule:new Qn("handlePreloadModule"),errorLoadRemote:new Ja("errorLoadRemote"),beforePreloadRemote:new Ja("beforePreloadRemote"),generatePreloadAssets:new Ja("generatePreloadAssets"),afterPreloadRemote:new Ja("afterPreloadRemote"),loadEntry:new Ja}),this.host=e,this.idToRemoteMap={}}formatAndRegisterRemote(e,t){return(t.remotes||[]).reduce((a,r)=>(this.registerRemote(r,a,{force:!1}),a),e.remotes)}setIdToRemoteMap(e,t){const{remote:a,expose:r}=t,{name:c,alias:m}=a;if(this.idToRemoteMap[e]={name:a.name,expose:r},m&&e.startsWith(c)){const d=e.replace(c,m);this.idToRemoteMap[d]={name:a.name,expose:r};return}if(m&&e.startsWith(m)){const d=e.replace(m,c);this.idToRemoteMap[d]={name:a.name,expose:r}}}async loadRemote(e,t){const{host:a}=this,r=w4(a.options.remotes,e);let c=e,m=r?.expose,d=r?Ec(r.remote):void 0,h;try{const{loadFactory:f=!0}=t||{loadFactory:!0},{module:k,moduleOptions:x,remoteMatchInfo:E}=await this.getRemoteModuleAndOptions({id:e}),{pkgNameOrAlias:R,remote:T,expose:N,id:j,remoteSnapshot:q}=E;c=j,m=N,d=Ec(T);const B=await k.get(j,N,t,q),F=await this.hooks.lifecycle.onLoad.emit({id:j,pkgNameOrAlias:R,expose:N,exposeModule:f?B:void 0,exposeModuleFactory:f?void 0:B,remote:T,options:x,moduleInstance:k,origin:a});return this.setIdToRemoteMap(e,E),h={id:c,expose:m,remote:d,options:t,origin:a},typeof F=="function"?F:B}catch(f){const{from:k="runtime"}=t||{from:"runtime"};let x;try{x=await this.hooks.lifecycle.errorLoadRemote.emit({id:e,error:f,from:k,lifecycle:"onLoad",expose:m,remote:d,origin:a})}catch(E){throw h={id:c,expose:m,remote:d,options:t,error:E,origin:a},E}if(!x)throw h={id:c,expose:m,remote:d,options:t,error:f,origin:a},f;return h={id:c,expose:m,remote:d,options:t,error:f,origin:a,recovered:!0},x}finally{h&&await this.hooks.lifecycle.afterLoadRemote.emit(h)}}async preloadRemote(e){const{host:t}=this,a=[];await this.hooks.lifecycle.beforePreloadRemote.emit({preloadOps:e,options:t.options,origin:t});const r=k4e(t.options.remotes,e),c=h=>{const{preloadConfig:f,remote:k}=h,x=f.exposes||[];return x.length?x.map(E=>({ops:{...h,preloadConfig:{...f,exposes:[E]}},id:kx(k.name,E)})):[{ops:h,id:`${k.name}/*`}]};let m;await Promise.all(r.flatMap(c).map(async h=>{const{ops:f,id:k}=h,{remote:x,preloadConfig:E}=f,R=Ec(x);try{const{globalSnapshot:T,remoteSnapshot:N}=await t.snapshotHandler.loadRemoteSnapshotInfo({moduleInfo:x,id:k,initiator:"preloadRemote"}),j=await this.hooks.lifecycle.generatePreloadAssets.emit({origin:t,preloadOptions:f,remote:x,remoteInfo:R,globalSnapshot:T,remoteSnapshot:N});if(!j)return;const q=await tL(R,t,j,!0,{initiator:"preloadRemote",id:k});a.push({remote:x,remoteInfo:R,preloadConfig:E,id:k,results:q})}catch(T){a.push({remote:x,remoteInfo:R,preloadConfig:E,id:k,results:[{url:R.entry,status:"error",resourceType:/\.json(?:$|[?#])/i.test(R.entry)?"manifest":"remoteEntry",initiator:"preloadRemote",id:k,error:T}]})}}));const d=a.flatMap(h=>h.results.filter(f=>f.status==="error"||f.status==="timeout"));if(d.length>0&&(m=new Error(`preloadRemote failed to load ${d.length} resource(s).`),Object.assign(m,{results:a,failedResults:d})),await this.hooks.lifecycle.afterPreloadRemote.emit({preloadOps:e,options:t.options,origin:t,results:a,error:m}),m)throw m}registerRemotes(e,t){const{host:a}=this;e.forEach(r=>{this.registerRemote(r,a.options.remotes,{force:t?.force})})}async getRemoteModuleAndOptions(e){const{host:t}=this,{id:a}=e;let r;try{r=await this.hooks.lifecycle.beforeRequest.emit({id:a,options:t.options,origin:t})}catch(T){if(r=await this.hooks.lifecycle.errorLoadRemote.emit({id:a,options:t.options,origin:t,from:"runtime",error:T,lifecycle:"beforeRequest"}),!r)throw T}const{id:c}=r,m=w4(t.options.remotes,c);if(!m)try{ka(U6,Kn,{hostName:t.options.name,requestId:c},void 0,uo(t.options))}catch(T){throw await this.hooks.lifecycle.afterMatchRemote.emit({id:c,options:t.options,error:T,origin:t}),T}const{remote:d}=m,h=Ec(d);await this.hooks.lifecycle.afterMatchRemote.emit({id:c,...m,options:t.options,remoteInfo:h,origin:t});const f=await t.sharedHandler.hooks.lifecycle.afterResolve.emit({id:c,...m,options:t.options,origin:t,remoteInfo:h}),{remote:k,expose:x}=f;lo(k&&x,`The 'beforeRequest' hook was executed, but it failed to return the correct 'remote' and 'expose' values while loading ${c}.`);let E=t.moduleCache.get(k.name);const R={host:t,remoteInfo:h};return E||(E=new aL(R),t.moduleCache.set(k.name,E)),{module:E,moduleOptions:R,remoteMatchInfo:f}}registerRemote(e,t,a){const{host:r}=this,c=()=>{if(e.alias){const d=t.find(h=>e.alias&&(h.name.startsWith(e.alias)||h.alias?.startsWith(e.alias)));lo(!d,`The alias ${e.alias} of remote ${e.name} is not allowed to be the prefix of ${d&&d.name} name or alias`)}"entry"in e&&ks&&typeof window<"u"&&!e.entry.startsWith("http")&&(e.entry=new URL(e.entry,window.location.origin).href),e.shareScope||(e.shareScope=Hg),e.type||(e.type=a4e)};this.hooks.lifecycle.beforeRegisterRemote.emit({remote:e,origin:r});const m=t.find(d=>d.name===e.name);if(!m)c(),t.push(e),this.hooks.lifecycle.registerRemote.emit({remote:e,origin:r});else{const d=[`The remote "${e.name}" is already registered.`,"Please note that overriding it may cause unexpected errors."];a?.force&&(this.removeRemote(m),c(),t.push(e),this.hooks.lifecycle.registerRemote.emit({remote:e,origin:r}),S6(d.join(" ")))}}removeRemote(e){try{const{host:t}=this,{name:a}=e,r=t.options.remotes.findIndex(m=>m.name===a);r!==-1&&t.options.remotes.splice(r,1);const c=t.moduleCache.get(e.name);if(c){const m=c.remoteInfo,d=m.entryGlobalName;hn[d]&&(Object.getOwnPropertyDescriptor(hn,d)?.configurable?delete hn[d]:hn[d]=void 0);const h=HS(c.remoteInfo);Ic[h]&&delete Ic[h],t.snapshotHandler.manifestCache.delete(m.entry);let f=m.buildVersion?k6(m.name,m.buildVersion):m.name;const k=hn.__FEDERATION__.__INSTANCES__.findIndex(E=>m.buildVersion?E.options.id===f:E.name===f);if(k!==-1){const E=hn.__FEDERATION__.__INSTANCES__[k];f=E.options.id||f;const R=L6();let T=!0;const N=[];Object.keys(R).forEach(j=>{const q=R[j];q&&Object.keys(q).forEach(B=>{const F=q[B];F&&Object.keys(F).forEach(U=>{const H=F[U];H&&Object.keys(H).forEach(Q=>{const te=H[Q];te&&typeof te=="object"&&te.from===m.name&&(te.loaded||te.loading?(te.useIn=te.useIn.filter(K=>K!==m.name),te.useIn.length?T=!1:N.push([j,B,U,Q])):N.push([j,B,U,Q]))})})})}),T&&(E.shareScopeMap={},delete R[f]),N.forEach(([j,q,B,F])=>{delete R[j]?.[q]?.[B]?.[F]}),hn.__FEDERATION__.__INSTANCES__.splice(k,1)}const{hostGlobalSnapshot:x}=oL(e,t);if(x){const E=x&&"remotesInfo"in x&&x.remotesInfo&&Xc(x.remotesInfo,e.name).key;E&&(delete x.remotesInfo[E],dm.__FEDERATION__.__MANIFEST_LOADING__[E]&&delete dm.__FEDERATION__.__MANIFEST_LOADING__[E])}t.moduleCache.delete(e.name)}}catch(t){$S.error(`removeRemote failed: ${t instanceof Error?t.message:String(t)}`)}}},N4e=typeof FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN=="boolean"?!FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN:!0,O4e=class{constructor(e){this.hooks=new zc({beforeInit:new jc("beforeInit"),init:new Qn,beforeInitContainer:new ls("beforeInitContainer"),initContainer:new ls("initContainer")}),this.version="2.5.1",this.moduleCache=new Map,this.loaderHook=new zc({getModuleInfo:new Qn,createScript:new Qn,createLink:new Qn,fetch:new Ja,loadEntryError:new Ja,afterLoadEntry:new Ja("afterLoadEntry"),beforeInitRemote:new Ja("beforeInitRemote"),afterInitRemote:new Ja("afterInitRemote"),beforeGetExpose:new Ja("beforeGetExpose"),afterGetExpose:new Ja("afterGetExpose"),beforeExecuteFactory:new Ja("beforeExecuteFactory"),afterExecuteFactory:new Ja("afterExecuteFactory"),getModuleFactory:new Ja}),this.bridgeHook=new zc({beforeBridgeRender:new Qn,afterBridgeRender:new Qn,beforeBridgeDestroy:new Qn,afterBridgeDestroy:new Qn});const t=N4e?[A4e(),R4e()]:[],a={id:v4e(),name:e.name,plugins:t,remotes:[],shared:{},inBrowser:ks};this.name=e.name,this.options=a,this.snapshotHandler=new T4e(this),this.sharedHandler=new _4e(this),this.remoteHandler=new P4e(this),this.shareScopeMap=this.sharedHandler.shareScopeMap,this.registerPlugins([...a.plugins,...e.plugins||[]]),this.options=this.formatOptions(a,e)}initOptions(e){e.name&&e.name!==this.options.name&&ka(E6(K6,Kn)),this.registerPlugins(e.plugins);const t=this.formatOptions(this.options,e);return this.options=t,t}async loadShare(e,t){return this.sharedHandler.loadShare(e,t)}loadShareSync(e,t){return this.sharedHandler.loadShareSync(e,t)}initializeSharing(e=Hg,t){return this.sharedHandler.initializeSharing(e,t)}initRawContainer(e,t,a){const r=Ec({name:e,entry:t}),c=new aL({host:this,remoteInfo:r});return c.remoteEntryExports=a,this.moduleCache.set(e,c),c}async loadRemote(e,t){return this.remoteHandler.loadRemote(e,t)}async preloadRemote(e){return this.remoteHandler.preloadRemote(e)}initShareScopeMap(e,t,a={}){this.sharedHandler.initShareScopeMap(e,t,a)}formatOptions(e,t){const{allShareInfos:a}=q6(e,t),{userOptions:r,options:c}=this.hooks.lifecycle.beforeInit.emit({origin:this,userOptions:t,options:e,shareInfo:a}),m=this.remoteHandler.formatAndRegisterRemote(c,r),{allShareInfos:d}=this.sharedHandler.registerShared(c,r),h=[...c.plugins];r.plugins&&r.plugins.forEach(k=>{h.includes(k)||h.push(k)});const f={...e,...t,plugins:h,remotes:m,shared:d,id:r.id||e.id};return this.hooks.lifecycle.init.emit({origin:this,options:f}),f}registerPlugins(e){const t=y4e(e,this);this.options.plugins=this.options.plugins.reduce((a,r)=>(r&&a&&!a.find(c=>c.name===r.name)&&a.push(r),a),t||[])}registerRemotes(e,t){return this.remoteHandler.registerRemotes(e,t)}registerShared(e){this.sharedHandler.registerShared(this.options,{...this.options,shared:e})}};MRe(O4e);var D4e="camstack-mount",j4e=/^\/(?:[A-Za-z0-9_\-.]+\/)*$/,C1=null;function x4(e){if(e==null||e==="")return null;const t=e.endsWith("/")?e:`${e}/`;return!j4e.test(t)||t.includes("/../")||t.includes("/./")?null:t}function z4e(){if(typeof document>"u")return"/";const e=x4(document.querySelector(`meta[name="${D4e}"]`)?.getAttribute("content"));if(e!==null)return e;if(document.querySelector("base[href]")!==null)try{const t=new URL(document.baseURI);if(t.origin===window.location.origin){const a=x4(t.pathname);if(a!==null)return a}}catch{}return"/"}function sL(){return C1===null&&(C1=z4e()),C1}function xx(){return sL().replace(/\/$/,"")}function q4e(e){return/^[a-z][a-z0-9+.-]*:/i.test(e)||e.startsWith("//")}function I8e(e){if(q4e(e))return e;const t=sL(),a=e.replace(/^\/+/,"");return t!=="/"&&(e===xx()||e.startsWith(t))?e:`${t}${a}`}function L4e(){return`${typeof window<"u"?window.location.origin:""}${xx()}`}Oi("camstack:widget-registry",null);function E8e({title:e,icon:t,headerRight:a,collapsible:r=!1,defaultOpen:c=!0,bodyClassName:m="p-3",children:d}){const[h,f]=P.useState(c),k=!r||h,x=v.jsxs(v.Fragment,{children:[v.jsxs("span",{className:"flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-foreground",children:[t,e]}),r?h?v.jsx(gl,{className:"h-3.5 w-3.5 text-foreground-subtle"}):v.jsx(H3e,{className:"h-3.5 w-3.5 text-foreground-subtle"}):a]}),E=`px-4 py-2 flex items-center justify-between ${k?"border-b border-border":""}`;return v.jsxs("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[r?v.jsx("button",{type:"button",onClick:()=>f(R=>!R),className:`w-full text-left ${E}`,children:x}):v.jsx("div",{className:E,children:x}),k?v.jsx("div",{className:m,children:d}):null]})}var B4e="capability.binding-changed";function Vm(e,t){const[a,r]=P.useState(null);return P.useEffect(()=>{if(t===null){r(null);return}let c=!1;const m=async()=>{try{const h=await e.deviceManager.getBindings.query({deviceId:t});c||r(h)}catch{c||r(h=>h)}};m();const d=e.live?.onEvent.subscribe({category:B4e},{onData:h=>{const f=h.data?.source;if(!f){m();return}f.type==="device"&&f.id===t&&m()}});return()=>{c=!0,d?.unsubscribe()}},[e,t]),P.useMemo(()=>a?tJ(e,a):null,[e,a])}function cs(e){const t=P.useCallback(r=>e?e.subscribe(()=>r()):()=>{},[e]),a=P.useCallback(()=>e?.value,[e]);return P.useSyncExternalStore(t,a,a)}var F4e="/addon/snapshot/media";function R8e(e,t={}){const{width:a,baseUrl:r}=t,[c,m]=P.useState(0);return{src:P.useMemo(()=>{if(e===null||e<=0)return null;const d=r!==void 0?r.replace(/\/+$/,""):xx(),h=new URLSearchParams;a!==void 0&&Number.isInteger(a)&&a>0&&h.set("w",String(a)),c>0&&(h.set("force","1"),h.set("r",String(c)));const f=h.toString();return`${d}${F4e}/${String(e)}.jpg${f.length>0?`?${f}`:""}`},[e,a,r,c]),loading:!1,refresh:P.useCallback(()=>{m(d=>d+1)},[])}}O.Camera;function Nt(e){const t=Vm(e.trpc,e.deviceId),a=cs(t!==null?e.slice(t):void 0),r=t!==null?e.cap(t):void 0,c=cs(t!==null?t.state.deviceStatus:void 0),m=c?.online??!0,d=m?null:c?.lastChangedAt??null;return{dev:t,cap:r,slice:a,available:(e.requireFeature===void 0||(e.deviceFeatures??[]).includes(e.requireFeature))&&r!==void 0&&a!==void 0&&m,online:m,offlineSince:d}}var $4e=bl("inline-flex items-center justify-center rounded-md font-medium transition-colors cursor-pointer disabled:opacity-50 disabled:pointer-events-none",{variants:{variant:{primary:"bg-primary text-primary-foreground hover:bg-primary/90",secondary:"bg-surface text-foreground hover:bg-surface-hover",ghost:"hover:bg-surface-hover text-foreground-muted",danger:"bg-danger text-white hover:bg-danger/90",outline:"border border-border bg-transparent text-foreground hover:bg-surface-hover"},size:{sm:"h-7 px-2.5 text-xs gap-1.5",md:"h-8 px-3 text-sm gap-2",lg:"h-9 px-4 text-sm gap-2"}},defaultVariants:{variant:"primary",size:"sm"}}),pm=P.forwardRef(({className:e,variant:t,size:a,...r},c)=>v.jsx("button",{ref:c,className:ne($4e({variant:t,size:a}),e),...r}));pm.displayName="Button";var U4e=P.forwardRef(({className:e,...t},a)=>v.jsx("div",{ref:a,className:ne("animate-pulse bg-surface-hover rounded-md h-4 w-full",e),...t}));U4e.displayName="Skeleton";Oi("camstack:vod-playback",{request:null,play:()=>{},clear:()=>{}});var H4e=bl("rounded-lg p-3",{variants:{variant:{flat:"bg-surface",bordered:"bg-surface border border-border"}},defaultVariants:{variant:"bordered"}}),Q4e=P.forwardRef(({className:e,variant:t,...a},r)=>v.jsx("div",{ref:r,className:ne(H4e({variant:t}),e),...a}));Q4e.displayName="Card";function V4e(e){if(e==null||typeof e!="object")return null;const t=Reflect.get(e,"data");if(t!=null&&typeof t=="object"){const a=Reflect.get(t,"capRouteReason");if(typeof a=="string")return a}return null}function T8e(e){const t=V4e(e);return t!==null?t==="no-provider"||t==="node-offline":(e instanceof Error?e.message:String(e)).includes("provider not available")}Oi("camstack:recorded-playback",{bindControlChannel:null,channelOpen:!1,mode:"live",positionMs:null,send:()=>!1});var lL=P.createContext(null);function K4e(){const e=P.useContext(lL);if(!e)throw new Error("Dialog compound components must be used within <Dialog>");return e}function cL({children:e,open:t,onOpenChange:a}){const[r,c]=P.useState(!1),m=t??r,d=P.useId(),h=P.useCallback(f=>{a?.(f),t===void 0&&c(f)},[t,a]);return v.jsx(lL.Provider,{value:{open:m,setOpen:h,contentId:d},children:e})}var G4e=bl("relative fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 m-0 w-[calc(100vw-2rem)] bg-background-elevated text-foreground border border-border rounded-lg p-4 backdrop:bg-black/50 backdrop:backdrop-blur-sm max-h-[calc(100dvh-2rem-2*max(env(safe-area-inset-top),env(safe-area-inset-bottom)))] [&:not([open])]:hidden",{variants:{width:{sm:"max-w-sm",md:"max-w-md",lg:"max-w-lg",xl:"max-w-4xl"},scroll:{content:"overflow-y-auto",body:"flex flex-col overflow-hidden"},placement:{center:"","sheet-on-mobile":"bottom-0 left-0 right-0 top-auto w-full max-w-full translate-x-0 translate-y-0 rounded-b-none max-h-[92dvh] pb-[calc(1rem+env(safe-area-inset-bottom))] md:left-1/2 md:top-1/2 md:-translate-x-1/2 md:-translate-y-1/2 md:rounded-lg md:bottom-auto md:pb-4 md:max-h-[calc(100dvh-2rem-2*max(env(safe-area-inset-top),env(safe-area-inset-bottom)))]"}},compoundVariants:[{placement:"sheet-on-mobile",width:"sm",class:"md:w-[calc(100vw-2rem)] md:max-w-sm"},{placement:"sheet-on-mobile",width:"md",class:"md:w-[calc(100vw-2rem)] md:max-w-md"},{placement:"sheet-on-mobile",width:"lg",class:"md:w-[calc(100vw-2rem)] md:max-w-lg"},{placement:"sheet-on-mobile",width:"xl",class:"md:w-[calc(100vw-2rem)] md:max-w-4xl"},{scroll:"body",placement:"sheet-on-mobile",class:"h-[92dvh] md:h-auto"},{scroll:"body",placement:"center",class:"h-[calc(100dvh-2rem-2*max(env(safe-area-inset-top),env(safe-area-inset-bottom)))] md:h-auto"}],defaultVariants:{width:"md",placement:"center",scroll:"content"}}),Mx=P.forwardRef(({className:e,width:t,placement:a,scroll:r,children:c,...m},d)=>{const{open:h,setOpen:f,contentId:k}=K4e(),x=P.useRef(null),E=d??x;return P.useEffect(()=>{const R=E.current;R&&(h&&!R.open&&R.showModal(),!h&&R.open&&R.close())},[h,E]),v.jsxs("dialog",{ref:E,id:k,className:ne(G4e({width:t,placement:a,scroll:r}),e),onClose:()=>f(!1),...m,children:[v.jsx(hx,{type:"button",variant:"ghost",size:"sm",icon:Kq,"aria-label":"Close",className:"absolute right-4 top-4 z-10 shrink-0",onClick:()=>f(!1)}),c]})});Mx.displayName="DialogContent";function W4e({className:e,...t}){return v.jsx("div",{className:ne("flex flex-col gap-1 mb-3 shrink-0 pr-10",e),...t})}function Z4e({className:e,...t}){return v.jsx("div",{className:ne("flex justify-end gap-2 mt-4 shrink-0",e),...t})}function Y4e({className:e,...t}){return v.jsx("h2",{className:ne("text-sm font-semibold text-foreground",e),...t})}function X4e({className:e,...t}){return v.jsx("p",{className:ne("text-xs text-foreground-muted",e),...t})}P.lazy(()=>Hc(()=>import("./MotionZonesSettings-CiYjd-yl-BirmOvge.js"),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.MotionZonesSettings}))),P.lazy(()=>Hc(()=>import("./PrivacyMaskSettings-BmRdUrPp-D7nMj8O6.js"),__vite__mapDeps([2,1]),import.meta.url).then(e=>({default:e.PrivacyMaskSettings})));var J4e=Object.defineProperty,Xf=Object.getOwnPropertySymbols,dL=Object.prototype.hasOwnProperty,uL=Object.prototype.propertyIsEnumerable,M4=(e,t,a)=>t in e?J4e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a,QS=(e,t)=>{for(var a in t||(t={}))dL.call(t,a)&&M4(e,a,t[a]);if(Xf)for(var a of Xf(t))uL.call(t,a)&&M4(e,a,t[a]);return e},VS=(e,t)=>{var a={};for(var r in e)dL.call(e,r)&&t.indexOf(r)<0&&(a[r]=e[r]);if(e!=null&&Xf)for(var r of Xf(e))t.indexOf(r)<0&&uL.call(e,r)&&(a[r]=e[r]);return a};var ll;(e=>{const t=class _t{constructor(f,k,x,E){if(this.version=f,this.errorCorrectionLevel=k,this.modules=[],this.isFunction=[],f<_t.MIN_VERSION||f>_t.MAX_VERSION)throw new RangeError("Version value out of range");if(E<-1||E>7)throw new RangeError("Mask value out of range");this.size=f*4+17;let R=[];for(let N=0;N<this.size;N++)R.push(!1);for(let N=0;N<this.size;N++)this.modules.push(R.slice()),this.isFunction.push(R.slice());this.drawFunctionPatterns();const T=this.addEccAndInterleave(x);if(this.drawCodewords(T),E==-1){let N=1e9;for(let j=0;j<8;j++){this.applyMask(j),this.drawFormatBits(j);const q=this.getPenaltyScore();q<N&&(E=j,N=q),this.applyMask(j)}}c(0<=E&&E<=7),this.mask=E,this.applyMask(E),this.drawFormatBits(E),this.isFunction=[]}static encodeText(f,k){const x=e.QrSegment.makeSegments(f);return _t.encodeSegments(x,k)}static encodeBinary(f,k){const x=e.QrSegment.makeBytes(f);return _t.encodeSegments([x],k)}static encodeSegments(f,k,x=1,E=40,R=-1,T=!0){if(!(_t.MIN_VERSION<=x&&x<=E&&E<=_t.MAX_VERSION)||R<-1||R>7)throw new RangeError("Invalid value");let N,j;for(N=x;;N++){const U=_t.getNumDataCodewords(N,k)*8,H=d.getTotalBits(f,N);if(H<=U){j=H;break}if(N>=E)throw new RangeError("Data too long")}for(const U of[_t.Ecc.MEDIUM,_t.Ecc.QUARTILE,_t.Ecc.HIGH])T&&j<=_t.getNumDataCodewords(N,U)*8&&(k=U);let q=[];for(const U of f){a(U.mode.modeBits,4,q),a(U.numChars,U.mode.numCharCountBits(N),q);for(const H of U.getData())q.push(H)}c(q.length==j);const B=_t.getNumDataCodewords(N,k)*8;c(q.length<=B),a(0,Math.min(4,B-q.length),q),a(0,(8-q.length%8)%8,q),c(q.length%8==0);for(let U=236;q.length<B;U^=253)a(U,8,q);let F=[];for(;F.length*8<q.length;)F.push(0);return q.forEach((U,H)=>F[H>>>3]|=U<<7-(H&7)),new _t(N,k,F,R)}getModule(f,k){return 0<=f&&f<this.size&&0<=k&&k<this.size&&this.modules[k][f]}getModules(){return this.modules}drawFunctionPatterns(){for(let x=0;x<this.size;x++)this.setFunctionModule(6,x,x%2==0),this.setFunctionModule(x,6,x%2==0);this.drawFinderPattern(3,3),this.drawFinderPattern(this.size-4,3),this.drawFinderPattern(3,this.size-4);const f=this.getAlignmentPatternPositions(),k=f.length;for(let x=0;x<k;x++)for(let E=0;E<k;E++)x==0&&E==0||x==0&&E==k-1||x==k-1&&E==0||this.drawAlignmentPattern(f[x],f[E]);this.drawFormatBits(0),this.drawVersion()}drawFormatBits(f){const k=this.errorCorrectionLevel.formatBits<<3|f;let x=k;for(let R=0;R<10;R++)x=x<<1^(x>>>9)*1335;const E=(k<<10|x)^21522;c(E>>>15==0);for(let R=0;R<=5;R++)this.setFunctionModule(8,R,r(E,R));this.setFunctionModule(8,7,r(E,6)),this.setFunctionModule(8,8,r(E,7)),this.setFunctionModule(7,8,r(E,8));for(let R=9;R<15;R++)this.setFunctionModule(14-R,8,r(E,R));for(let R=0;R<8;R++)this.setFunctionModule(this.size-1-R,8,r(E,R));for(let R=8;R<15;R++)this.setFunctionModule(8,this.size-15+R,r(E,R));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let f=this.version;for(let x=0;x<12;x++)f=f<<1^(f>>>11)*7973;const k=this.version<<12|f;c(k>>>18==0);for(let x=0;x<18;x++){const E=r(k,x),R=this.size-11+x%3,T=Math.floor(x/3);this.setFunctionModule(R,T,E),this.setFunctionModule(T,R,E)}}drawFinderPattern(f,k){for(let x=-4;x<=4;x++)for(let E=-4;E<=4;E++){const R=Math.max(Math.abs(E),Math.abs(x)),T=f+E,N=k+x;0<=T&&T<this.size&&0<=N&&N<this.size&&this.setFunctionModule(T,N,R!=2&&R!=4)}}drawAlignmentPattern(f,k){for(let x=-2;x<=2;x++)for(let E=-2;E<=2;E++)this.setFunctionModule(f+E,k+x,Math.max(Math.abs(E),Math.abs(x))!=1)}setFunctionModule(f,k,x){this.modules[k][f]=x,this.isFunction[k][f]=!0}addEccAndInterleave(f){const k=this.version,x=this.errorCorrectionLevel;if(f.length!=_t.getNumDataCodewords(k,x))throw new RangeError("Invalid argument");const E=_t.NUM_ERROR_CORRECTION_BLOCKS[x.ordinal][k],R=_t.ECC_CODEWORDS_PER_BLOCK[x.ordinal][k],T=Math.floor(_t.getNumRawDataModules(k)/8),N=E-T%E,j=Math.floor(T/E);let q=[];const B=_t.reedSolomonComputeDivisor(R);for(let U=0,H=0;U<E;U++){let Q=f.slice(H,H+j-R+(U<N?0:1));H+=Q.length;const te=_t.reedSolomonComputeRemainder(Q,B);U<N&&Q.push(0),q.push(Q.concat(te))}let F=[];for(let U=0;U<q[0].length;U++)q.forEach((H,Q)=>{(U!=j-R||Q>=N)&&F.push(H[U])});return c(F.length==T),F}drawCodewords(f){if(f.length!=Math.floor(_t.getNumRawDataModules(this.version)/8))throw new RangeError("Invalid argument");let k=0;for(let x=this.size-1;x>=1;x-=2){x==6&&(x=5);for(let E=0;E<this.size;E++)for(let R=0;R<2;R++){const T=x-R,N=(x+1&2)==0?this.size-1-E:E;!this.isFunction[N][T]&&k<f.length*8&&(this.modules[N][T]=r(f[k>>>3],7-(k&7)),k++)}}c(k==f.length*8)}applyMask(f){if(f<0||f>7)throw new RangeError("Mask value out of range");for(let k=0;k<this.size;k++)for(let x=0;x<this.size;x++){let E;switch(f){case 0:E=(x+k)%2==0;break;case 1:E=k%2==0;break;case 2:E=x%3==0;break;case 3:E=(x+k)%3==0;break;case 4:E=(Math.floor(x/3)+Math.floor(k/2))%2==0;break;case 5:E=x*k%2+x*k%3==0;break;case 6:E=(x*k%2+x*k%3)%2==0;break;case 7:E=((x+k)%2+x*k%3)%2==0;break;default:throw new Error("Unreachable")}!this.isFunction[k][x]&&E&&(this.modules[k][x]=!this.modules[k][x])}}getPenaltyScore(){let f=0;for(let R=0;R<this.size;R++){let T=!1,N=0,j=[0,0,0,0,0,0,0];for(let q=0;q<this.size;q++)this.modules[R][q]==T?(N++,N==5?f+=_t.PENALTY_N1:N>5&&f++):(this.finderPenaltyAddHistory(N,j),T||(f+=this.finderPenaltyCountPatterns(j)*_t.PENALTY_N3),T=this.modules[R][q],N=1);f+=this.finderPenaltyTerminateAndCount(T,N,j)*_t.PENALTY_N3}for(let R=0;R<this.size;R++){let T=!1,N=0,j=[0,0,0,0,0,0,0];for(let q=0;q<this.size;q++)this.modules[q][R]==T?(N++,N==5?f+=_t.PENALTY_N1:N>5&&f++):(this.finderPenaltyAddHistory(N,j),T||(f+=this.finderPenaltyCountPatterns(j)*_t.PENALTY_N3),T=this.modules[q][R],N=1);f+=this.finderPenaltyTerminateAndCount(T,N,j)*_t.PENALTY_N3}for(let R=0;R<this.size-1;R++)for(let T=0;T<this.size-1;T++){const N=this.modules[R][T];N==this.modules[R][T+1]&&N==this.modules[R+1][T]&&N==this.modules[R+1][T+1]&&(f+=_t.PENALTY_N2)}let k=0;for(const R of this.modules)k=R.reduce((T,N)=>T+(N?1:0),k);const x=this.size*this.size,E=Math.ceil(Math.abs(k*20-x*10)/x)-1;return c(0<=E&&E<=9),f+=E*_t.PENALTY_N4,c(0<=f&&f<=2568888),f}getAlignmentPatternPositions(){if(this.version==1)return[];{const f=Math.floor(this.version/7)+2,k=this.version==32?26:Math.ceil((this.version*4+4)/(f*2-2))*2;let x=[6];for(let E=this.size-7;x.length<f;E-=k)x.splice(1,0,E);return x}}static getNumRawDataModules(f){if(f<_t.MIN_VERSION||f>_t.MAX_VERSION)throw new RangeError("Version number out of range");let k=(16*f+128)*f+64;if(f>=2){const x=Math.floor(f/7)+2;k-=(25*x-10)*x-55,f>=7&&(k-=36)}return c(208<=k&&k<=29648),k}static getNumDataCodewords(f,k){return Math.floor(_t.getNumRawDataModules(f)/8)-_t.ECC_CODEWORDS_PER_BLOCK[k.ordinal][f]*_t.NUM_ERROR_CORRECTION_BLOCKS[k.ordinal][f]}static reedSolomonComputeDivisor(f){if(f<1||f>255)throw new RangeError("Degree out of range");let k=[];for(let E=0;E<f-1;E++)k.push(0);k.push(1);let x=1;for(let E=0;E<f;E++){for(let R=0;R<k.length;R++)k[R]=_t.reedSolomonMultiply(k[R],x),R+1<k.length&&(k[R]^=k[R+1]);x=_t.reedSolomonMultiply(x,2)}return k}static reedSolomonComputeRemainder(f,k){let x=k.map(E=>0);for(const E of f){const R=E^x.shift();x.push(0),k.forEach((T,N)=>x[N]^=_t.reedSolomonMultiply(T,R))}return x}static reedSolomonMultiply(f,k){if(f>>>8||k>>>8)throw new RangeError("Byte out of range");let x=0;for(let E=7;E>=0;E--)x=x<<1^(x>>>7)*285,x^=(k>>>E&1)*f;return c(x>>>8==0),x}finderPenaltyCountPatterns(f){const k=f[1];c(k<=this.size*3);const x=k>0&&f[2]==k&&f[3]==k*3&&f[4]==k&&f[5]==k;return(x&&f[0]>=k*4&&f[6]>=k?1:0)+(x&&f[6]>=k*4&&f[0]>=k?1:0)}finderPenaltyTerminateAndCount(f,k,x){return f&&(this.finderPenaltyAddHistory(k,x),k=0),k+=this.size,this.finderPenaltyAddHistory(k,x),this.finderPenaltyCountPatterns(x)}finderPenaltyAddHistory(f,k){k[0]==0&&(f+=this.size),k.pop(),k.unshift(f)}};t.MIN_VERSION=1,t.MAX_VERSION=40,t.PENALTY_N1=3,t.PENALTY_N2=3,t.PENALTY_N3=40,t.PENALTY_N4=10,t.ECC_CODEWORDS_PER_BLOCK=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],t.NUM_ERROR_CORRECTION_BLOCKS=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],e.QrCode=t;function a(h,f,k){if(f<0||f>31||h>>>f)throw new RangeError("Value out of range");for(let x=f-1;x>=0;x--)k.push(h>>>x&1)}function r(h,f){return(h>>>f&1)!=0}function c(h){if(!h)throw new Error("Assertion error")}const m=class Na{constructor(f,k,x){if(this.mode=f,this.numChars=k,this.bitData=x,k<0)throw new RangeError("Invalid argument");this.bitData=x.slice()}static makeBytes(f){let k=[];for(const x of f)a(x,8,k);return new Na(Na.Mode.BYTE,f.length,k)}static makeNumeric(f){if(!Na.isNumeric(f))throw new RangeError("String contains non-numeric characters");let k=[];for(let x=0;x<f.length;){const E=Math.min(f.length-x,3);a(parseInt(f.substring(x,x+E),10),E*3+1,k),x+=E}return new Na(Na.Mode.NUMERIC,f.length,k)}static makeAlphanumeric(f){if(!Na.isAlphanumeric(f))throw new RangeError("String contains unencodable characters in alphanumeric mode");let k=[],x;for(x=0;x+2<=f.length;x+=2){let E=Na.ALPHANUMERIC_CHARSET.indexOf(f.charAt(x))*45;E+=Na.ALPHANUMERIC_CHARSET.indexOf(f.charAt(x+1)),a(E,11,k)}return x<f.length&&a(Na.ALPHANUMERIC_CHARSET.indexOf(f.charAt(x)),6,k),new Na(Na.Mode.ALPHANUMERIC,f.length,k)}static makeSegments(f){return f==""?[]:Na.isNumeric(f)?[Na.makeNumeric(f)]:Na.isAlphanumeric(f)?[Na.makeAlphanumeric(f)]:[Na.makeBytes(Na.toUtf8ByteArray(f))]}static makeEci(f){let k=[];if(f<0)throw new RangeError("ECI assignment value out of range");if(f<128)a(f,8,k);else if(f<16384)a(2,2,k),a(f,14,k);else if(f<1e6)a(6,3,k),a(f,21,k);else throw new RangeError("ECI assignment value out of range");return new Na(Na.Mode.ECI,0,k)}static isNumeric(f){return Na.NUMERIC_REGEX.test(f)}static isAlphanumeric(f){return Na.ALPHANUMERIC_REGEX.test(f)}getData(){return this.bitData.slice()}static getTotalBits(f,k){let x=0;for(const E of f){const R=E.mode.numCharCountBits(k);if(E.numChars>=1<<R)return 1/0;x+=4+R+E.bitData.length}return x}static toUtf8ByteArray(f){f=encodeURI(f);let k=[];for(let x=0;x<f.length;x++)f.charAt(x)!="%"?k.push(f.charCodeAt(x)):(k.push(parseInt(f.substring(x+1,x+3),16)),x+=2);return k}};m.NUMERIC_REGEX=/^[0-9]*$/,m.ALPHANUMERIC_REGEX=/^[A-Z0-9 $%*+.\/:-]*$/,m.ALPHANUMERIC_CHARSET="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";let d=m;e.QrSegment=m})(ll||(ll={}));(e=>{(t=>{const a=class{constructor(c,m){this.ordinal=c,this.formatBits=m}};a.LOW=new a(0,1),a.MEDIUM=new a(1,0),a.QUARTILE=new a(2,3),a.HIGH=new a(3,2),t.Ecc=a})(e.QrCode||(e.QrCode={}))})(ll||(ll={}));(e=>{(t=>{const a=class{constructor(c,m){this.modeBits=c,this.numBitsCharCount=m}numCharCountBits(c){return this.numBitsCharCount[Math.floor((c+7)/17)]}};a.NUMERIC=new a(1,[10,12,14]),a.ALPHANUMERIC=new a(2,[9,11,13]),a.BYTE=new a(4,[8,16,16]),a.KANJI=new a(8,[8,10,12]),a.ECI=new a(7,[0,0,0]),t.Mode=a})(e.QrSegment||(e.QrSegment={}))})(ll||(ll={}));var Rc=ll;var eTe={L:Rc.QrCode.Ecc.LOW,M:Rc.QrCode.Ecc.MEDIUM,Q:Rc.QrCode.Ecc.QUARTILE,H:Rc.QrCode.Ecc.HIGH},mL=128,pL="L",hL="#FFFFFF",fL="#000000",gL=!1,vL=1,tTe=4,aTe=0,nTe=.1;function yL(e,t=0){const a=[];return e.forEach(function(r,c){let m=null;r.forEach(function(d,h){if(!d&&m!==null){a.push(`M${m+t} ${c+t}h${h-m}v1H${m+t}z`),m=null;return}if(h===r.length-1){if(!d)return;m===null?a.push(`M${h+t},${c+t} h1v1H${h+t}z`):a.push(`M${m+t},${c+t} h${h+1-m}v1H${m+t}z`);return}d&&m===null&&(m=h)})}),a.join("")}function bL(e,t){return e.slice().map((a,r)=>r<t.y||r>=t.y+t.h?a:a.map((c,m)=>m<t.x||m>=t.x+t.w?c:!1))}function iTe(e,t,a,r){if(r==null)return null;const c=e.length+a*2,m=Math.floor(t*nTe),d=c/t,h=(r.width||m)*d,f=(r.height||m)*d,k=r.x==null?e.length/2-h/2:r.x*d,x=r.y==null?e.length/2-f/2:r.y*d,E=r.opacity==null?1:r.opacity;let R=null;if(r.excavate){let N=Math.floor(k),j=Math.floor(x);R={x:N,y:j,w:Math.ceil(h+k-N),h:Math.ceil(f+x-j)}}const T=r.crossOrigin;return{x:k,y:x,h:f,w:h,excavation:R,opacity:E,crossOrigin:T}}function rTe(e,t){return t!=null?Math.max(Math.floor(t),0):e?tTe:aTe}function kL({value:e,level:t,minVersion:a,includeMargin:r,marginSize:c,imageSettings:m,size:d,boostLevel:h}){let f=Xa.useMemo(()=>{const T=(Array.isArray(e)?e:[e]).reduce((N,j)=>(N.push(...Rc.QrSegment.makeSegments(j)),N),[]);return Rc.QrCode.encodeSegments(T,eTe[t],a,void 0,void 0,h)},[e,t,a,h]);const{cells:k,margin:x,numCells:E,calculatedImageSettings:R}=Xa.useMemo(()=>{let T=f.getModules();const N=rTe(r,c);return{cells:T,margin:N,numCells:T.length+N*2,calculatedImageSettings:iTe(T,d,N,m)}},[f,d,m,r,c]);return{qrcode:f,margin:x,cells:k,numCells:E,calculatedImageSettings:R}}var oTe=(function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0})(),sTe=Xa.forwardRef(function(t,a){const r=t,{value:c,size:m=mL,level:d=pL,bgColor:h=hL,fgColor:f=fL,includeMargin:k=gL,minVersion:x=vL,boostLevel:E,marginSize:R,imageSettings:T}=r,N=VS(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:j}=N,q=VS(N,["style"]),B=T?.src,F=Xa.useRef(null),U=Xa.useRef(null),H=Xa.useCallback(Ee=>{F.current=Ee,typeof a=="function"?a(Ee):a&&(a.current=Ee)},[a]),[Q,te]=Xa.useState(!1),{margin:K,cells:W,numCells:oe,calculatedImageSettings:he}=kL({value:c,level:d,minVersion:x,boostLevel:E,includeMargin:k,marginSize:R,imageSettings:T,size:m});Xa.useEffect(()=>{if(F.current!=null){const Ee=F.current,Ie=Ee.getContext("2d");if(!Ie)return;let Me=W;const Y=U.current,de=he!=null&&Y!==null&&Y.complete&&Y.naturalHeight!==0&&Y.naturalWidth!==0;de&&he.excavation!=null&&(Me=bL(W,he.excavation));const Re=window.devicePixelRatio||1;Ee.height=Ee.width=m*Re;const Qe=m/oe*Re;Ie.scale(Qe,Qe),Ie.fillStyle=h,Ie.fillRect(0,0,oe,oe),Ie.fillStyle=f,oTe?Ie.fill(new Path2D(yL(Me,K))):W.forEach(function(re,V){re.forEach(function(ie,fe){ie&&Ie.fillRect(fe+K,V+K,1,1)})}),he&&(Ie.globalAlpha=he.opacity),de&&Ie.drawImage(Y,he.x+K,he.y+K,he.w,he.h)}}),Xa.useEffect(()=>{te(!1)},[B]);const Ae=QS({height:m,width:m},j);let we=null;return B!=null&&(we=Xa.createElement("img",{src:B,key:B,style:{display:"none"},onLoad:()=>{te(!0)},ref:U,crossOrigin:he?.crossOrigin})),Xa.createElement(Xa.Fragment,null,Xa.createElement("canvas",QS({style:Ae,height:m,width:m,ref:H,role:"img"},q)),we)});sTe.displayName="QRCodeCanvas";var lTe=Xa.forwardRef(function(t,a){const r=t,{value:c,size:m=mL,level:d=pL,bgColor:h=hL,fgColor:f=fL,includeMargin:k=gL,minVersion:x=vL,boostLevel:E,title:R,marginSize:T,imageSettings:N}=r,j=VS(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:q,cells:B,numCells:F,calculatedImageSettings:U}=kL({value:c,level:d,minVersion:x,boostLevel:E,includeMargin:k,marginSize:T,imageSettings:N,size:m});let H=B,Q=null;N!=null&&U!=null&&(U.excavation!=null&&(H=bL(B,U.excavation)),Q=Xa.createElement("image",{href:N.src,height:U.h,width:U.w,x:U.x+q,y:U.y+q,preserveAspectRatio:"none",opacity:U.opacity,crossOrigin:U.crossOrigin}));const te=yL(H,q);return Xa.createElement("svg",QS({height:m,width:m,viewBox:`0 0 ${F} ${F}`,ref:a,role:"img"},j),!!R&&Xa.createElement("title",null,R),Xa.createElement("path",{fill:h,d:`M0,0 h${F}v${F}H0z`,shapeRendering:"crispEdges"}),Xa.createElement("path",{fill:f,d:te,shapeRendering:"crispEdges"}),Q)});lTe.displayName="QRCodeSVG";var N8e="text-[10px] text-foreground-subtle",cTe="inline-flex items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-medium transition-colors",dTe="border-primary/50 bg-primary/15 text-primary",uTe=P.forwardRef(({className:e,...t},a)=>v.jsx("label",{ref:a,className:ne("text-[10px] uppercase tracking-wider text-foreground-muted font-medium",e),...t}));uTe.displayName="Label";var mTe=bl("",{variants:{orientation:{horizontal:"h-px w-full bg-border-subtle",vertical:"w-px h-full bg-border-subtle"}},defaultVariants:{orientation:"horizontal"}}),pTe=P.forwardRef(({className:e,orientation:t,...a},r)=>v.jsx("div",{ref:r,role:"separator","aria-orientation":t??"horizontal",className:ne(mTe({orientation:t}),e),...a}));pTe.displayName="Separator";var hTe=P.forwardRef(({className:e,...t},a)=>v.jsx("input",{ref:a,type:"checkbox",className:ne("w-3.5 h-3.5 rounded-sm border border-border accent-primary",e),...t}));hTe.displayName="Checkbox";var fTe=P.forwardRef(({className:e,checked:t,onCheckedChange:a,label:r,...c},m)=>v.jsxs("button",{ref:m,role:"switch","aria-checked":t,type:"button",onClick:()=>a(!t),className:ne("inline-flex items-center gap-2",e),...c,children:[v.jsx("span",{className:ne("w-8 h-4 rounded-full transition-colors",t?"bg-primary":"bg-surface-hover"),children:v.jsx("span",{className:ne("block w-3.5 h-3.5 rounded-full bg-white transition-transform",t?"translate-x-4":"translate-x-0.5")})}),r&&v.jsx("span",{className:"text-xs text-foreground",children:r})]}));fTe.displayName="Switch";P.createContext(null);var gTe=P.forwardRef(({className:e,...t},a)=>v.jsx("div",{ref:a,className:ne("overflow-auto [&::-webkit-scrollbar]:w-1 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-thumb]:bg-surface-hover [&::-webkit-scrollbar-thumb]:rounded-full",e),...t}));gTe.displayName="ScrollArea";var A1={baseDelayMs:1500,maxDelayMs:15e3,maxAttempts:40};function vTe(e,t=Math.random){if(e>=A1.maxAttempts)return{kind:"exhausted",attempts:e};const a=Math.min(A1.maxDelayMs,A1.baseDelayMs*2**e);return{kind:"retry",delayMs:Math.round(a*(.8+t()*.4))}}var yTe="/adaptive-probe",bTe=2500,kTe=15e3,STe=250,wTe=2;function SL(e){return e>=8?"high":e>=2.5?"mid":"low"}function xTe(e){const{downlinkMbps:t,...a}=e;return a}function C4(e){return SL(e)!=="low"}function A4(e){if(e===void 0||e==="")return null;let t;try{t=new URL(e)}catch{return null}return t.protocol!=="http:"&&t.protocol!=="https:"?null:`${t.origin}${t.pathname.replace(/\/+$/,"")}`}function MTe(e,t){return A4(e)??A4(t)}function CTe(e){const t=e.downlinkMbps===void 0?"none":SL(e.downlinkMbps);return[e.phase,e.viewportWidth??"-",e.viewportHeight??"-",e.devicePixelRatio??"-",t,e.prefersTier??"-",e.probeOrigin??"unreachable",e.probeStatus??"-",e.probeAnswer??"-"].join("|")}function wL(e,t){return e<65536||!(t>0)?null:e*8/t/1e3}async function ATe(e,t){let a=null,r=0,c=0;try{for(;;){const m=await e.read();if(m.done)break;const d=m.value?.byteLength??0,h=t();a===null?a=h:c+=d,r=h}}catch{e.cancel().catch(()=>{})}return a===null?null:wL(c,r-a)}async function ITe(e,t){const a=e.replace(/\/+$/,""),r=new AbortController,c=setTimeout(()=>r.abort(),bTe);try{const m=await t.fetchImpl(`${a}${yTe}`,{signal:r.signal});if(!m.ok)return m.status!==void 0&&t.onRefused?.(m.status),null;const d=m.body?.getReader()??null;if(d!==null)return await ATe(d,t.now);const h=t.now();return wL((await m.arrayBuffer()).byteLength,t.now()-h)}catch{return null}finally{clearTimeout(c)}}async function ETe(e,t=kTe){const a=e.now()+t;for(;;){if(e.signal.aborted)return"aborted";if((e.readyState()??0)>=wTe)return"frame";if(e.now()>=a)return"timeout";await e.sleep(STe)}}async function RTe(e){if(await e.waitFrame()==="frame")return e.measure()}function TTe(e){const t=new Map,a=new Map,r=new Set,c=m=>{const d=t.get(m);return d!==void 0&&e.now()-d.at<=e.ttlMs?d.mbps:void 0};return{cached:c,firstRefusal:(m,d)=>{const h=`${m}|${String(d)}`;return r.has(h)?!1:(r.add(h),!0)},latest:m=>{const d=t.get(m);return d===void 0?null:{mbps:d.mbps,ageMs:Math.max(0,e.now()-d.at)}},measured:(m,d)=>{const h=c(m);if(h!==void 0)return Promise.resolve(h);const f=a.get(m);if(f!==void 0)return f;const k=d().then(x=>{if(!(x===null||!Number.isFinite(x)))return t.set(m,{mbps:x,at:e.now()}),x}).catch(()=>{}).finally(()=>{a.delete(m)});return a.set(m,k),k}}}async function _Te(e,t,a){if(e===void 0)return{kind:"unsupported",why:"no-wiring"};if(t===null)return{kind:"unsupported",why:"no-session"};try{return{kind:"answered",answer:await e(t,a)}}catch{return{kind:"unsupported",why:"call-failed"}}}var PTe=100;function NTe(e,t,a){if(a.renegotiating)return{baseline:null,sample:null};if(e===null||e.pc!==t.pc||t.ts<=e.ts)return{baseline:t,sample:null};const r=Math.max(0,t.lost-e.lost),c=r+Math.max(0,t.recv-e.recv),m=c>0?Math.min(PTe,r/c*100):0,d=Math.max(0,Math.round((t.bytes-e.bytes)*8/(t.ts-e.ts)));return{baseline:t,sample:{rttMs:Math.round(t.rttS*1e3),jitterMs:Math.round(t.jitterS*1e3),estimatedBandwidthKbps:d,packetLossPercent:m,...a.probe!==null?{downlinkMbps:a.probe.mbps,downlinkAgeMs:a.probe.ageMs}:{}}}}var OTe={urls:"stun:stun.l.google.com:19302"};function I1(e,t){const a=[...e??[],OTe];return t===void 0?{iceServers:a}:{iceServers:a,iceTransportPolicy:t}}var I4=8;function pn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Ji(e){return typeof e=="string"&&e.length>0?e:null}function Zi(e,t){if(e===null||t===null)return null;const a=e-t;return a<0?null:a}function xL(e,t){if(e===null||t===null)return null;const a=e+t;return a<=0?null:e/a*100}function DTe(e){return e===null?null:/profile-level-id=([0-9a-fA-F]+)/.exec(e)?.[1]??null}function jTe(e){const t={inbound:null,codecs:new Map,candidates:new Map,pair:null,selectedPairId:null},a=[];e.forEach(c=>{const m=c,d=Ji(m.id);switch(m.type){case"inbound-rtp":(m.kind??m.mediaType)==="video"&&(t.inbound=m);break;case"codec":d!==null&&t.codecs.set(d,m);break;case"local-candidate":case"remote-candidate":d!==null&&t.candidates.set(d,m);break;case"candidate-pair":a.push(m);break;case"transport":t.selectedPairId=Ji(m.selectedCandidatePairId);break}});const r=t.selectedPairId;return t.pair=a.find(c=>Ji(c.id)===r)??a.find(c=>c.selected===!0)??a.find(c=>c.nominated===!0&&c.state==="succeeded")??a.find(c=>c.nominated===!0)??a.find(c=>c.state==="succeeded")??null,t}function zTe(e){return e===null?{timestamp:null,bytesReceived:null,packetsReceived:null,packetsLost:null,framesDecoded:null,framesDropped:null,freezeCount:null,totalFreezesDurationS:null,totalDecodeTimeS:null,nackCount:null,pliCount:null}:{timestamp:pn(e.timestamp),bytesReceived:pn(e.bytesReceived),packetsReceived:pn(e.packetsReceived),packetsLost:pn(e.packetsLost),framesDecoded:pn(e.framesDecoded),framesDropped:pn(e.framesDropped),freezeCount:pn(e.freezeCount),totalFreezesDurationS:pn(e.totalFreezesDuration),totalDecodeTimeS:pn(e.totalDecodeTime),nackCount:pn(e.nackCount),pliCount:pn(e.pliCount)}}var E4={spanMs:null,kbps:null,packetsReceived:null,packetsLost:null,lossPercent:null,framesDecoded:null,framesDropped:null,freezeCount:null,freezeMs:null,nackCount:null,pliCount:null,decodeMs:null};function qTe(e,t){if(t===null)return E4;const a=Zi(e.timestamp,t.timestamp);if(a===null||a<=0)return E4;const r=Zi(e.bytesReceived,t.bytesReceived),c=Zi(e.packetsLost,t.packetsLost),m=Zi(e.packetsReceived,t.packetsReceived),d=Zi(e.framesDecoded,t.framesDecoded),h=Zi(e.totalDecodeTimeS,t.totalDecodeTimeS),f=Zi(e.totalFreezesDurationS,t.totalFreezesDurationS);return{spanMs:a,kbps:r===null?null:Math.round(r*8/a),packetsReceived:m,packetsLost:c,lossPercent:xL(c,m),framesDecoded:d,framesDropped:Zi(e.framesDropped,t.framesDropped),freezeCount:Zi(e.freezeCount,t.freezeCount),freezeMs:f===null?null:Math.round(f*1e3),nackCount:Zi(e.nackCount,t.nackCount),pliCount:Zi(e.pliCount,t.pliCount),decodeMs:h===null||d===null||d<=0?null:h/d*1e3}}function LTe(e,t,a,r){if(t===null||a===null)return e;const c=e.at(-1);if(c!==void 0&&c.width===t&&c.height===a)return e;const m=[...e,{width:t,height:a,at:r}];return m.length>I4?m.slice(m.length-I4):m}function BTe(e){const{inbound:t,codecs:a,candidates:r,pair:c}=jTe(e.report),m=zTe(t),d=t!==null?a.get(Ji(t.codecId)??""):void 0,h=Ji(d?.mimeType),f=Ji(d?.sdpFmtpLine),k=c!==null?r.get(Ji(c.localCandidateId)??""):void 0,x=c!==null?r.get(Ji(c.remoteCandidateId)??""):void 0,E=Ji(k?.candidateType),R=Ji(x?.candidateType),T=pn(t?.frameWidth),N=pn(t?.frameHeight),j=m.totalFreezesDurationS,q=m.totalDecodeTimeS,B=m.framesDecoded;return{at:e.now,hasInboundVideo:t!==null,width:T,height:N,fps:pn(t?.framesPerSecond),codec:h===null?null:h.split("/")[1]??h,codecProfileLevelId:DTe(f),jitterMs:FTe(t),packetsReceived:m.packetsReceived,packetsLost:m.packetsLost,lossPercent:xL(m.packetsLost,m.packetsReceived),nackCount:m.nackCount,pliCount:m.pliCount,framesDecoded:B,framesDropped:m.framesDropped,freezeCount:m.freezeCount,totalFreezeMs:j===null?null:Math.round(j*1e3),avgDecodeMs:q===null||B===null||B<=0?null:q/B*1e3,rttMs:$Te(c),availableIncomingKbps:UTe(c),localCandidateType:E,remoteCandidateType:R,candidatePairType:E===null&&R===null?null:`${E??"?"}/${R??"?"}`,candidateProtocol:Ji(k?.protocol),iceConnectionState:e.iceConnectionState,dtlsState:e.dtlsState,window:qTe(m,e.prev?.raw??null),resolutionLog:LTe(e.prev?.resolutionLog??[],T,N,e.now),raw:m}}function FTe(e){const t=pn(e?.jitter);return t===null?null:t*1e3}function $Te(e){const t=pn(e?.currentRoundTripTime);return t===null?null:t*1e3}function UTe(e){const t=pn(e?.availableIncomingBitrate);return t===null?null:Math.round(t/1e3)}var HTe={unknown:"no window yet",decoding:"decoding","decoder-stall":"DECODER STALL — bytes arriving, no frames out","transport-stall":"TRANSPORT STALL — nothing arriving","frozen-unknown":"frames stopped — byte rate unknown"};function ML(e){const t=QTe(e);return{kind:t,label:HTe[t]}}function QTe(e){if(e===null||!e.hasInboundVideo)return"unknown";const t=e.window.framesDecoded;if(t===null)return"unknown";if(t>0)return"decoding";const a=e.window.kbps;return a===null?"frozen-unknown":a>0?"decoder-stall":"transport-stall"}var ol="—";function ia(e,t){if(e==null||!Number.isFinite(e))return ol;const a=t?.digits??0;return`${e.toFixed(a)}${t?.suffix??""}`}function Yi(e){return e==null||e===""?ol:e}function jh(e){return e==null?ol:e?"yes":"no"}function KS(e,t){if(e===null)return ol;const a=Math.max(0,t-e);return a<1e3?`${a}ms ago`:a<6e4?`${(a/1e3).toFixed(1)}s ago`:`${Math.floor(a/6e4)}m${Math.floor(a%6e4/1e3)}s ago`}var CL=3e3,VTe={unknown:"bg-white/15 text-white/70",decoding:"bg-emerald-500/25 text-emerald-200","decoder-stall":"bg-amber-500/30 text-amber-100","transport-stall":"bg-rose-500/30 text-rose-100","frozen-unknown":"bg-white/15 text-white/70"};function yt({label:e,value:t,window:a,strong:r=!1}){return v.jsxs("div",{className:"flex items-baseline justify-between gap-2 leading-[1.25]",children:[v.jsx("span",{className:"text-white/55 shrink-0",children:e}),v.jsxs("span",{className:"flex items-baseline gap-1 text-right",children:[v.jsx("span",{className:r?"text-white font-semibold tabular-nums":"text-white/90 tabular-nums",children:t}),a!==void 0&&v.jsx("span",{className:"text-sky-300/80 tabular-nums",children:a})]})]})}function zh({title:e,measuredAt:t,now:a}){const r=t!==null&&a-t>CL;return v.jsxs("div",{className:"flex items-baseline justify-between gap-3 mt-2 first:mt-0 pb-0.5 border-b border-white/20",children:[v.jsx("span",{className:"text-white/80 font-semibold tracking-wide uppercase text-[9px]",children:e}),v.jsxs("span",{className:r?"text-amber-300 text-[9px]":"text-white/45 text-[9px]",children:[r?"STALE · ":"",KS(t,a)]})]})}var KTe={unknown:"bg-white/50",decoding:"bg-emerald-400","decoder-stall":"bg-amber-400","transport-stall":"bg-rose-400","frozen-unknown":"bg-white/50"};function GTe(e){const{stats:t,server:a,serverError:r,serverWired:c,now:m,sessionId:d}=e,h=ML(t),f=t?.window,[k,x]=P.useState(!1),E=t!==null&&m-t.at>CL;return k?v.jsxs("div",{className:"absolute bottom-10 left-2 z-20 transform-gpu w-[13.5rem] max-h-[70%] overflow-y-auto rounded-md bg-neutral-950/95 ring-1 ring-white/25 shadow-lg px-1.5 py-1 text-[9px] font-mono text-white/90 select-text","data-testid":"stream-debug-overlay",children:[v.jsx("button",{type:"button",onClick:()=>x(!1),className:`w-full text-left rounded px-1.5 py-0.5 mb-1 text-[9px] font-semibold ${VTe[h.kind]}`,children:h.label}),v.jsx(zh,{title:"decode",measuredAt:t?.at??null,now:m}),v.jsx(yt,{label:"framesDecoded",value:ia(t?.framesDecoded),window:f?.framesDecoded===null?void 0:`+${ia(f?.framesDecoded)}`,strong:!0}),v.jsx(yt,{label:"freezeCount",value:ia(t?.freezeCount),strong:!0}),v.jsx(yt,{label:"frozen",value:ia(t?.totalFreezeMs,{suffix:"ms"}),window:f?.freezeMs===null?void 0:`+${ia(f?.freezeMs)}ms`,strong:!0}),v.jsx(yt,{label:"pliCount",value:ia(t?.pliCount),window:f?.pliCount===null?void 0:`+${ia(f?.pliCount)}`,strong:!0}),v.jsx(yt,{label:"framesDropped",value:ia(t?.framesDropped)}),v.jsx(yt,{label:"decode",value:ia(t?.avgDecodeMs,{digits:1,suffix:"ms"}),window:f?.decodeMs===null?void 0:`${ia(f?.decodeMs,{digits:1})}ms`}),v.jsx(zh,{title:"picture",measuredAt:t?.at??null,now:m}),v.jsx(yt,{label:"resolution",value:t?.width!==null&&t?.width!==void 0&&t.height!==null?`${t.width}×${t.height}`:ol}),v.jsx(yt,{label:"fps",value:ia(t?.fps)}),v.jsx(yt,{label:"codec",value:t?.codec===null||t?.codec===void 0?ol:`${t.codec}${t.codecProfileLevelId!==null?` ${t.codecProfileLevelId}`:""}`}),(t?.resolutionLog.length??0)>1&&v.jsx("div",{className:"mt-0.5 text-white/60 leading-tight",children:t?.resolutionLog.map(R=>v.jsxs("div",{className:"flex justify-between",children:[v.jsxs("span",{children:[R.width,"×",R.height]}),v.jsx("span",{className:"text-white/40",children:KS(R.at,m)})]},`${R.at}-${R.width}x${R.height}`))}),v.jsx(zh,{title:"transport",measuredAt:t?.at??null,now:m}),v.jsx(yt,{label:"bitrate",value:ia(f?.kbps,{suffix:" kbps"})}),v.jsx(yt,{label:"rtt",value:ia(t?.rttMs,{digits:0,suffix:"ms"})}),v.jsx(yt,{label:"jitter",value:ia(t?.jitterMs,{digits:1,suffix:"ms"})}),v.jsx(yt,{label:"packetsLost",value:ia(t?.packetsLost),window:f?.packetsLost===null?void 0:`+${ia(f?.packetsLost)}`}),v.jsx(yt,{label:"loss",value:ia(t?.lossPercent,{digits:2,suffix:"%"}),window:f?.lossPercent===null?void 0:ia(f?.lossPercent,{digits:2,suffix:"%"})}),v.jsx(yt,{label:"nackCount",value:ia(t?.nackCount),window:f?.nackCount===null?void 0:`+${ia(f?.nackCount)}`}),v.jsx(yt,{label:"candidate pair",value:Yi(t?.candidatePairType)}),v.jsx(yt,{label:"protocol",value:Yi(t?.candidateProtocol)}),v.jsx(yt,{label:"ice",value:Yi(t?.iceConnectionState)}),v.jsx(yt,{label:"dtls",value:Yi(t?.dtlsState)}),v.jsx(zh,{title:"server",measuredAt:a?.observedAt??null,now:m}),c?r!==null?v.jsx("div",{className:"text-rose-300 leading-tight py-0.5 break-words",children:r}):a===null?v.jsx("div",{className:"text-white/50 leading-tight py-0.5",children:"waiting for the first answer…"}):a.alive?v.jsxs(v.Fragment,{children:[v.jsx(yt,{label:"served rung",value:Yi(a.servedTier),strong:!0}),v.jsx(yt,{label:"adaptive",value:jh(a.adaptive)}),v.jsx(yt,{label:"source",value:Yi(a.camStreamId)}),v.jsx(yt,{label:"source kind",value:a.sourceKind}),v.jsx(yt,{label:"ingest node",value:Yi(a.ingestNodeId)}),v.jsx(yt,{label:"· remote",value:jh(a.ingestIsRemote)}),v.jsx(yt,{label:"egress leg",value:a.egressLeg,strong:!0}),v.jsx(yt,{label:"codec src→out",value:`${Yi(a.sourceCodec)}→${Yi(a.negotiatedCodec)}`}),v.jsx(yt,{label:"broker",value:Yi(a.brokerStatus)}),v.jsx(yt,{label:"· bitrate",value:ia(a.brokerBitrateKbps,{suffix:" kbps"})}),v.jsx(yt,{label:"· input fps",value:ia(a.brokerInputFps)}),v.jsx(yt,{label:"rtp sent",value:ia(a.rtpPacketsSent)}),v.jsx(yt,{label:"track mode",value:Yi(a.trackMode)}),a.lastDecision===null?v.jsx(yt,{label:"ladder",value:a.climbHold?"held":"never moved"}):v.jsxs(v.Fragment,{children:[v.jsx(yt,{label:"ladder move",value:`${a.lastDecision.causeDetail??a.lastDecision.cause}${a.lastDecision.tier!==null?` → ${a.lastDecision.tier}`:""}`,strong:!0}),v.jsx(yt,{label:"· when",value:KS(a.lastDecision.at,m)}),v.jsx(yt,{label:"· lossRatio",value:ia(a.lastDecision.lossRatio,{digits:4})}),v.jsx(yt,{label:"· clientKbps",value:ia(a.lastDecision.clientKbps,{suffix:" kbps"})}),v.jsx(yt,{label:"· stalledFor",value:ia(a.lastDecision.stalledForMs,{suffix:"ms"})}),v.jsx(yt,{label:"· serverSending",value:jh(a.lastDecision.serverSending)}),v.jsx(yt,{label:"· transcode-down",value:jh(a.lastDecision.forcedTranscodeDown)})]}),a.climbHold?v.jsx(yt,{label:"climb",value:a.climbHold.summary}):null,v.jsx(yt,{label:"promotions",value:ia(a.upgradeCount)}),a.tierFailures.length>0&&v.jsx(yt,{label:"tier failures",value:a.tierFailures.map(R=>`${R.tier}:${R.failures}`).join(" ")})]}):v.jsx("div",{className:"text-amber-300 leading-tight py-0.5",children:"session not found on the server — it ended, or this node never had it"}):v.jsxs("div",{className:"text-amber-300/90 leading-tight py-0.5",children:["not wired on this surface — this player was mounted without",v.jsx("span",{className:"text-white/80",children:" getSessionDebug"}),", so the server half cannot be asked"]}),d!==null&&v.jsx("div",{className:"mt-1 pt-0.5 border-t border-white/15 text-white/40 break-all leading-tight",children:d})]}):v.jsxs("button",{type:"button",onClick:()=>x(!0),className:"absolute bottom-10 left-2 z-20 transform-gpu flex items-center gap-1.5 rounded bg-neutral-950/90 ring-1 ring-white/20 px-1.5 py-0.5 text-[9px] font-mono text-white/85 tabular-nums select-text","data-testid":"stream-debug-pill",title:h.label,children:[v.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${KTe[h.kind]}`}),v.jsx("span",{children:t?.width!==null&&t?.width!==void 0?`${t.width}×${t.height}`:ol}),v.jsxs("span",{children:[ia(t?.fps),"fps"]}),v.jsxs("span",{children:[ia(f?.kbps),"k"]}),E&&v.jsx("span",{className:"text-amber-300",children:"stale"})]})}function Gs(e,t){e.muted=t;const a=e.srcObject;if(a instanceof MediaStream)for(const r of a.getAudioTracks())r.enabled=!t}function WTe(){return typeof window>"u"?!1:window.matchMedia("(hover: none) and (pointer: coarse)").matches||typeof navigator<"u"&&navigator.maxTouchPoints>0||"ontouchstart"in window}function ZTe(e,t,a){let d=0;for(let h=0;h<8;h++)for(let f=0;f<8;f++){const k=Math.min(t-1,Math.floor((f+.5)/8*t)),x=Math.min(a-1,Math.floor((h+.5)/8*a)),{data:E}=e.getImageData(k,x,1,1);.2126*(E[0]??0)+.7152*(E[1]??0)+.0722*(E[2]??0)>12&&d++}return d<=1}function E1(e){const t={};if(typeof window<"u"){const a=window.devicePixelRatio||1;if(e){const r=e.getBoundingClientRect();r.width>0&&r.height>0&&(t.viewportWidth=Math.round(r.width*a),t.viewportHeight=Math.round(r.height*a))}t.viewportWidth===void 0&&(t.viewportWidth=Math.round(window.innerWidth*a),t.viewportHeight=Math.round(window.innerHeight*a)),t.devicePixelRatio=a}return t}var Jf=TTe({now:()=>Date.now(),ttlMs:3e4});function tl(e){return MTe(e,typeof window<"u"?L4e():void 0)}function GS(e,t,a){const r=tl(e);return r===null?Promise.resolve(void 0):Jf.measured(r,()=>ITe(r,{onRefused:c=>{Jf.firstRefusal(r,c)&&a(r,c)},fetchImpl:(c,m)=>fetch(c,{...m,...t!==null?{headers:{authorization:`Bearer ${t}`}}:{}}),now:()=>Date.now()}))}function YTe(e){const t=tl(e);return t===null?void 0:Jf.cached(t)}function XTe(e){const t=tl(e);return t===null?null:Jf.latest(t)}function R4(e){return RTe({waitFrame:()=>ETe({readyState:()=>{const t=e.video();return t!==null&&t.srcObject===e.stream?t.readyState:null},signal:e.signal,sleep:t=>new Promise(a=>setTimeout(a,t)),now:()=>Date.now()}),measure:()=>GS(e.serverUrl,e.authToken,e.onRefused)})}function T4(e,t,a,r){const c={...e,...a!==void 0?{downlinkMbps:a}:{},...t};return r?xTe(c):c}var JTe=8e3;function AL({serverUrl:e,streamKey:t,label:a,autoPlay:r=!0,muted:c=!0,showControls:m=!0,showStats:d=!1,onDebugStats:h,onPlaybackStats:f,onClientNetworkSample:k,probeAuthToken:x,onConnectTiming:E,className:R="",onStateChange:T,onError:N,onReconnectAttempt:j,overlay:q,createSession:B,sendAnswer:F,handleOffer:U,getIceServers:H,addIceCandidate:Q,getIceCandidates:te,closeSession:K,getSessionState:W,getSessionDebug:oe,applyDownlinkProbe:he,reoffer:Ae,posterUrl:we,hintsOverride:Ee,onAdaptiveHints:Ie,reconnectSignal:Me,onControlChannel:Y,onVideoElement:de,iceTransportPolicy:Re,onPeerConnection:Qe}){const re=P.useRef(null),V=P.useRef(null),ie=P.useRef(null),fe=P.useRef(new Set),be=P.useRef(null),ee=P.useRef(null),Se=P.useRef(0),_e=P.useRef(!0),Be=P.useRef(Y);Be.current=Y;const Ge=P.useRef(Re);Ge.current=Re;const Ft=P.useRef(Qe);Ft.current=Qe;const Ot=P.useRef(de);Ot.current=de,P.useEffect(()=>(Ot.current?.(re.current),()=>Ot.current?.(null)),[]);const wt=P.useRef(Ie);wt.current=Ie;const sa=P.useRef(null),nt=P.useCallback((me,Ve,u)=>{const dt=wt.current;if(!dt)return;const tt={phase:me,probeOrigin:u,...Ve},pt=CTe(tt);pt!==sa.current&&(sa.current=pt,dt(tt))},[]),za=P.useRef(he);za.current=he;const ft=P.useCallback(async(me,Ve,u)=>{const dt=await _Te(za.current,me,Ve);if(!_e.current)return;if(dt.kind==="unsupported"){u();return}const{outcome:tt,tier:pt,reason:at}=dt.answer;wt.current?.({phase:"probe-in-session",probeOrigin:tl(e),downlinkMbps:Ve,probeAnswer:`${tt}:${pt??"-"}:${at}`})},[e]),lt=P.useCallback((me,Ve)=>{wt.current?.({phase:"probe-refused",probeOrigin:me,probeStatus:Ve})},[]),Dt=P.useRef(null),bt=P.useRef(null),ve=P.useRef(0),Fe=P.useRef(!1),Le=P.useRef(!1),ot=P.useRef(async()=>{}),[He,ea]=P.useState("idle"),[$t,ze]=P.useState(""),[st,Lt]=P.useState(c),Kt=P.useRef(st);Kt.current=st;const[qa,fn]=P.useState(!1),[ct,Ut]=P.useState(!1),La=WTe(),[Sa,Di]=P.useState(!0),Zn=P.useRef(null),ji=P.useRef(!1);(F||B)&&(ji.current=!0);const gn=ji.current,Pn=P.useRef(!1);U&&(Pn.current=!0);const vn=Pn.current,[xe,Oe]=P.useState(!1),xt=P.useRef(null),[ha,xn]=P.useState(null),[Yn,gi]=P.useState(!1),Mr=P.useCallback(()=>{const me=re.current;if(!(!me||me.readyState<2||!me.videoWidth||!me.videoHeight))try{const Ve=document.createElement("canvas");Ve.width=me.videoWidth,Ve.height=me.videoHeight;const u=Ve.getContext("2d");if(!u||(u.drawImage(me,0,0),ZTe(u,Ve.width,Ve.height)))return;xt.current=Ve.toDataURL("image/jpeg",.6)}catch{}},[]),fa=P.useCallback(me=>{ea(me),me==="playing"&&Oe(!0),T?.(me)},[T]),Mn=P.useCallback(()=>{if(be.current?.abort(),be.current=null,ee.current&&(clearTimeout(ee.current),ee.current=null),bt.current&&(clearTimeout(bt.current),bt.current=null),Dt.current=null,Le.current=!1,ve.current=0,ie.current&&(ie.current.close(),ie.current=null),K&&fe.current.size>0){for(const me of fe.current)K(me).catch(()=>{});fe.current.clear()}},[K]),zi=P.useCallback(()=>{be.current?.abort(),be.current=null,ee.current&&(clearTimeout(ee.current),ee.current=null),bt.current&&(clearTimeout(bt.current),bt.current=null),Dt.current=null,Le.current=!1,ve.current=0},[]),nr=1e3,Xn=P.useCallback(me=>{if(!W||!Ae)return;bt.current&&(clearTimeout(bt.current),bt.current=null);const Ve=async()=>{if(_e.current&&Dt.current===me){if(!Le.current)try{const{pendingRenegotiation:u}=await W(me);if(_e.current&&Dt.current===me&&u&&u.epoch>ve.current&&!Le.current){ve.current=u.epoch,await ot.current(me,u.target);return}}catch{}!_e.current||Dt.current!==me||(bt.current=setTimeout(()=>{Ve()},nr))}};bt.current=setTimeout(()=>{Ve()},nr)},[W,Ae]),ir=P.useCallback(async(me=!1,Ve=me,u)=>{if(!_e.current||!B||!F)return;const dt=me?ie.current:null,tt=me?new Set(fe.current):null;me?zi():Mn(),fa("connecting");const pt=new AbortController;be.current=pt;try{const at=T4(E1(V.current),Ee,Ve?u??await GS(e,x??null,lt):void 0,!Ve);nt(Ve?"probe-climb":"cold-start",at,tl(e));const{sessionId:At,sdpOffer:It,iceServers:Fa}=await B(at);if(fe.current.add(At),!_e.current||pt.signal.aborted){K?.(At).catch(()=>{}),fe.current.delete(At);return}const mt=new RTCPeerConnection(I1(Fa,Ge.current));Ft.current?.(mt),me||(ie.current=mt);const Va=new MediaStream;Ve||R4({video:()=>re.current,stream:Va,signal:pt.signal,serverUrl:e,authToken:x??null,onRefused:lt}).then(gt=>{gt===void 0||!C4(gt)||!_e.current||pt.signal.aborted||Fe.current||(Fe.current=!0,ft(At,gt,()=>{!_e.current||pt.signal.aborted||ir(!0,!0,gt)}))});let Vt=!1;const Aa=()=>{if(!(Vt||!_e.current)){if(Vt=!0,ie.current=mt,re.current&&(re.current.srcObject=Va,Gs(re.current,Kt.current),re.current.play().catch(()=>{})),dt&&dt!==mt)try{dt.close()}catch{}if(tt)for(const gt of tt)fe.current.delete(gt),K?.(gt).catch(()=>{})}};mt.ontrack=gt=>{if(console.debug("[WebRTC] ontrack",gt.track.kind,gt.track.readyState),Va.addTrack(gt.track),me){Aa();return}re.current&&(re.current.srcObject=Va,Gs(re.current,Kt.current),re.current.play().catch(()=>{}))},mt.oniceconnectionstatechange=()=>{if(!_e.current)return;const gt=mt.iceConnectionState;if(console.debug("[WebRTC] ICE state:",gt),gt==="connected"||gt==="completed")Se.current=0,me&&Aa(),fa("playing"),re.current?.paused&&(console.debug("[WebRTC] video was paused at ICE connected — calling play()"),re.current.play().catch(()=>{}));else if(gt==="failed"||gt==="disconnected"||gt==="closed"){if(me&&!Vt)try{mt.close()}catch{}fa("disconnected"),Nn()}},mt.onicecandidateerror=gt=>{console.debug("[WebRTC] ICE candidate error:",gt)},console.debug("[WebRTC] Setting remote description (server offer)..."),await mt.setRemoteDescription({type:"offer",sdp:It});const Dn=await mt.createAnswer();if(await mt.setLocalDescription(Dn),console.debug("[WebRTC] Local description set, waiting for ICE gathering..."),await _4(mt),!_e.current)return;const Ka=(mt.localDescription?.sdp??"").split(`
84
84
  `).filter(gt=>gt.startsWith("a=candidate:")).length;console.debug("[WebRTC] Sending answer to server",{localCandidates:Ka,sessionId:At.slice(0,8)}),await F(At,mt.localDescription?.sdp??""),console.debug("[WebRTC] Answer sent successfully");const en=mt,on=()=>{const gt=en.connectionState;if(gt==="closed"||gt==="failed")return;const Ui=re.current;Ui&&Ui.readyState===0&&console.log(`[WebRTC] no video data yet (ice=${en.iceConnectionState})`)};setTimeout(on,3e3),setTimeout(on,8e3)}catch(at){if(!_e.current)return;const At=at instanceof Error?at.message:String(at);ze(At),fa("error"),N?.(At),Nn()}},[e,t,B,F,Mn,zi,K,fa,N,Ee,nt,x,lt,ft]),fo=P.useCallback(async()=>{if(_e.current){Mn(),fa("connecting");try{const me=new RTCPeerConnection({iceServers:[{urls:"stun:stun.l.google.com:19302"}]});ie.current=me,me.addTransceiver("video",{direction:"recvonly"}),me.addTransceiver("audio",{direction:"recvonly"});const Ve=new MediaStream;me.ontrack=at=>{Ve.addTrack(at.track),re.current&&(re.current.srcObject=Ve,Gs(re.current,Kt.current),re.current.play().catch(()=>{}))},me.oniceconnectionstatechange=()=>{if(!_e.current)return;const at=me.iceConnectionState;at==="connected"||at==="completed"?(Se.current=0,fa("playing"),re.current?.paused&&re.current.play().catch(()=>{})):(at==="failed"||at==="disconnected"||at==="closed")&&(fa("disconnected"),Nn())};const u=await me.createOffer();if(await me.setLocalDescription(u),await _4(me),!_e.current)return;const dt=`${e}/api/webrtc?src=${encodeURIComponent(t)}`,tt=await fetch(dt,{method:"POST",headers:{"Content-Type":"application/sdp"},body:me.localDescription?.sdp??""});if(!tt.ok)throw new Error(`WHEP ${tt.status}: ${tt.statusText}`);const pt=await tt.text();await me.setRemoteDescription({type:"answer",sdp:pt})}catch(me){if(!_e.current)return;const Ve=me instanceof Error?me.message:String(me);ze(Ve),fa("error"),N?.(Ve),Nn()}}},[e,t,Mn,fa,N]),yn=P.useCallback(async(me=!1,Ve=me,u)=>{if(!_e.current||!U)return;const dt=me?ie.current:null,tt=me?new Set(fe.current):null;me?zi():Mn(),fa("connecting");const pt=new AbortController;be.current=pt;const at=performance.now(),At=()=>Math.round(performance.now()-at),It={};try{const Fa=await H?.();if(It.iceServersMs=At(),!_e.current||pt.signal.aborted)return;const mt=new RTCPeerConnection(I1(Fa,Ge.current));Ft.current?.(mt),me||(ie.current=mt);const Va=new MediaStream;let Vt=null;Ve||R4({video:()=>re.current,stream:Va,signal:pt.signal,serverUrl:e,authToken:x??null,onRefused:lt}).then(Et=>{Et===void 0||!C4(Et)||!_e.current||pt.signal.aborted||Fe.current||(Fe.current=!0,ft(Vt,Et,()=>{!_e.current||pt.signal.aborted||yn(!0,!0,Et)}))});let Aa=!1;const Dn=()=>{if(!(Aa||!_e.current)){if(Aa=!0,ie.current=mt,re.current&&(re.current.srcObject=Va,Gs(re.current,Kt.current),re.current.play().catch(()=>{})),dt&&dt!==mt)try{dt.close()}catch{}if(tt)for(const Et of tt)fe.current.delete(Et),K?.(Et).catch(()=>{})}};mt.ontrack=Et=>{if(It.firstTrackMs===void 0&&(It.firstTrackMs=At()),console.debug("[WebRTC] ontrack (client-offer)",Et.track.kind,Et.track.readyState),Va.addTrack(Et.track),me){Dn();return}re.current&&(re.current.srcObject=Va,Gs(re.current,Kt.current),re.current.play().catch(()=>{}))};let Ka=!1;mt.oniceconnectionstatechange=()=>{if(!_e.current)return;const Et=mt.iceConnectionState;if(console.debug("[WebRTC] ICE state (client-offer):",Et),Et==="connected"||Et==="completed"){if(!Ka){Ka=!0,It.iceConnectedMs=At(),console.info("[WebRTC timing] client-offer connected",{streamKey:t,...It}),E?.({...It});const tn=re.current;tn&&"requestVideoFrameCallback"in tn&&(tn.requestVideoFrameCallback(()=>{It.firstFrameMs=At(),console.info("[WebRTC timing] first decoded frame",{streamKey:t,firstFrameMs:It.firstFrameMs}),E?.({...It})}),setTimeout(()=>{_e.current&&It.firstFrameMs===void 0&&(console.warn("[WebRTC timing] NO decoded frame (stalled)",{streamKey:t,sinceIceConnectedMs:At()-(It.iceConnectedMs??0),iceConnectedMs:It.iceConnectedMs,firstTrackMs:It.firstTrackMs}),qi.current("no decoded frame after connect"),Nn())},JTe))}Se.current=0,me&&Dn(),fa("playing"),re.current?.paused&&re.current.play().catch(()=>{})}else if(Et==="failed"||Et==="disconnected"||Et==="closed"){if(me&&!Aa)try{mt.close()}catch{}fa("disconnected"),Nn()}};let en=null;const on=[];if(mt.onicecandidate=Et=>{if(!Et.candidate)return;const tn=Et.candidate.toJSON();en&&Q?Q(en,tn).catch(()=>{}):on.push(tn)},mt.addTransceiver("video",{direction:"recvonly"}),mt.addTransceiver("audio",{direction:"recvonly"}),Be.current){const Et=mt.createDataChannel("camstack-control");Be.current(Et)}const gt=await mt.createOffer();if(It.offerCreatedMs=At(),await mt.setLocalDescription(gt),It.localSetMs=At(),!_e.current||pt.signal.aborted)return;const Ui=Ve?u??await GS(e,x??null,lt):void 0,bi=T4(E1(V.current),Ee,Ui,!Ve);nt(Ve?"probe-climb":"cold-start",bi,tl(e));const Tr=At(),{sessionId:rt,sdpAnswer:lr}=await U(mt.localDescription?.sdp??gt.sdp??"",void 0,bi);if(It.signalingRttMs=At()-Tr,en=rt,Vt=rt,fe.current.add(rt),Dt.current=rt,!_e.current||pt.signal.aborted){K?.(rt).catch(()=>{}),fe.current.delete(rt);return}if(Q)for(const Et of on)Q(rt,Et).catch(()=>{});if(on.length=0,await mt.setRemoteDescription({type:"answer",sdp:lr}),It.answerSetMs=At(),console.debug("[WebRTC] Client-offer answer set (trickle)",{sessionId:rt.slice(0,8)}),te){const Et=new Set,tn=Date.now(),ko=async()=>{if(!(!_e.current||pt.signal.aborted)&&!(mt.connectionState==="closed"||mt.signalingState==="closed")){try{const{candidates:_r,done:Ms}=await te(rt);for(const Cs of _r){const kl=Cs.candidate??"";kl&&!Et.has(kl)&&(Et.add(kl),mt.addIceCandidate(new RTCIceCandidate(Cs)).catch(()=>{}))}const Hi=mt.iceConnectionState;if(Ms||Date.now()-tn>1e4||Hi==="connected"||Hi==="completed")return}catch{}setTimeout(()=>{ko()},200)}};ko()}Xn(rt)}catch(Fa){if(!_e.current)return;const mt=Fa instanceof Error?Fa.message:String(Fa);ze(mt),fa("error"),N?.(mt),Nn()}},[e,U,H,Q,te,K,Mn,zi,fa,N,Xn,Ee,nt,x,lt,ft]);ot.current=P.useCallback(async(me,Ve)=>{const u=Ae;if(!_e.current||!u)return;const dt=ie.current;Le.current=!0;try{let tt=function(){if(It||!_e.current){Aa();return}It=!0,ie.current=at,re.current&&(re.current.srcObject=At,re.current.play().catch(()=>{})),dt&&dt!==at&&dt.close(),Aa()};const pt=await H?.();if(!_e.current)return;const at=new RTCPeerConnection(I1(pt,Ge.current));Ft.current?.(at);const At=new MediaStream;let It=!1,Fa=!1,mt=null,Va,Vt;const Aa=()=>{Vt!==void 0&&(clearTimeout(Vt),Vt=void 0);const rt=mt;if(mt=null,!!rt){Va!==void 0&&typeof rt.cancelVideoFrameCallback=="function"&&rt.cancelVideoFrameCallback(Va),rt.removeEventListener("loadeddata",tt);try{rt.srcObject=null}catch{}rt.remove()}},Dn=()=>{if(Fa||It||!_e.current)return;if(Fa=!0,typeof document>"u"){tt();return}const rt=document.createElement("video");rt.muted=!0,rt.playsInline=!0,rt.autoplay=!0,rt.style.cssText="position:absolute;left:-9999px;top:0;width:1px;height:1px;opacity:0;pointer-events:none;",rt.srcObject=At,mt=rt,(V.current??document.body).appendChild(rt),rt.play().catch(()=>{}),typeof rt.requestVideoFrameCallback=="function"&&(Va=rt.requestVideoFrameCallback(()=>tt())),rt.addEventListener("loadeddata",tt,{once:!0}),Vt=setTimeout(()=>tt(),1800)};at.ontrack=rt=>{console.debug("[WebRTC] ontrack (reoffer)",rt.track.kind,rt.track.readyState),At.addTrack(rt.track),Dn()},at.oniceconnectionstatechange=()=>{if(!_e.current)return;const rt=at.iceConnectionState;console.debug("[WebRTC] ICE state (reoffer):",rt),rt==="connected"||rt==="completed"?(Se.current=0,Dn(),fa("playing"),re.current?.paused&&re.current.play().catch(()=>{})):(rt==="failed"||rt==="closed")&&(Aa(),!It&&rt==="failed"&&at.close(),fa("disconnected"),Nn())};let Ka=null;const en=[];if(at.onicecandidate=rt=>{if(!rt.candidate)return;const lr=rt.candidate.toJSON();Ka&&Q?Q(Ka,lr).catch(()=>{}):en.push(lr)},at.addTransceiver("video",{direction:"recvonly"}),at.addTransceiver("audio",{direction:"recvonly"}),Be.current){const rt=at.createDataChannel("camstack-control");Be.current(rt)}const on=await at.createOffer();if(await at.setLocalDescription(on),!_e.current){at.close();return}const gt=YTe(e),Ui={...E1(V.current),...gt!==void 0?{downlinkMbps:gt}:{},...Ee};nt("renegotiate",Ui,tl(e));const{sessionId:bi,sdpAnswer:Tr}=await u(me,at.localDescription?.sdp??on.sdp??"",Ve,Ui);if(!_e.current){at.close();return}if(Ka=bi,fe.current.add(bi),Dt.current=bi,Q)for(const rt of en)Q(bi,rt).catch(()=>{});if(en.length=0,await at.setRemoteDescription({type:"answer",sdp:Tr}),te){const rt=new Set,lr=Date.now(),Et=async()=>{if(_e.current&&!(at.connectionState==="closed"||at.signalingState==="closed")){try{const{candidates:tn,done:ko}=await te(bi);for(const Ms of tn){const Hi=Ms.candidate??"";Hi&&!rt.has(Hi)&&(rt.add(Hi),at.addIceCandidate(new RTCIceCandidate(Ms)).catch(()=>{}))}const _r=at.iceConnectionState;if(ko||Date.now()-lr>1e4||_r==="connected"||_r==="completed")return}catch{}setTimeout(()=>{Et()},200)}};Et()}Xn(bi)}catch(tt){console.debug("[WebRTC] reoffer failed; keeping last frame, re-arming poll",tt instanceof Error?tt.message:String(tt)),Xn(me)}finally{Le.current=!1}},[e,Ae,H,Q,te,fa,Xn,Ee,nt]);const ta=vn?yn:gn?ir:fo,Ba=P.useRef(()=>{}),Jn=P.useRef(j);Jn.current=j;const qi=P.useRef(()=>{});qi.current=me=>{console.warn("[WebRTC] hard error",{streamKey:t,msg:me}),ze(me),N?.(me),fa("error")},Ba.current=ta;const Nn=P.useCallback(()=>{if(!_e.current)return;const me=Se.current,Ve=vTe(me);if(Jn.current?.(Ve),Ve.kind==="exhausted"){qi.current(`reconnect attempts exhausted (${Ve.attempts})`);return}Se.current+=1,ee.current=setTimeout(()=>{_e.current&&Ba.current()},Ve.delayMs)},[]);P.useEffect(()=>(_e.current=!0,Se.current=0,r&&ta(),()=>{_e.current=!1,Mn()}),[]);const go=P.useRef(!1);P.useEffect(()=>{if(r){if(vn){if(!U)return}else if(gn){if(!B||!F)return}else return;go.current||ie.current||(go.current=!0,ta())}},[r,vn,gn,U,B,F,ta]);const Cr=()=>{Se.current=0,ta()},vi=()=>{if(Se.current=0,ie.current&&vn){yn(!0);return}if(ie.current&&gn){ir(!0);return}ta()},rr=P.useRef(e),ei=P.useRef(t);P.useEffect(()=>{const me=rr.current!==e,Ve=ei.current!==t;if(rr.current=e,ei.current=t,!(!me&&!Ve)&&_e.current){if(Se.current=0,Fe.current=!1,me){Mn(),ta();return}vi()}},[e,t]);const ti=P.useRef(Me);P.useEffect(()=>{ti.current!==Me&&(ti.current=Me,_e.current&&vi())},[Me]);const Li=()=>{if(re.current){const me=!re.current.muted;Gs(re.current,me),Lt(me)}},yi=async()=>{if(V.current)try{if(document.fullscreenElement){await document.exitFullscreen();return}if(V.current.requestFullscreen){await V.current.requestFullscreen();return}const me=re.current;me?.webkitEnterFullscreen&&me.webkitEnterFullscreen()}catch(me){console.warn(`Fullscreen toggle failed: ${me instanceof Error?me.message:me}`)}},wa=async()=>{const me=re.current;if(me)try{if(typeof me.webkitSetPresentationMode=="function"){me.webkitSetPresentationMode(me.webkitPresentationMode==="picture-in-picture"?"inline":"picture-in-picture");return}document.pictureInPictureElement?await document.exitPictureInPicture():await me.requestPictureInPicture()}catch(Ve){console.warn(`PiP toggle failed: ${Ve instanceof Error?Ve.message:String(Ve)}`)}},vo=()=>{if(!re.current)return;const me=document.createElement("canvas");me.width=re.current.videoWidth||1280,me.height=re.current.videoHeight||720;const Ve=me.getContext("2d");if(!Ve)return;Ve.drawImage(re.current,0,0);const u=document.createElement("a");u.download=`${t.replace(/[/:]/g,"-")}-${Date.now()}.jpg`,u.href=me.toDataURL("image/jpeg",.92),u.click()};P.useEffect(()=>{const me=()=>fn(!!document.fullscreenElement);document.addEventListener("fullscreenchange",me);const Ve=re.current;return Ve?.addEventListener("webkitbeginfullscreen",me),Ve?.addEventListener("webkitendfullscreen",me),()=>{document.removeEventListener("fullscreenchange",me),Ve?.removeEventListener("webkitbeginfullscreen",me),Ve?.removeEventListener("webkitendfullscreen",me)}},[]),P.useEffect(()=>{const me=re.current,Ve=typeof document<"u"&&document.pictureInPictureEnabled===!0,u=me!==null&&typeof me.webkitSetPresentationMode=="function";Ut(Ve||u)},[]);const[Ar,On]=P.useState(null),[ai,yo]=P.useState(null),[Ir,Bi]=P.useState(null),[ws,or]=P.useState(()=>Date.now()),ni=d||h!==void 0;P.useEffect(()=>{if(!d)return;const me=setInterval(()=>or(Date.now()),500);return()=>clearInterval(me)},[d]),P.useEffect(()=>{if(!ni){On(null);return}const me={current:null};let Ve=!1;const u=async()=>{const tt=ie.current;if(tt)try{const pt=await tt.getStats();if(Ve)return;const at=BTe({report:pt,prev:me.current,now:Date.now(),iceConnectionState:tt.iceConnectionState,dtlsState:tt.connectionState});me.current=at,On(at)}catch{}};u();const dt=setInterval(()=>{u()},1e3);return()=>{Ve=!0,clearInterval(dt)}},[ni]),P.useEffect(()=>{if(!ni||!oe){yo(null),Bi(null);return}let me=!1;const Ve=async()=>{const dt=Dt.current;if(dt===null){Bi("no session id on this player yet — nothing to ask the server about");return}try{const tt=await oe(dt);if(me)return;yo(tt),Bi(null)}catch(tt){if(me)return;Bi(tt instanceof Error?tt.message:String(tt))}};Ve();const u=setInterval(()=>{Ve()},1e3);return()=>{me=!0,clearInterval(u)}},[ni,oe]);const bn=P.useRef(h);bn.current=h,P.useEffect(()=>{if(h===void 0)return;const me=()=>{bn.current?.({at:Date.now(),verdict:ML(Qa.current).kind,sessionId:Dt.current,stats:Qa.current,server:Er.current,serverError:bo.current,serverWired:oe!==void 0})};me();const Ve=setInterval(me,1e3);return()=>clearInterval(Ve)},[h===void 0,oe]);const Qa=P.useRef(null);Qa.current=Ar;const Er=P.useRef(null);Er.current=ai;const bo=P.useRef(null);bo.current=Ir;const Fi=P.useRef(null);P.useEffect(()=>{if(!k){Fi.current=null;return}const me=async()=>{const u=ie.current;if(u)try{const dt=await u.getStats();let tt=0,pt=0,at=0,At=0,It=0,Fa=0;dt.forEach(Va=>{const Vt=Va;Vt.type==="inbound-rtp"&&(Vt.kind??Vt.mediaType)==="video"?(tt=Vt.packetsLost??0,pt=Vt.packetsReceived??0,at=Vt.bytesReceived??0,At=Vt.timestamp,It=Vt.jitter??0):Vt.type==="candidate-pair"&&Vt.nominated&&typeof Vt.currentRoundTripTime=="number"&&(Fa=Vt.currentRoundTripTime)});const mt=NTe(Fi.current,{pc:u,lost:tt,recv:pt,bytes:at,ts:At,rttS:Fa,jitterS:It},{renegotiating:Le.current,probe:XTe(e)});Fi.current=mt.baseline,mt.sample!==null&&k(mt.sample)}catch{}},Ve=setInterval(()=>{me()},2e3);return()=>clearInterval(Ve)},[k,e]);const sr=P.useRef(null);P.useEffect(()=>{if(!f){sr.current=null;return}const me=async()=>{const u=ie.current,dt=re.current;if(u)try{const tt=await u.getStats();let pt=0,at=0,At=0,It=0,Fa=0,mt=0,Va=0,Vt=0;tt.forEach(on=>{const gt=on;gt.type==="inbound-rtp"&&(gt.kind??gt.mediaType)==="video"&&(pt=gt.framesReceived??0,at=gt.framesDecoded??0,At=gt.framesDropped??0,It=gt.framesPerSecond??0,Fa=gt.freezeCount??0,mt=gt.totalFreezesDuration??0,Va=gt.jitterBufferDelay??0,Vt=gt.jitterBufferEmittedCount??0)});const Aa=dt?.currentTime??0,Dn=Date.now(),Ka=sr.current,en=Vt>0?Math.round(Va/Vt*1e3):0;Ka&&f({dRecv:pt-Ka.recv,dDec:at-Ka.dec,dDrop:At-Ka.drop,fps:Math.round(It),dFreeze:Fa-Ka.freeze,freezeTotalMs:Math.round(mt*1e3),avgJitterMs:en,dCtMs:Math.round((Aa-Ka.ct)*1e3),dtMs:Dn-Ka.ts,readyState:dt?.readyState??-1}),sr.current={recv:pt,dec:at,drop:At,freeze:Fa,ct:Aa,ts:Dn}}catch{}};me();const Ve=setInterval(()=>{me()},5e3);return()=>clearInterval(Ve)},[f]),P.useEffect(()=>{Lt(c);const me=re.current;me&&(Gs(me,c),c||me.play().catch(()=>{}))},[c]);const $i=()=>{La||(Di(!0),Zn.current&&clearTimeout(Zn.current),Zn.current=setTimeout(()=>Di(!1),3e3))},xs=()=>{Di(me=>!me),Zn.current&&clearTimeout(Zn.current)};P.useEffect(()=>{if(He==="playing"){Mr();const me=setInterval(Mr,2e3);return()=>clearInterval(me)}xe&&xt.current&&xn(xt.current)},[He,xe,Mr]),P.useEffect(()=>{if(He!=="playing"){gi(!1);return}const me=re.current;if(!me)return;let Ve=!1;const u=()=>{Ve||gi(!0)};let dt;typeof me.requestVideoFrameCallback=="function"&&(dt=me.requestVideoFrameCallback(()=>u())),me.addEventListener("loadeddata",u,{once:!0});const tt=setTimeout(u,12e3);return()=>{Ve=!0,clearTimeout(tt),dt!==void 0&&typeof me.cancelVideoFrameCallback=="function"&&me.cancelVideoFrameCallback(dt),me.removeEventListener("loadeddata",u)}},[He]);const xa=xe&&ha?ha:we??null,Rr=!Yn&&xa!==null;return v.jsxs("div",{ref:V,className:`relative isolate bg-black overflow-hidden group ${R}`,onMouseMove:$i,onMouseEnter:$i,onTouchStart:xs,children:[v.jsx("video",{ref:re,autoPlay:r,muted:st,playsInline:!0,className:"w-full h-full object-contain relative z-0"}),Rr&&xa&&v.jsx("img",{src:xa,alt:"",className:"absolute inset-0 w-full h-full object-contain z-[5] transform-gpu pointer-events-none"}),a&&He==="playing"&&v.jsx("div",{className:"absolute top-2 left-2 z-10 transform-gpu px-2 py-0.5 rounded bg-black/60 text-[10px] text-white font-medium",children:a}),d&&v.jsx(GTe,{stats:Ar,server:ai,serverError:Ir,serverWired:oe!==void 0,now:ws,sessionId:Dt.current}),q,m&&!xa&&He==="connecting"&&v.jsxs("div",{className:"absolute inset-0 z-10 transform-gpu flex flex-col items-center justify-center bg-black/70 gap-2",children:[v.jsx("svg",{className:"h-6 w-6 text-white/60 animate-spin",viewBox:"0 0 24 24",fill:"none",children:v.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeDasharray:"32",strokeDashoffset:"32",className:"animate-[dash_1.5s_ease-in-out_infinite]"})}),v.jsx("span",{className:"text-xs text-white/60",children:"Connecting…"})]}),m&&!xa&&(He==="error"||He==="disconnected")&&v.jsxs("div",{className:"absolute inset-0 z-10 transform-gpu flex flex-col items-center justify-center bg-black/70 gap-2",children:[v.jsx("svg",{className:"h-6 w-6 text-red-400",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:v.jsx("path",{d:"M1 1l5.5 5.5M23 23l-5.5-5.5M8.11 15.89a8 8 0 0110.78-10.78M3.64 3.64A12 12 0 0020.36 20.36",strokeLinecap:"round"})}),v.jsx("span",{className:"text-xs text-red-400 text-center px-4",children:He==="error"?$t||"Connection failed":"Disconnected"}),v.jsx("button",{onClick:Cr,className:"mt-1 inline-flex items-center gap-1.5 rounded px-3 py-1 text-xs bg-white/10 text-white hover:bg-white/20 transition-colors",children:"Reconnect"})]}),m&&xa&&(He==="connecting"||He==="disconnected")&&v.jsx("div",{className:"absolute top-2 left-2 z-10 transform-gpu flex h-6 w-6 items-center justify-center rounded-full bg-black/55",children:v.jsx("svg",{className:"h-3.5 w-3.5 text-white/90 animate-spin",viewBox:"0 0 24 24",fill:"none",children:v.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeDasharray:"32",strokeDashoffset:"32",className:"animate-[dash_1.5s_ease-in-out_infinite]"})})}),m&&xa&&He==="error"&&v.jsx("button",{onClick:Cr,title:$t||"Reconnect",className:"absolute top-2 left-2 z-10 transform-gpu flex h-6 w-6 items-center justify-center rounded-full bg-black/55 text-white/90 hover:bg-black/75 transition-colors",children:v.jsxs("svg",{className:"h-3.5 w-3.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[v.jsx("path",{d:"M23 4v6h-6M1 20v-6h6"}),v.jsx("path",{d:"M3.51 9a9 9 0 0114.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0020.49 15"})]})}),m&&He!=="idle"&&He!=="error"&&v.jsxs("div",{className:`absolute bottom-0 inset-x-0 z-20 transform-gpu flex items-center justify-between px-3 py-1.5 bg-gradient-to-t from-black/80 to-transparent transition-opacity duration-200 ${La||Sa?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none"}`,children:[v.jsx("div",{className:"flex items-center gap-1",children:v.jsx(qh,{onClick:Li,title:st?"Unmute":"Mute",children:st?v.jsxs("svg",{className:"h-3.5 w-3.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[v.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),v.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),v.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]}):v.jsxs("svg",{className:"h-3.5 w-3.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[v.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),v.jsx("path",{d:"M19.07 4.93a10 10 0 010 14.14M15.54 8.46a5 5 0 010 7.07"})]})})}),v.jsxs("div",{className:"flex items-center gap-1",children:[v.jsx(qh,{onClick:vo,title:"Take snapshot",children:v.jsxs("svg",{className:"h-3.5 w-3.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[v.jsx("path",{d:"M23 19a2 2 0 01-2 2H3a2 2 0 01-2-2V8a2 2 0 012-2h4l2-3h6l2 3h4a2 2 0 012 2z"}),v.jsx("circle",{cx:"12",cy:"13",r:"4"})]})}),ct&&v.jsx(qh,{onClick:wa,title:"Picture-in-Picture",children:v.jsxs("svg",{className:"h-3.5 w-3.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[v.jsx("path",{d:"M21 9V6a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2h4"}),v.jsx("rect",{width:"10",height:"7",x:"12",y:"13",rx:"2"})]})}),v.jsx(qh,{onClick:yi,title:qa?"Exit fullscreen":"Fullscreen",children:qa?v.jsx("svg",{className:"h-3.5 w-3.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:v.jsx("path",{d:"M8 3v3a2 2 0 01-2 2H3m18 0h-3a2 2 0 01-2-2V3m0 18v-3a2 2 0 012-2h3M3 16h3a2 2 0 012 2v3"})}):v.jsx("svg",{className:"h-3.5 w-3.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:v.jsx("path",{d:"M8 3H5a2 2 0 00-2 2v3m18 0V5a2 2 0 00-2-2h-3m0 18h3a2 2 0 002-2v-3M3 16v3a2 2 0 002 2h3"})})})]})]})]})}function qh({onClick:e,title:t,children:a}){return v.jsx("button",{onClick:e,title:t,className:"rounded-full p-1.5 min-w-[44px] min-h-[44px] flex items-center justify-center text-white/80 hover:text-white hover:bg-white/20 active:bg-white/30 transition-colors",children:a})}async function _4(e){if(e.iceGatheringState!=="complete")return new Promise(t=>{let a=!1,r;const c=()=>{a||(a=!0,r&&clearInterval(r),e.removeEventListener("icegatheringstatechange",m),t())},m=()=>{e.iceGatheringState==="complete"&&c()};e.addEventListener("icegatheringstatechange",m);const d=Date.now();r=setInterval(()=>{const h=e.localDescription?.sdp??"";/ typ host/.test(h)&&Date.now()-d>=600&&c()},100),setTimeout(c,2500)})}var e_e=5*6e4,t_e=720*6e4,a_e="camstack:turn-servers:v1";function n_e(){const e=globalThis;try{return e.localStorage??null}catch{return null}}function i_e(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.fetchedAt!="number"||!Array.isArray(t.servers)?!1:t.servers.every(a=>{if(typeof a!="object"||a===null)return!1;const r=a;return!(!(typeof r.urls=="string"||Array.isArray(r.urls)&&r.urls.every(c=>typeof c=="string"))||r.username!==void 0&&typeof r.username!="string"||r.credential!==void 0&&typeof r.credential!="string")})}var r_e=class{freshTtlMs;staleCapMs;storage;now;storageKey;memory=new WeakMap;inflight=new WeakMap;constructor(e={}){this.freshTtlMs=e.freshTtlMs??e_e,this.staleCapMs=e.staleCapMs??t_e,this.storage="storage"in e?e.storage??null:n_e(),this.now=e.now??(()=>Date.now()),this.storageKey=e.storageKey??a_e}async getOrFetch(e,t){const a=this.now(),r=this.memory.get(e)??this.readStorage();if(r){const c=a-r.fetchedAt;if(c<this.freshTtlMs)return r.servers;if(c<this.staleCapMs)return this.startFetch(e,t,r),r.servers}return this.startFetch(e,t,r)}startFetch(e,t,a){const r=this.inflight.get(e);if(r)return r;const c=(async()=>{try{const m=await t();if(m.length>0){const d={servers:m,fetchedAt:this.now()};this.memory.set(e,d),this.writeStorage(d)}return m}catch{return a?.servers}})().finally(()=>{this.inflight.delete(e)});return this.inflight.set(e,c),c}readStorage(){if(this.storage)try{const e=this.storage.getItem(this.storageKey);if(e===null)return;const t=JSON.parse(e);return i_e(t)?t:void 0}catch{return}}writeStorage(e){if(this.storage)try{this.storage.setItem(this.storageKey,JSON.stringify(e))}catch{}}},o_e=new r_e;function IL(e,t,a=5e3){const[r,c]=P.useState([]);P.useEffect(()=>{if(t===null)return;let T=!1;const N=()=>{e.webrtcSession.listStreams.query({deviceId:t}).then(q=>{T||c(q)}).catch(()=>{})};N();const j=setInterval(N,a);return()=>{T=!0,clearInterval(j)}},[e,t,a]);const[m,d]=P.useState(null);P.useEffect(()=>{if(t===null)return;let T=!1;return e.pipelineOrchestrator&&e.pipelineOrchestrator.getCameraMetrics.query({deviceId:t}).then(N=>{T||!N||d({phase:N.phase,detectionFps:N.actualFps,avgInferenceMs:N.avgInferenceTimeMs,droppedFrames:N.droppedFrames})}).catch(()=>{}),()=>{T=!0}},[e,t]),kr("pipeline.camera-metrics-snapshot",T=>{if(t===null)return;const N=T.data;N.deviceId!==t||!N.metrics||d({phase:N.metrics.phase,detectionFps:N.metrics.actualFps,avgInferenceMs:N.metrics.avgInferenceTimeMs,droppedFrames:N.metrics.droppedFrames})});const{streams:h,hasWebrtc:f}=P.useMemo(()=>t===null||r.length===0?{streams:[],hasWebrtc:!1}:{streams:r.map(T=>({id:T.id,label:T.label,target:T.target,status:T.status,inputFps:T.inputFps,bitrateKbps:T.bitrateKbps})),hasWebrtc:!0},[t,r]),k=P.useCallback(async()=>{const T=e.turnProvider;if(T)return o_e.getOrFetch(e,async()=>(await T.getTurnServers.query()).map(N=>({urls:typeof N.urls=="string"?N.urls:[...N.urls],...N.username!==void 0?{username:N.username}:{},...N.credential!==void 0?{credential:N.credential}:{}})))},[e]);P.useEffect(()=>{k()},[k]);const x=P.useCallback(async(T,N)=>{if(t===null)throw new Error("No device selected");const j=await e.webrtcSession.createSession.mutate({deviceId:t,target:T,hints:N}),q=await k();return{sessionId:j.sessionId,sdpOffer:j.sdpOffer,...q?{iceServers:q}:{}}},[e,t,k]),E=P.useCallback(async(T,N,j,q)=>{if(t===null)throw new Error("No device selected");return e.webrtcSession.handleOffer.mutate({deviceId:t,target:T,sdpOffer:N,...j!==void 0?{sessionId:j}:{},...q!==void 0?{hints:q}:{}})},[e,t]),R=P.useCallback(async(T,N)=>{if(t===null)throw new Error("No device selected");await e.webrtcSession.handleAnswer.mutate({deviceId:t,sessionId:T,sdpAnswer:N})},[e,t]);return{streams:h,hasWebrtc:f,pipelineMetrics:m,createSession:x,handleOffer:E,getIceServers:k,addIceCandidate:P.useCallback(async(T,N)=>{t!==null&&await e.webrtcSession.addIceCandidate.mutate({deviceId:t,sessionId:T,candidate:N.candidate??"",sdpMid:N.sdpMid??null,sdpMLineIndex:N.sdpMLineIndex??null}).catch(()=>{})},[e,t]),getIceCandidates:P.useCallback(async T=>t===null?{candidates:[],done:!0}:e.webrtcSession.getIceCandidates.query({deviceId:t,sessionId:T}),[e,t]),sendAnswer:R,closeSession:P.useCallback(async T=>{t!==null&&await e.webrtcSession.closeSession.mutate({deviceId:t,sessionId:T}).catch(()=>{})},[e,t]),getSessionState:P.useCallback(async T=>{if(t===null)return{pendingRenegotiation:null};try{return await e.webrtcSession.getSessionState.query({deviceId:t,sessionId:T})}catch{return{pendingRenegotiation:null}}},[e,t]),getSessionDebug:P.useCallback(async T=>{if(t===null)throw new Error("getSessionDebug: no device bound to this player");return e.webrtcSession.getSessionDebug.query({deviceId:t,sessionId:T})},[e,t]),applyDownlinkProbe:P.useCallback(async(T,N)=>{const j=e.webrtcSession.applyDownlinkProbe;if(t===null||j===void 0)throw new Error("applyDownlinkProbe: not available for this player");return j.mutate({deviceId:t,sessionId:T,downlinkMbps:N})},[e,t])}}var R1=["day","ir"],s_e={day:"Daylight",ir:"Night (IR)",night:"Night",dawn:"Dawn",dusk:"Dusk"};function ff(e){return s_e[e]??e}function O8e(e){const t=new Set(e.coveredConditions),a=R1.map(d=>`${ff(d)} ${t.has(d)?"✓":"✗"}`),r=[...t].filter(d=>!R1.some(h=>h===d));for(const d of r)a.push(`${ff(d)} ✓`);const c=R1.filter(d=>!t.has(d));if(c.length===0)return a.join(" · ");if(t.size===0)return`${a.join(" · ")} — nothing captured yet, so this scene is not watching.`;const m=c.map(d=>ff(d).toLowerCase()).join(" and ");return e.onUncoveredCondition==="judge-anyway"?`${a.join(" · ")} — ${m} judged against the references you do have.`:`${a.join(" · ")} — optional; checks in ${m} are skipped.`}function l_e(e){if(e.suspendedCondition===null)return null;const t=ff(e.suspendedCondition).toLowerCase();return`Paused — nothing was captured in ${t}, so checks are on hold until the light changes back. Capture ${t} if you want it watched around the clock.`}var c_e={"no-reference-for-condition":"can’t tell — nothing has been captured for this scene yet. Press “Capture daylight” to photograph what normal looks like.","view-shifted":"can’t tell — the camera view has moved since the reference was captured. Re-capture it.","no-vision-profile":"can’t tell — the vision model is unreachable, so the change is on hold.","encoder-model-changed":"can’t tell — the embedding model changed, so the stored references are unreadable. Re-capture them.","no-snapshot":"can’t tell — this camera did not return a frame."};function D8e(e,t){if(e.states.length===0)return"Not armed yet — capture the initial state to start watching.";if(e.verdict==="unknown")return e.unavailable!==null?c_e[e.unavailable]:"can’t tell right now.";const a=e.verdict==="diverged"?e.divergedAt:e.armedAt,r=a!==null?` for ${u_e(Math.max(0,t-a))}`:"";if(e.latched)return e.verdict==="diverged"?`CHANGED${r} — press Reset when you have dealt with it.`:`Back to normal, but still flagged as changed${r}. Press Reset to clear it.`;const c=l_e(e);return c!==null?c:e.verdict==="diverged"?`CHANGED${r}`:`Normal${r}`}function j8e(e){return e.states.length===0?{text:"Not armed",tone:"unknown"}:e.latched?{text:"Changed",tone:"alarm"}:e.suspendedCondition!==null?{text:"Paused",tone:"unknown"}:e.verdict==="unknown"?{text:"Can’t tell",tone:"unknown"}:e.verdict==="diverged"?{text:"Changed",tone:"alarm"}:{text:"Normal",tone:"ok"}}var d_e=.4;function z8e(e){return e.width*e.height>d_e}function u_e(e){const t=Math.floor(e/1e3);if(t<60)return`${t}s`;const a=Math.floor(t/60);if(a<60)return`${a}m`;const r=Math.floor(a/60);return r<48?`${r}h`:`${Math.floor(r/24)}d`}var m_e={face:"#a855f7",plate:"#ec4899"};Object.freeze({...Object.fromEntries(Object.values(V0).filter(e=>e.category==="detection"||e.kind==="motion").map(e=>[e.kind,e.color])),...m_e});var p_e=class{constructor(){this.keyToValue=new Map,this.valueToKey=new Map}set(e,t){this.keyToValue.set(e,t),this.valueToKey.set(t,e)}getByKey(e){return this.keyToValue.get(e)}getByValue(e){return this.valueToKey.get(e)}clear(){this.keyToValue.clear(),this.valueToKey.clear()}},EL=class{constructor(e){this.generateIdentifier=e,this.kv=new p_e}register(e,t){this.kv.getByValue(e)||(t||(t=this.generateIdentifier(e)),this.kv.set(t,e))}clear(){this.kv.clear()}getIdentifier(e){return this.kv.getByValue(e)}getValue(e){return this.kv.getByKey(e)}},h_e=class extends EL{constructor(){super(e=>e.name),this.classToAllowedProps=new Map}register(e,t){typeof t=="object"?(t.allowProps&&this.classToAllowedProps.set(e,t.allowProps),super.register(e,t.identifier)):super.register(e,t)}getAllowedProps(e){return this.classToAllowedProps.get(e)}};function f_e(e){if("values"in Object)return Object.values(e);const t=[];for(const a in e)e.hasOwnProperty(a)&&t.push(e[a]);return t}function g_e(e,t){const a=f_e(e);if("find"in a)return a.find(t);const r=a;for(let c=0;c<r.length;c++){const m=r[c];if(t(m))return m}}function ed(e,t){Object.entries(e).forEach(([a,r])=>t(r,a))}function gf(e,t){return e.indexOf(t)!==-1}function P4(e,t){for(let a=0;a<e.length;a++){const r=e[a];if(t(r))return r}}var v_e=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return g_e(this.transfomers,t=>t.isApplicable(e))}findByName(e){return this.transfomers[e]}},y_e=e=>Object.prototype.toString.call(e).slice(8,-1),RL=e=>typeof e>"u",b_e=e=>e===null,hm=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,WS=e=>hm(e)&&Object.keys(e).length===0,ps=e=>Array.isArray(e),k_e=e=>typeof e=="string",S_e=e=>typeof e=="number"&&!isNaN(e),w_e=e=>typeof e=="boolean",x_e=e=>e instanceof RegExp,fm=e=>e instanceof Map,gm=e=>e instanceof Set,TL=e=>y_e(e)==="Symbol",M_e=e=>e instanceof Date&&!isNaN(e.valueOf()),_L=e=>e instanceof Error,N4=e=>typeof e=="number"&&isNaN(e),C_e=e=>w_e(e)||b_e(e)||RL(e)||S_e(e)||k_e(e)||TL(e),A_e=e=>typeof e=="bigint",I_e=e=>e===1/0||e===-1/0,E_e=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),R_e=e=>e instanceof URL,ZS=e=>e.replace(/\\/g,"\\\\").replace(/\./g,"\\."),T1=e=>e.map(String).map(ZS).join("."),Fu=(e,t)=>{const a=[];let r="";for(let m=0;m<e.length;m++){let d=e.charAt(m);if(!t&&d==="\\"){const h=e.charAt(m+1);if(h==="\\"){r+="\\",m++;continue}else if(h!==".")throw Error("invalid path")}if(d==="\\"&&e.charAt(m+1)==="."){r+=".",m++;continue}if(d==="."){a.push(r),r="";continue}r+=d}const c=r;return a.push(c),a};function gr(e,t,a,r){return{isApplicable:e,annotation:t,transform:a,untransform:r}}var PL=[gr(RL,"undefined",()=>null,()=>{}),gr(A_e,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):(console.error("Please add a BigInt polyfill."),e)),gr(M_e,"Date",e=>e.toISOString(),e=>new Date(e)),gr(_L,"Error",(e,t)=>{const a={name:e.name,message:e.message};return"cause"in e&&(a.cause=e.cause),t.allowedErrorProps.forEach(r=>{a[r]=e[r]}),a},(e,t)=>{const a=new Error(e.message,{cause:e.cause});return a.name=e.name,a.stack=e.stack,t.allowedErrorProps.forEach(r=>{a[r]=e[r]}),a}),gr(x_e,"regexp",e=>""+e,e=>{const t=e.slice(1,e.lastIndexOf("/")),a=e.slice(e.lastIndexOf("/")+1);return new RegExp(t,a)}),gr(gm,"set",e=>[...e.values()],e=>new Set(e)),gr(fm,"map",e=>[...e.entries()],e=>new Map(e)),gr(e=>N4(e)||I_e(e),"number",e=>N4(e)?"NaN":e>0?"Infinity":"-Infinity",Number),gr(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),gr(R_e,"URL",e=>e.toString(),e=>new URL(e))];function Qg(e,t,a,r){return{isApplicable:e,annotation:t,transform:a,untransform:r}}var NL=Qg((e,t)=>TL(e)?!!t.symbolRegistry.getIdentifier(e):!1,(e,t)=>["symbol",t.symbolRegistry.getIdentifier(e)],e=>e.description,(e,t,a)=>{const r=a.symbolRegistry.getValue(t[1]);if(!r)throw new Error("Trying to deserialize unknown symbol");return r}),T_e=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,t)=>(e[t.name]=t,e),{}),OL=Qg(E_e,e=>["typed-array",e.constructor.name],e=>[...e],(e,t)=>{const a=T_e[t[1]];if(!a)throw new Error("Trying to deserialize unknown typed array");return new a(e)});function DL(e,t){return e?.constructor?!!t.classRegistry.getIdentifier(e.constructor):!1}var jL=Qg(DL,(e,t)=>["class",t.classRegistry.getIdentifier(e.constructor)],(e,t)=>{const a=t.classRegistry.getAllowedProps(e.constructor);if(!a)return{...e};const r={};return a.forEach(c=>{r[c]=e[c]}),r},(e,t,a)=>{const r=a.classRegistry.getValue(t[1]);if(!r)throw new Error(`Trying to deserialize unknown class '${t[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);return Object.assign(Object.create(r.prototype),e)}),zL=Qg((e,t)=>!!t.customTransformerRegistry.findApplicable(e),(e,t)=>["custom",t.customTransformerRegistry.findApplicable(e).name],(e,t)=>t.customTransformerRegistry.findApplicable(e).serialize(e),(e,t,a)=>{const r=a.customTransformerRegistry.findByName(t[1]);if(!r)throw new Error("Trying to deserialize unknown custom value");return r.deserialize(e)}),__e=[jL,NL,zL,OL],O4=(e,t)=>{const a=P4(__e,c=>c.isApplicable(e,t));if(a)return{value:a.transform(e,t),type:a.annotation(e,t)};const r=P4(PL,c=>c.isApplicable(e,t));if(r)return{value:r.transform(e,t),type:r.annotation}},qL={};PL.forEach(e=>{qL[e.annotation]=e});var P_e=(e,t,a)=>{if(ps(t))switch(t[0]){case"symbol":return NL.untransform(e,t,a);case"class":return jL.untransform(e,t,a);case"custom":return zL.untransform(e,t,a);case"typed-array":return OL.untransform(e,t,a);default:throw new Error("Unknown transformation: "+t)}else{const r=qL[t];if(!r)throw new Error("Unknown transformation: "+t);return r.untransform(e,a)}},Tc=(e,t)=>{if(t>e.size)throw new Error("index out of bounds");const a=e.keys();for(;t>0;)a.next(),t--;return a.next().value};function LL(e){if(gf(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(gf(e,"prototype"))throw new Error("prototype is not allowed as a property");if(gf(e,"constructor"))throw new Error("constructor is not allowed as a property")}var N_e=(e,t)=>{LL(t);for(let a=0;a<t.length;a++){const r=t[a];if(gm(e))e=Tc(e,+r);else if(fm(e)){const c=+r,m=+t[++a]==0?"key":"value",d=Tc(e,c);switch(m){case"key":e=d;break;case"value":e=e.get(d);break}}else e=e[r]}return e},YS=(e,t,a)=>{if(LL(t),t.length===0)return a(e);let r=e;for(let m=0;m<t.length-1;m++){const d=t[m];if(ps(r)){const h=+d;r=r[h]}else if(hm(r))r=r[d];else if(gm(r)){const h=+d;r=Tc(r,h)}else if(fm(r)){if(m===t.length-2)break;const h=+d,f=+t[++m]==0?"key":"value",k=Tc(r,h);switch(f){case"key":r=k;break;case"value":r=r.get(k);break}}}const c=t[t.length-1];if(ps(r)?r[+c]=a(r[+c]):hm(r)&&(r[c]=a(r[c])),gm(r)){const m=Tc(r,+c),d=a(m);m!==d&&(r.delete(m),r.add(d))}if(fm(r)){const m=+t[t.length-2],d=Tc(r,m);switch(+c==0?"key":"value"){case"key":{const h=a(d);r.set(h,r.get(d)),h!==d&&r.delete(d);break}case"value":r.set(d,a(r.get(d)));break}}return e},BL=e=>e<1;function XS(e,t,a,r=[]){if(!e)return;const c=BL(a);if(!ps(e)){ed(e,(h,f)=>XS(h,t,a,[...r,...Fu(f,c)]));return}const[m,d]=e;d&&ed(d,(h,f)=>{XS(h,t,a,[...r,...Fu(f,c)])}),t(m,r)}function O_e(e,t,a,r){return XS(t,(c,m)=>{e=YS(e,m,d=>P_e(d,c,r))},a),e}function D_e(e,t,a){const r=BL(a);function c(m,d){const h=N_e(e,Fu(d,r));m.map(f=>Fu(f,r)).forEach(f=>{e=YS(e,f,()=>h)})}if(ps(t)){const[m,d]=t;m.forEach(h=>{e=YS(e,Fu(h,r),()=>e)}),d&&ed(d,c)}else ed(t,c);return e}var j_e=(e,t)=>hm(e)||ps(e)||fm(e)||gm(e)||_L(e)||DL(e,t);function z_e(e,t,a){const r=a.get(e);r?r.push(t):a.set(e,[t])}function q_e(e,t){const a={};let r;return e.forEach(c=>{if(c.length<=1)return;t||(c=c.map(h=>h.map(String)).sort((h,f)=>h.length-f.length));const[m,...d]=c;m.length===0?r=d.map(T1):a[T1(m)]=d.map(T1)}),r?WS(a)?[r]:[r,a]:WS(a)?void 0:a}var FL=(e,t,a,r,c=[],m=[],d=new Map)=>{const h=C_e(e);if(!h){z_e(e,c,t);const T=d.get(e);if(T)return r?{transformedValue:null}:T}if(!j_e(e,a)){const T=O4(e,a),N=T?{transformedValue:T.value,annotations:[T.type]}:{transformedValue:e};return h||d.set(e,N),N}if(gf(m,e))return{transformedValue:null};const f=O4(e,a),k=f?.value??e,x=ps(k)?[]:{},E={};ed(k,(T,N)=>{if(N==="__proto__"||N==="constructor"||N==="prototype")throw new Error(`Detected property ${N}. This is a prototype pollution risk, please remove it from your object.`);const j=FL(T,t,a,r,[...c,N],[...m,e],d);x[N]=j.transformedValue,ps(j.annotations)?E[ZS(N)]=j.annotations:hm(j.annotations)&&ed(j.annotations,(q,B)=>{E[ZS(N)+"."+B]=q})});const R=WS(E)?{transformedValue:x,annotations:f?[f.type]:void 0}:{transformedValue:x,annotations:f?[f.type,E]:E};return h||d.set(e,R),R};function $L(e){return Object.prototype.toString.call(e).slice(8,-1)}function D4(e){return $L(e)==="Array"}function L_e(e){if($L(e)!=="Object")return!1;const t=Object.getPrototypeOf(e);return!!t&&t.constructor===Object&&t===Object.prototype}function B_e(e,t,a,r,c){const m={}.propertyIsEnumerable.call(r,t)?"enumerable":"nonenumerable";m==="enumerable"&&(e[t]=a),c&&m==="nonenumerable"&&Object.defineProperty(e,t,{value:a,enumerable:!1,writable:!0,configurable:!0})}function JS(e,t={}){if(D4(e))return e.map(c=>JS(c,t));if(!L_e(e))return e;const a=Object.getOwnPropertyNames(e),r=Object.getOwnPropertySymbols(e);return[...a,...r].reduce((c,m)=>{if(m==="__proto__"||D4(t.props)&&!t.props.includes(m))return c;const d=e[m];return B_e(c,m,JS(d,t),e,t.nonenumerable),c},{})}var ga=class{constructor({dedupe:e=!1}={}){this.classRegistry=new h_e,this.symbolRegistry=new EL(t=>t.description??""),this.customTransformerRegistry=new v_e,this.allowedErrorProps=[],this.dedupe=e}serialize(e){const t=new Map,a=FL(e,t,this,this.dedupe),r={json:a.transformedValue};a.annotations&&(r.meta={...r.meta,values:a.annotations});const c=q_e(t,this.dedupe);return c&&(r.meta={...r.meta,referentialEqualities:c}),r.meta&&(r.meta.v=1),r}deserialize(e,t){const{json:a,meta:r}=e;let c=t?.inPlace?a:JS(a);return r?.values&&(c=O_e(c,r.values,r.v??0,this)),r?.referentialEqualities&&(c=D_e(c,r.referentialEqualities,r.v??0)),c}stringify(e){return JSON.stringify(this.serialize(e))}parse(e){return this.deserialize(JSON.parse(e),{inPlace:!0})}registerClass(e,t){this.classRegistry.register(e,t)}registerSymbol(e,t){this.symbolRegistry.register(e,t)}registerCustom(e,t){this.customTransformerRegistry.register({name:t,...e})}allowErrorProps(...e){this.allowedErrorProps.push(...e)}};ga.defaultInstance=new ga;ga.serialize=ga.defaultInstance.serialize.bind(ga.defaultInstance);ga.deserialize=ga.defaultInstance.deserialize.bind(ga.defaultInstance);ga.stringify=ga.defaultInstance.stringify.bind(ga.defaultInstance);ga.parse=ga.defaultInstance.parse.bind(ga.defaultInstance);ga.registerClass=ga.defaultInstance.registerClass.bind(ga.defaultInstance);ga.registerSymbol=ga.defaultInstance.registerSymbol.bind(ga.defaultInstance);ga.registerCustom=ga.defaultInstance.registerCustom.bind(ga.defaultInstance);ga.allowErrorProps=ga.defaultInstance.allowErrorProps.bind(ga.defaultInstance);P.createContext(null);Ke.AddonStarted+"",Ke.AddonInstalled+"",Ke.AddonRestarted+"",Ke.AddonUpdated+"",Ke.AddonStopped+"",Ke.AddonUninstalled+"",Ke.AddonCrashed+"",Ke.AddonError+"",Ke.DetectionPhaseTransition+"",Ke.DetectionResult+"",Ke.DetectionEvent+"",Ke.DetectionCameraNative+"",Ke.ProviderMotion+"",Ke.MotionOnMotionChanged+"",Ke.MotionAnalysis+"",Ke.MotionZonesRaw+"",Ke.ProviderDetection+"",Ke.PipelineAudioInferenceResult+"",Ke.AgentOnline+"",Ke.AgentOffline+"",Ke.DeviceRegistered+"",Ke.DeviceUnregistered+"",Ke.DeviceStateChanged+"",Ke.EventEmitted+"";var F_e=Object.freeze([...uX()]),$_e=Object.freeze([Ke.PipelineCameraMetricsSnapshot,Ke.PipelineRunnerLoadSnapshot,Ke.PipelineEngineMetricsSnapshot,Ke.PipelineInferenceResult,Ke.PipelineTrace,Ke.PipelineProgress,Ke.StreamBrokerMetricsSnapshot,Ke.MetricsNodeResourcesSnapshot,Ke.MetricsNodeProcessesSnapshot,Ke.ClusterTopologySnapshot,Ke.MotionAnalysis,Ke.MotionZonesRaw,Ke.DetectionResult,Ke.PipelineAudioInferenceResult,Ke.PlatformProbePhase,Ke.BenchmarkProgress,Ke.ModelDownloadProgress,Ke.ProviderMotion]),U_e=new Set($_e);Object.freeze(F_e.filter(e=>!U_e.has(e)));Object.freeze([...new Set(KCe.filter(e=>e.scope==="device").map(e=>e.name))].toSorted());function UL({value:e,unit:t,onDelta:a}){return v.jsxs("div",{className:"flex h-8 w-full overflow-hidden rounded-lg border border-border bg-surface",children:[v.jsx("button",{type:"button","aria-label":"Decrement",className:"w-9 shrink-0 bg-surface-hover text-base text-foreground",onClick:()=>a(-1),children:"−"}),v.jsxs("span",{className:"flex flex-1 items-center justify-center gap-0.5 border-x border-border/60 text-sm",children:[e,t?v.jsx("span",{"data-unit":!0,className:"text-[11px] text-foreground-subtle",children:t}):null]}),v.jsx("button",{type:"button","aria-label":"Increment",className:"w-9 shrink-0 bg-surface-hover text-base text-foreground",onClick:()=>a(1),children:"+"})]})}function H_e({on:e,targetLabel:t,onConfirm:a}){const r=P.useRef(null),c=P.useRef(!1);return v.jsxs("div",{className:ne("relative h-12 w-full rounded-full border flex items-center",e?"bg-emerald-50 border-emerald-200 pl-4":"bg-amber-50 border-amber-200 justify-end pr-4"),children:[v.jsx("span",{className:"text-xs font-semibold opacity-60",children:t}),v.jsx("span",{"data-testid":"slide-thumb",className:"absolute top-1 left-1 h-10 w-14 rounded-[19px] bg-surface shadow flex items-center justify-center",onPointerDown:m=>{m.currentTarget.setPointerCapture?.(m.pointerId),r.current=m.clientX,c.current=!1},onPointerMove:m=>{r.current!==null&&Math.abs(m.clientX-r.current)>40&&(c.current=!0)},onPointerUp:()=>{c.current&&a(),c.current=!1,r.current=null},onPointerCancel:()=>{c.current=!1,r.current=null}})]})}var Q_e=2,j4=270,V_e=315;function K_e(e){const t=(e-135+360)%360;return t>j4?t<=V_e?1:0:t/j4}function vf({fraction:e,color:t,knobTopPx:a,onDragFraction:r}){const c=-135+e*270,m=P.useRef(null),[d,h]=P.useState(!1),f=r!==void 0,k=a??Q_e,x=T=>{r!==void 0&&(T.preventDefault(),T.stopPropagation(),T.currentTarget.setPointerCapture?.(T.pointerId),h(!0))},E=T=>{if(r===void 0||!d)return;const N=m.current;if(N===null)return;const j=N.getBoundingClientRect(),q=j.left+j.width/2,B=j.top+j.height/2;r(K_e(Math.atan2(T.clientY-B,T.clientX-q)*180/Math.PI))},R=T=>{r!==void 0&&(T.currentTarget.releasePointerCapture?.(T.pointerId),h(!1))};return v.jsx("div",{ref:m,className:"absolute inset-0",style:{transform:`rotate(${c}deg)`},children:v.jsx("div",{className:ne("absolute left-1/2 h-5 w-5 -translate-x-1/2 rounded-full bg-white shadow",f&&(d?"cursor-grabbing":"cursor-grab")),style:{top:k,border:`3px solid ${t}`},...f?{onPointerDown:x,onPointerMove:E,onPointerUp:R,onPointerCancel:R}:{}})})}function ew({fraction:e,color:t}){return v.jsxs("div",{className:"relative h-2 w-full rounded-full bg-border",children:[v.jsx("div",{className:"absolute left-0 top-0 h-2 rounded-full",style:{width:`${e*100}%`,background:t??"var(--color-primary)"}}),v.jsx("div",{className:"absolute -top-1 h-4 w-4 rounded-full bg-white shadow",style:{left:`calc(${e*100}% - 8px)`}})]})}var eo=150,yf=64,G_e=eo/2,tw=2*Math.PI*yf,_1=tw*(270/360);function HL({fraction:e,color:t,children:a,onDragFraction:r}){const c=Math.min(1,Math.max(0,e)),m=eo/2,d=eo/2,h=tw-_1,f=c*_1;return v.jsxs("div",{className:"relative",style:{width:eo,height:eo},children:[v.jsxs("svg",{width:eo,height:eo,viewBox:`0 0 ${eo} ${eo}`,"aria-hidden":"true",className:"absolute inset-0",style:{transform:"rotate(135deg)"},children:[v.jsx("circle",{cx:m,cy:d,r:yf,fill:"none",stroke:"var(--color-border)",strokeWidth:11,strokeDasharray:`${_1} ${h}`,strokeLinecap:"round"}),v.jsx("circle",{cx:m,cy:d,r:yf,fill:"none",stroke:t,strokeWidth:11,strokeDasharray:`${f} ${tw-f}`,strokeLinecap:"round"})]}),v.jsx("div",{"data-testid":"arc-knob",children:v.jsx(vf,{fraction:c,color:t,knobTopPx:G_e-yf-10,...r!==void 0?{onDragFraction:r}:{}})}),v.jsx("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-0.5 pointer-events-none",children:a})]})}function Cx({on:e,busy:t,onToggle:a}){const r={transform:e?"translateX(30px)":"translateX(3px)"};return v.jsx("button",{type:"button","aria-pressed":e,title:e?"Turn off":"Turn on",disabled:t,onClick:c=>{c.stopPropagation(),a()},className:ne("relative inline-flex h-8 w-16 items-center rounded-full border transition-colors flex-shrink-0",e?"bg-success/30 border-success/50":"bg-surface-hover border-border",t&&"opacity-60 cursor-not-allowed"),children:v.jsx("span",{className:ne("absolute h-6 w-6 rounded-full transition-all",e?"bg-success":"bg-foreground-subtle"),style:r})})}function W_e({trpc:e,deviceId:t}){const a=Vm(e,t),r=a!==null?a.button:void 0;if(r===void 0)return null;const c=()=>{r.press({deviceId:t})};return v.jsxs("button",{type:"button","aria-label":"Press",title:"Press",onClick:m=>{m.stopPropagation(),c()},className:ne("inline-flex h-5 items-center gap-1 rounded px-1.5 text-xs","bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"),children:[v.jsx(qq,{className:"h-3 w-3"}),v.jsx("span",{children:"Press"})]})}function Z_e({trpc:e,deviceId:t}){const a=Vm(e,t),r=a!==null?a.button:void 0;if(r===void 0)return null;const c=()=>{r.press({deviceId:t})};return v.jsxs("div",{className:"flex flex-col items-center justify-center gap-4 rounded-lg border border-border bg-surface p-6",children:[v.jsx("button",{type:"button","aria-label":"Press button",onClick:c,className:ne("inline-flex h-14 w-14 items-center justify-center rounded-full","bg-primary text-primary-foreground hover:bg-primary/90 transition-colors","shadow-md"),children:v.jsx(qq,{className:"h-6 w-6"})}),v.jsx("span",{className:"text-sm font-medium text-foreground",children:"Press"})]})}var Y_e=4e3;function z4(e){if(e!==void 0)return e!==null&&typeof e=="object"&&"lastChangedAt"in e&&typeof e.lastChangedAt=="number"?e.lastChangedAt:e}function ra(e,t){const a=t?.enabled!==!1,r=t?.timeoutMs??Y_e,[c,m]=P.useState(void 0),d=P.useRef(void 0),h=P.useRef(void 0),f=P.useRef(!1),k=P.useRef(void 0),x=P.useCallback(()=>{k.current!==void 0&&(clearTimeout(k.current),k.current=void 0),d.current=void 0,f.current=!1,h.current=void 0,m(void 0)},[]);P.useEffect(()=>{if(!a||!f.current)return;const R=z4(e),T=h.current;R!==void 0&&R!==T&&x()}),P.useEffect(()=>()=>{k.current!==void 0&&clearTimeout(k.current)},[]);const E=P.useCallback(R=>{if(!a)return;k.current!==void 0&&(clearTimeout(k.current),k.current=void 0);const T=d.current??e;if(T!==void 0){const N={...T,...R};d.current=N,m(N)}h.current=z4(e),f.current=!0,k.current=setTimeout(x,r)},[a,e,x,r]);return a?{display:c!==void 0?c:e,applyOptimistic:E,rollback:x}:{display:e,applyOptimistic:()=>{},rollback:()=>{}}}function X_e(e){return e instanceof Error?e.message:String(e)}function J_e({trpc:e,deviceId:t,layout:a,optimistic:r,features:c}){const{cap:m,slice:d,available:h}=Nt({trpc:e,deviceId:t,cap:Y=>Y.lockControl,slice:Y=>Y.state.lockControl}),{display:f,applyOptimistic:k}=ra(d,{enabled:r??!0}),[x,E]=P.useState(null),[R,T]=P.useState(!1),[N,j]=P.useState(null);if(f===void 0)return null;const q=f.state==="locked"||f.state==="locking",B=!h||f.state==="jammed",F=c?.includes(Ht.LockOpen)===!0,U=a==="compact",H=()=>{k({state:"locking"}),m?.lock({})},Q=()=>{k({state:"unlocking"}),m?.unlock({})},te=()=>{m?.open({})},K=()=>{if(!B){if(!q){H();return}if(U){j(null),E("unlock");return}Q()}},W=()=>{if(!B){if(U){j(null),E("open");return}te()}},oe=()=>{R||E(null)},he=async()=>{if(!(R||x===null)){j(null),T(!0);try{x==="unlock"?(k({state:"unlocking"}),await m?.unlock({})):await m?.open({}),E(null)}catch(Y){j(X_e(Y))}finally{T(!1)}}},Ae=q?"Unlock":"Lock",we=x==="open"?"Open door?":"Unlock device?",Ee=x==="open"?"This will release the latch and open the door.":"This will unlock the device.",Ie=x==="open"?"Confirm open":"Confirm unlock",Me=x==="open"?v.jsx(Zc,{className:"h-4 w-4 text-amber-400"}):v.jsx(NS,{className:"h-4 w-4 text-amber-400"});return v.jsxs("div",{className:ne("inline-flex items-center",a==="full"?"gap-2":"gap-1"),children:[v.jsxs("button",{type:"button","aria-label":Ae,title:f.state==="jammed"?"Jammed":Ae,disabled:B,onClick:Y=>{Y.stopPropagation(),K()},className:ne("inline-flex items-center justify-center rounded transition-colors",a==="full"?"h-7 gap-1.5 px-2 text-xs":"h-5 w-5",q?"text-success":"text-warning",B&&"opacity-40 cursor-not-allowed","hover:bg-surface-hover"),children:[q?v.jsx(Bm,{className:"h-3.5 w-3.5"}):v.jsx(NS,{className:"h-3.5 w-3.5"}),a==="full"&&v.jsx("span",{children:f.state})]}),F&&v.jsxs("button",{type:"button","aria-label":"Open door",title:"Open door",disabled:B,onClick:Y=>{Y.stopPropagation(),W()},className:ne("inline-flex items-center justify-center rounded transition-colors",a==="full"?"h-7 gap-1.5 px-2 text-xs":"h-5 w-5","text-foreground-muted",B&&"opacity-40 cursor-not-allowed","hover:bg-surface-hover"),children:[v.jsx(Zc,{className:"h-3.5 w-3.5"}),a==="full"&&v.jsx("span",{children:"Open"})]}),U&&v.jsx(cL,{open:x!==null,onOpenChange:Y=>{Y||oe()},children:v.jsxs(Mx,{width:"sm",onClick:Y=>Y.stopPropagation(),children:[v.jsxs(W4e,{children:[v.jsxs(Y4e,{className:"flex items-center gap-2",children:[Me,we]}),v.jsx(X4e,{children:Ee})]}),N!==null&&v.jsx("div",{className:"mt-2 px-3 py-2 rounded border border-danger/40 bg-danger/10 text-xs text-danger",children:N}),v.jsxs(Z4e,{children:[v.jsx(pm,{type:"button",variant:"ghost",size:"sm",disabled:R,onClick:()=>oe(),children:"Cancel"}),v.jsxs(pm,{type:"button",variant:"danger",size:"sm","aria-label":Ie,disabled:R,onClick:()=>{he()},children:[R&&v.jsx($g,{className:"h-3.5 w-3.5 animate-spin"}),Ie]})]})]})})]})}function Ax({trpc:e,deviceId:t,optimistic:a}){const{cap:r,slice:c,available:m}=Nt({trpc:e,deviceId:t,cap:N=>N.switch,slice:N=>N.state.switch}),{display:d,applyOptimistic:h}=ra(c,{enabled:a??!0}),[f,k]=P.useState(!1);if(d===void 0)return null;const x=d.on===!0,E=f||!m,R={transform:x?"translateX(14px)":"translateX(2px)"},T=async()=>{if(E||!r)return;const N=!x;h({on:N}),k(!0);try{await r.setState({on:N})}finally{k(!1)}};return v.jsx("button",{type:"button","aria-pressed":x,title:x?"Turn off":"Turn on",disabled:E,onClick:N=>{N.stopPropagation(),T()},className:ne("relative inline-flex h-4 w-7 items-center rounded-full border transition-colors flex-shrink-0",x?"bg-success/30 border-success/50":"bg-surface-hover border-border",E&&"opacity-60"),children:v.jsx("span",{className:ne("absolute h-3 w-3 rounded-full transition-all",x?"bg-success":"bg-foreground-subtle"),style:R})})}function ePe({trpc:e,deviceId:t,layout:a,optimistic:r}){const{cap:c,slice:m,available:d}=Nt({trpc:e,deviceId:t,cap:x=>x.brightness,slice:x=>x.state.brightness}),{display:h,applyOptimistic:f}=ra(m,{enabled:r??!0});if(h===void 0)return null;const k=!d;return v.jsxs("label",{className:ne("flex items-center gap-2 text-xs text-foreground-subtle",a==="compact"&&"min-w-[140px]"),children:[v.jsx("input",{"aria-label":"Brightness",type:"range",min:0,max:100,step:1,value:h.percentage,disabled:k,onChange:x=>{const E=Number(x.target.value);f({percentage:E}),k||c?.setBrightness({percentage:E})}}),v.jsxs("span",{className:"tabular-nums w-8 text-right",children:[h.percentage,"%"]})]})}function tPe({trpc:e,deviceId:t,features:a,layout:r,optimistic:c}){const{cap:m,slice:d,available:h}=Nt({trpc:e,deviceId:t,cap:j=>j.fanControl,slice:j=>j.state.fanControl}),{display:f,applyOptimistic:k}=ra(d,{enabled:c??!0});if(f===void 0)return null;const x=!h,E=a??[],R=E.includes("fan-speed"),T=E.includes("fan-preset"),N=d?.percentageStep!=null&&d.percentageStep>0?d.percentageStep:1;return v.jsxs("div",{className:ne("inline-flex items-center gap-2",r==="full"&&"flex-col items-stretch"),children:[R&&v.jsxs("div",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[v.jsx("input",{"aria-label":"Fan speed",type:"range",min:0,max:100,step:N,value:f.percentage??0,disabled:x,onChange:j=>{const q=Number(j.target.value),B=Math.min(100,Math.max(0,Math.round(q/N)*N));k({percentage:B}),x||m?.setPercentage({percentage:B})}}),v.jsxs("span",{className:"tabular-nums w-8 text-right",children:[f.percentage??"—","%"]})]}),T&&f.availablePresets.length>0&&v.jsx("div",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:v.jsxs("select",{"aria-label":"Fan preset",value:f.preset,disabled:x,onChange:j=>{const q=j.target.value;!x&&q&&(k({preset:q}),m?.setPreset({preset:q}))},className:"bg-surface border border-border rounded px-1 py-0.5",children:[v.jsx("option",{value:"",disabled:!0,children:"—"}),f.availablePresets.map(j=>v.jsx("option",{value:j,children:j},j))]})})]})}var Ix={heat:"border-amber-400 bg-amber-50 dark:bg-amber-950",cool:"border-blue-400 bg-blue-50 dark:bg-blue-950",auto:"border-purple-400 bg-purple-50 dark:bg-purple-950",heat_cool:"border-fuchsia-400 bg-fuchsia-50 dark:bg-fuchsia-950",fan_only:"border-slate-400 bg-slate-50 dark:bg-slate-950",dry:"border-cyan-400 bg-cyan-50 dark:bg-cyan-950",off:"border-zinc-300 bg-zinc-50 dark:bg-zinc-900"},QL={heat:"text-amber-600 dark:text-amber-400",cool:"text-blue-600 dark:text-blue-400",auto:"text-purple-600 dark:text-purple-400",heat_cool:"text-fuchsia-600 dark:text-fuchsia-400",fan_only:"text-slate-600 dark:text-slate-400",dry:"text-cyan-600 dark:text-cyan-400",off:"text-foreground"},aPe={heat:"bg-amber-400 text-amber-950",cool:"bg-blue-400 text-blue-950",auto:"bg-purple-400 text-purple-950",heat_cool:"bg-fuchsia-400 text-fuchsia-950",fan_only:"bg-slate-400 text-slate-950",dry:"bg-cyan-400 text-cyan-950",off:"bg-zinc-300 text-zinc-700"};function nPe({trpc:e,deviceId:t,features:a,layout:r,optimistic:c}){const{cap:m,slice:d,available:h}=Nt({trpc:e,deviceId:t,cap:T=>T.climateControl,slice:T=>T.state.climateControl}),{display:f,applyOptimistic:k}=ra(d,{enabled:c??!0});if(m===void 0||f===void 0)return null;const x=!h;if(r==="compact")return v.jsxs("div",{"data-mode":f.mode,className:"inline-flex items-center gap-1",children:[v.jsx("span",{className:ne("text-xs tabular-nums font-medium",QL[f.mode]),children:f.target!==null?v.jsxs(v.Fragment,{children:[f.target,"°",f.currentTemp!==null&&v.jsxs("span",{className:"text-foreground-subtle font-normal",children:[" ","(",f.currentTemp,"°)"]})]}):f.currentTemp!==null?v.jsxs("span",{className:"text-foreground-subtle",children:[f.currentTemp,"°"]}):null}),f.target!==null&&v.jsxs(v.Fragment,{children:[v.jsx("button",{type:"button","aria-label":"Decrease target",disabled:x,onClick:T=>{if(T.stopPropagation(),!x&&f.target!==null){const N=f.target-1;k({target:N}),m.setTarget({target:N})}},className:ne("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs",x&&"opacity-40 cursor-not-allowed"),children:"−"}),v.jsx("button",{type:"button","aria-label":"Increase target",disabled:x,onClick:T=>{if(T.stopPropagation(),!x&&f.target!==null){const N=f.target+1;k({target:N}),m.setTarget({target:N})}},className:ne("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs",x&&"opacity-40 cursor-not-allowed"),children:"+"})]}),v.jsx("select",{"aria-label":"Mode",value:f.mode,disabled:x,onChange:T=>{T.stopPropagation();const N=T.target.value;x||(k({mode:N}),m.setMode({mode:N}))},className:ne("bg-transparent px-0.5 text-xs text-foreground-subtle hover:text-foreground cursor-pointer",x&&"opacity-40 cursor-not-allowed"),children:f.availableModes.map(T=>v.jsx("option",{value:T,children:T},T))})]});const E=f.mode==="heat_cool"||f.targetLow!==null&&f.targetHigh!==null,R=!E&&f.target!==null;return v.jsxs("div",{"data-mode":f.mode,className:ne("inline-flex items-center gap-2 rounded border px-2 py-1 transition-colors",Ix[f.mode],"flex-col items-stretch gap-3"),children:[v.jsxs("div",{className:"inline-flex items-center gap-1 text-xs tabular-nums",children:[f.currentTemp!==null&&v.jsxs("span",{className:"text-foreground-subtle",children:[f.currentTemp,"°"]}),R&&v.jsxs(v.Fragment,{children:[v.jsx("span",{className:"text-foreground-subtle",children:"→"}),v.jsxs("span",{className:"font-medium",children:[f.target,"°"]}),v.jsx("button",{type:"button","aria-label":"Decrease target",disabled:x,onClick:T=>{if(T.stopPropagation(),!x&&f.target!==null){const N=f.target-1;k({target:N}),m.setTarget({target:N})}},className:ne("inline-flex h-4 w-4 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",x&&"opacity-40 cursor-not-allowed"),children:"−"}),v.jsx("button",{type:"button","aria-label":"Increase target",disabled:x,onClick:T=>{if(T.stopPropagation(),!x&&f.target!==null){const N=f.target+1;k({target:N}),m.setTarget({target:N})}},className:ne("inline-flex h-4 w-4 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",x&&"opacity-40 cursor-not-allowed"),children:"+"})]})]}),v.jsx("div",{className:"inline-flex items-center gap-0.5 rounded bg-surface-subtle p-0.5",children:f.availableModes.map(T=>v.jsx("button",{type:"button","aria-label":T,disabled:x,onClick:N=>{N.stopPropagation(),x||(k({mode:T}),m.setMode({mode:T}))},className:ne("rounded px-1.5 py-0.5 text-xs transition-colors",T===f.mode?aPe[T]:"text-foreground-subtle hover:text-foreground hover:bg-surface-hover",x&&"opacity-40 cursor-not-allowed"),children:T},T))}),E&&v.jsxs("div",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[v.jsxs("label",{className:"flex items-center gap-1",children:[v.jsx("span",{children:"Low"}),v.jsx("input",{"aria-label":"Target low",type:"number",step:.5,value:f.targetLow??"",disabled:x,onChange:T=>{if(!x){const N=Number(T.target.value),j=f.targetHigh??N;k({targetLow:N}),m.setTargetRange({targetLow:N,targetHigh:j})}},className:"w-14 rounded border border-border bg-surface px-1 py-0.5 tabular-nums"})]}),v.jsxs("label",{className:"flex items-center gap-1",children:[v.jsx("span",{children:"High"}),v.jsx("input",{"aria-label":"Target high",type:"number",step:.5,value:f.targetHigh??"",disabled:x,onChange:T=>{if(!x){const N=Number(T.target.value),j=f.targetLow??N;k({targetHigh:N}),m.setTargetRange({targetLow:j,targetHigh:N})}},className:"w-14 rounded border border-border bg-surface px-1 py-0.5 tabular-nums"})]})]}),f.availableFanModes.length>0&&v.jsxs("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[v.jsx("span",{children:"Fan"}),v.jsxs("select",{"aria-label":"Fan mode",value:f.fanMode,disabled:x,onChange:T=>{const N=T.target.value;!x&&N&&(k({fanMode:N}),m.setFanMode({fanMode:N}))},className:"rounded border border-border bg-surface px-1 py-0.5",children:[v.jsx("option",{value:"",disabled:!0,children:"—"}),f.availableFanModes.map(T=>v.jsx("option",{value:T,children:T},T))]})]}),f.availablePresets.length>0&&v.jsxs("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[v.jsx("span",{children:"Preset"}),v.jsxs("select",{"aria-label":"Preset",value:f.preset,disabled:x,onChange:T=>{const N=T.target.value;!x&&N&&(k({preset:N}),m.setPreset({preset:N}))},className:"rounded border border-border bg-surface px-1 py-0.5",children:[v.jsx("option",{value:"",disabled:!0,children:"—"}),f.availablePresets.map(T=>v.jsx("option",{value:T,children:T},T))]})]}),f.targetHumidity!==null&&v.jsxs("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[v.jsx("span",{children:"Humidity"}),v.jsx("input",{"aria-label":"Target humidity",type:"range",min:0,max:100,step:1,value:f.targetHumidity,disabled:x,onChange:T=>{const N=Number(T.target.value);k({targetHumidity:N}),x||m.setTargetHumidity({targetHumidity:N})}}),v.jsxs("span",{className:"tabular-nums w-8 text-right",children:[f.targetHumidity,"%"]})]})]})}var iPe={playing:"border-green-400 bg-green-50 dark:bg-green-950",paused:"border-amber-400 bg-amber-50 dark:bg-amber-950",buffering:"border-blue-400 bg-blue-50 dark:bg-blue-950",on:"border-slate-400 bg-slate-50 dark:bg-slate-950",idle:"border-slate-400 bg-slate-50 dark:bg-slate-950",off:"border-zinc-300 bg-zinc-50 dark:bg-zinc-900",standby:"border-zinc-300 bg-zinc-50 dark:bg-zinc-900"},rPe={playing:"bg-green-500",paused:"bg-amber-400",buffering:"bg-blue-400",on:"bg-slate-400",idle:"bg-slate-400",off:"bg-zinc-300",standby:"bg-zinc-300"},VL=["off","all","one"];function oPe(e){return VL.includes(e)}var sPe={off:"Off",all:"All",one:"One"};function lPe(e){return e==="playing"||e==="buffering"?"pause":"play"}function cPe({trpc:e,deviceId:t,features:a,layout:r,optimistic:c}){const{cap:m,slice:d,available:h}=Nt({trpc:e,deviceId:t,cap:R=>R.mediaPlayer,slice:R=>R.state.mediaPlayer}),{display:f,applyOptimistic:k}=ra(d,{enabled:c??!0});if(f===void 0)return null;const x=!h,E=lPe(f.state);return v.jsxs("div",{"data-state":f.state,className:ne("inline-flex items-center gap-2 rounded border px-2 py-1 transition-colors",iPe[f.state],r==="full"&&"flex-col items-stretch gap-3"),children:[v.jsxs("div",{className:"inline-flex items-center gap-2",children:[v.jsx("span",{role:"status","aria-label":f.state,className:ne("inline-block h-2 w-2 rounded-full flex-shrink-0",rPe[f.state])}),v.jsx("button",{type:"button","aria-label":E==="play"?"Play":"Pause",disabled:x,onClick:R=>{R.stopPropagation(),!x&&(E==="play"?(k({state:"playing"}),m?.play({})):(k({state:"paused"}),m?.pause({})))},className:ne("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs",x&&"opacity-40 cursor-not-allowed"),children:E==="play"?"▶":"⏸"})]}),r==="full"&&v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"inline-flex items-center gap-1",children:[v.jsx("button",{type:"button","aria-label":"Previous",disabled:x,onClick:R=>{R.stopPropagation(),x||m?.previous({})},className:ne("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs",x&&"opacity-40 cursor-not-allowed"),children:"⏮"}),v.jsx("button",{type:"button","aria-label":"Next",disabled:x,onClick:R=>{R.stopPropagation(),x||m?.next({})},className:ne("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs",x&&"opacity-40 cursor-not-allowed"),children:"⏭"})]}),f.volumeLevel!==null&&v.jsxs("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[v.jsx("span",{children:"Vol"}),v.jsx("input",{"aria-label":"Volume",type:"range",min:0,max:100,step:1,value:f.volumeLevel,disabled:x,onChange:R=>{const T=Number(R.target.value);k({volumeLevel:T}),x||m?.setVolume({volumeLevel:T})}}),v.jsxs("span",{className:"tabular-nums w-8 text-right",children:[f.volumeLevel,"%"]})]}),f.isMuted!==null&&v.jsx("button",{type:"button","aria-label":f.isMuted?"Unmute":"Mute",disabled:x,onClick:R=>{if(R.stopPropagation(),!x&&f.isMuted!==null){const T=!f.isMuted;k({isMuted:T}),m?.setMute({muted:T})}},className:ne("inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs transition-colors",f.isMuted?"bg-amber-400 text-amber-950":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover",x&&"opacity-40 cursor-not-allowed"),children:f.isMuted?"🔇":"🔊"}),f.availableSources.length>0&&v.jsxs("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[v.jsx("span",{children:"Source"}),v.jsxs("select",{"aria-label":"Source",value:f.source,disabled:x,onChange:R=>{const T=R.target.value;!x&&T&&(k({source:T}),m?.selectSource({source:T}))},className:"rounded border border-border bg-surface px-1 py-0.5",children:[v.jsx("option",{value:"",disabled:!0,children:"—"}),f.availableSources.map(R=>v.jsx("option",{value:R,children:R},R))]})]}),f.shuffle!==null&&v.jsx("button",{type:"button","aria-label":"Shuffle",disabled:x,onClick:R=>{if(R.stopPropagation(),!x&&f.shuffle!==null){const T=!f.shuffle;k({shuffle:T}),m?.setShuffle({shuffle:T})}},className:ne("inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs transition-colors",f.shuffle?"bg-green-400 text-green-950":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover",x&&"opacity-40 cursor-not-allowed"),children:"⇌ Shuffle"}),f.repeat!==null&&v.jsxs("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[v.jsx("span",{children:"Repeat"}),v.jsx("select",{"aria-label":"Repeat",value:f.repeat,disabled:x,onChange:R=>{const T=R.target.value;!x&&oPe(T)&&(k({repeat:T}),m?.setRepeat({repeat:T}))},className:"rounded border border-border bg-surface px-1 py-0.5",children:VL.map(R=>v.jsx("option",{value:R,children:sPe[R]},R))})]})]})]})}function $u(e,t){return t!==void 0?e.toFixed(t):Number.isInteger(e)?String(e):e.toFixed(1)}var dPe=/^(\d{4})-(\d{2})-(\d{2})/,uPe=/^(\d{2}):(\d{2})(?::(\d{2}))?$/;function mPe(e,t){const a=dPe.exec(e);if(a===null)return e;const r=Number(a[1]),c=Number(a[2]),m=Number(a[3]),d=new Date(r,c-1,m);if(Number.isNaN(d.getTime()))return e;try{return d.toLocaleDateString(t)}catch{return e}}function pPe(e,t){const a=uPe.exec(e);if(a===null)return e;const r=new Date(1970,0,1,Number(a[1]),Number(a[2]),a[3]!==void 0?Number(a[3]):0);if(Number.isNaN(r.getTime()))return e;try{return r.toLocaleTimeString(t,{hour:"2-digit",minute:"2-digit"})}catch{return e}}function hPe(e,t){const a=e.includes("T")?e:e.replace(" ","T"),r=new Date(a);if(Number.isNaN(r.getTime()))return e;try{return r.toLocaleString(t,{dateStyle:"medium",timeStyle:"short"})}catch{return e}}function Ex(e,t,a){return e===""?e:t==="date"?mPe(e,a):t==="time"?pPe(e,a):hPe(e,a)}function fPe(e){return e.slice(0,10)}function gPe(e){return e.slice(0,5)}function vPe(e){return(e.includes("T")?e:e.replace(" ","T")).slice(0,16)}function yPe({value:e,busy:t,onCommit:a,unit:r,min:c,max:m,step:d,precision:h}){const[f,k]=P.useState($u(e,h)),x=Number(f),E=f!==""&&!Number.isNaN(x),R=d??1,T=j=>{let q=j;return c!==void 0&&(q=Math.max(c,q)),m!==void 0&&(q=Math.min(m,q)),q},N=()=>{!t&&E&&a(T(x))};return v.jsxs("div",{className:"inline-flex items-center gap-1",children:[v.jsx("button",{type:"button","aria-label":"Decrement",disabled:t,onClick:j=>{if(j.stopPropagation(),!t){const q=T(e-R);k($u(q,h)),a(q)}},className:ne("inline-flex h-5 w-5 items-center justify-center rounded border border-border bg-surface text-xs transition-colors hover:bg-surface-hover",t&&"opacity-40 cursor-not-allowed"),children:"−"}),v.jsx("input",{"aria-label":"Numeric value",type:"number",disabled:t,value:f,onChange:j=>{k(j.target.value);const q=Number(j.target.value);j.target.value!==""&&!Number.isNaN(q)&&(t||a(T(q)))},onBlur:N,onKeyDown:j=>{j.key==="Enter"&&N()},className:ne("w-16 rounded border border-border bg-surface px-1 py-0.5 text-xs tabular-nums text-center",t&&"opacity-40 cursor-not-allowed")}),r!==void 0&&v.jsx("span",{className:"text-foreground-subtle text-xs",children:r}),v.jsx("button",{type:"button","aria-label":"Increment",disabled:t,onClick:j=>{if(j.stopPropagation(),!t){const q=T(e+R);k($u(q,h)),a(q)}},className:ne("inline-flex h-5 w-5 items-center justify-center rounded border border-border bg-surface text-xs transition-colors hover:bg-surface-hover",t&&"opacity-40 cursor-not-allowed"),children:"+"})]})}function bPe({value:e,busy:t,onCommit:a}){const[r,c]=P.useState(e);return v.jsx("input",{type:"text",disabled:t,value:r,onChange:m=>c(m.target.value),onBlur:()=>{t||a(r)},onKeyDown:m=>{m.key==="Enter"&&!t&&a(r)},className:ne("rounded border border-border bg-surface px-2 py-0.5 text-xs",t&&"opacity-40 cursor-not-allowed")})}function kPe({slice:e,busy:t,setValueFn:a,layout:r}){switch(e.kind){case"numeric":return v.jsx(yPe,{value:typeof e.value=="number"?e.value:Number(e.value),busy:t,onCommit:c=>{a({control:{kind:"numeric",value:c}})},unit:e.unit,min:e.min,max:e.max,step:e.step,precision:e.precision});case"select":return v.jsx("select",{"aria-label":"Control value",disabled:t,value:String(e.value),onChange:c=>{c.stopPropagation(),t||a({control:{kind:"select",value:c.target.value}})},className:ne("w-full max-w-full min-w-0 truncate rounded bg-transparent px-0.5 py-0.5 text-xs",t&&"opacity-40 cursor-not-allowed"),children:e.options.map(c=>v.jsx("option",{value:c,children:c},c))});case"text":return v.jsx(bPe,{value:String(e.value),busy:t,onCommit:c=>{a({control:{kind:"text",value:c}})}});case"datetime":{const c=String(e.value),m=e.format??"datetime";return r==="compact"?c===""?v.jsx("span",{"aria-label":"Control value",className:"text-xs text-foreground-subtle",children:"—"}):v.jsx("span",{"aria-label":"Control value",className:"text-xs text-foreground",children:Ex(c,m)}):v.jsx("input",{type:m==="date"?"date":m==="time"?"time":"datetime-local","aria-label":"Control value",disabled:t,value:m==="date"?fPe(c):m==="time"?gPe(c):vPe(c),onChange:d=>{d.stopPropagation(),t||a({control:{kind:"datetime",value:d.target.value}})},className:ne("rounded border border-border bg-surface px-1 py-0.5 text-xs",t&&"opacity-40 cursor-not-allowed")})}default:return null}}function KL({trpc:e,deviceId:t,features:a,layout:r,optimistic:c}){const{cap:m,slice:d,available:h}=Nt({trpc:e,deviceId:t,cap:R=>R.control,slice:R=>R.state.control}),{display:f,applyOptimistic:k}=ra(d,{enabled:c??!0});if(f===void 0)return null;const x=!h,E=R=>{!x&&m&&(k({value:R.control.value}),m.setValue(R))};return v.jsx("div",{"data-kind":f.kind,className:"inline-flex min-w-0 max-w-full items-center gap-1 rounded border border-border px-2 py-1 transition-colors",children:v.jsx(kPe,{slice:f,busy:x,setValueFn:E,layout:r})})}function q4(e){if(e!==void 0)return yne(e)??e}var SPe=e=>e;function GL(e){const t=e.capName!==void 0?e.display?.perCap?.[e.capName]:void 0,a=t?.precision??e.display?.precision??e.roleDefault?.precision??e.slicePrecision,r=q4(e.sliceUnit??e.canonicalUnit),c=q4(t?.unit??e.display?.unit??e.roleDefault?.unit);return c!==void 0&&r!==void 0&&c!==r&&Sne(r,c)?{unit:c,precision:a,toDisplayValue:m=>eD(m,r,c)??m}:{unit:r??"",precision:a,toDisplayValue:SPe}}var WL={kind:"binary",field:"on",onLabel:"Low",offLabel:"Normal"};function ZL(e){return e==="battery-sensor"}function YL(e,t){if(!XL(e))return!1;const a=e[t];if(typeof a!="number")return!1;const r=e.lastFetchedAt;return!(a===0&&r===0)}var aw={"temperature-sensor":{kind:"numeric",field:"celsius",canonicalUnit:"°C",getSliceHandle:e=>e.temperatureSensor},"humidity-sensor":{kind:"numeric",field:"percent",canonicalUnit:"%",getSliceHandle:e=>e.humiditySensor},"ambient-light-sensor":{kind:"numeric",field:"lux",canonicalUnit:"lx",getSliceHandle:e=>e.ambientLightSensor},"pressure-sensor":{kind:"numeric",field:"hpa",canonicalUnit:"hPa",getSliceHandle:e=>e.pressureSensor},"numeric-sensor":{kind:"numeric",field:"value",getSliceHandle:e=>e.numericSensor},"wind-sensor":{kind:"numeric",field:"value",getSliceHandle:e=>e.numericSensor},"rain-sensor":{kind:"numeric",field:"value",getSliceHandle:e=>e.numericSensor},"uv-sensor":{kind:"numeric",field:"value",getSliceHandle:e=>e.numericSensor},"solar-radiation-sensor":{kind:"numeric",field:"value",getSliceHandle:e=>e.numericSensor},"soil-moisture-sensor":{kind:"numeric",field:"value",getSliceHandle:e=>e.numericSensor},"power-sensor":{kind:"numeric",field:"watts",canonicalUnit:"W",getSliceHandle:e=>e.powerMeter},"energy-sensor":{kind:"numeric",field:"kwhTotal",canonicalUnit:"kWh",getSliceHandle:e=>e.powerMeter},"voltage-sensor":{kind:"numeric",field:"volts",canonicalUnit:"V",getSliceHandle:e=>e.powerMeter},"current-sensor":{kind:"numeric",field:"amps",canonicalUnit:"A",getSliceHandle:e=>e.powerMeter},"battery-sensor":{kind:"numeric",field:"value",canonicalUnit:"%",getSliceHandle:e=>e.numericSensor},"generic-sensor":{kind:"numeric",field:"value",getSliceHandle:e=>e.numericSensor},"motion-sensor":{kind:"binary",field:"detected",onLabel:"Detected",offLabel:"Clear",getSliceHandle:e=>e.motion},"pir-sensor":{kind:"binary",field:"detected",onLabel:"Detected",offLabel:"Clear",getSliceHandle:e=>e.motion},"contact-sensor":{kind:"binary",field:"entryOpen",onLabel:"Open",offLabel:"Closed",getSliceHandle:e=>e.contact},"smoke-sensor":{kind:"binary",field:"detected",onLabel:"Smoke!",offLabel:"Clear",getSliceHandle:e=>e.smoke},"leak-sensor":{kind:"binary",field:"flooded",onLabel:"Leak!",offLabel:"Dry",getSliceHandle:e=>e.flood},"co-sensor":{kind:"binary",field:"detected",onLabel:"CO!",offLabel:"Clear",getSliceHandle:e=>e.carbonMonoxide},"binary-sensor":{kind:"binary",field:"on",onLabel:"On",offLabel:"Off",getSliceHandle:e=>e.binary},presence:{kind:"presence",getSliceHandle:e=>e.presence},"enum-sensor":{kind:"string",getSliceHandle:e=>e.enumSensor},"datetime-sensor":{kind:"datetime",format:"datetime",getSliceHandle:e=>e.enumSensor}};function XL(e){return typeof e=="object"&&e!==null}function wPe(e){return typeof e=="object"&&e!==null}function xPe(e){return typeof e=="object"&&e!==null&&"state"in e&&typeof e.state=="string"}function Uu(e){return typeof e=="object"&&e!==null&&"value"in e&&typeof e.value=="string"}function JL(e){if(typeof e!="object"||e===null)return;const t=e.format;if(t==="date"||t==="time"||t==="datetime")return t}function MPe(e){return e==="home"?"Home":e==="not_home"?"Away":e.charAt(0).toUpperCase()+e.slice(1)}function CPe({trpc:e,device:t}){const a=t.role!=null?aw[t.role]:void 0,r=ZL(t.role),{data:c}=g6({},{staleTime:6e4}),m=Vm(e,t.id),d=cs(m!==null&&a!==void 0?a.getSliceHandle(m.state):void 0),h=cs(m!==null&&a?.kind==="numeric"?m.state.enumSensor:void 0),f=cs(m!==null&&r?m.state.binary:void 0),k=r&&a?.kind==="numeric"&&!YL(d,a.field)&&f!==void 0,x=k?WL:a,E=k?f:d;if(x===void 0||E===void 0)return null;if(x.kind==="numeric"){if(!XL(E))return null;const T=E[x.field];if(typeof T!="number")return null;const N=E.lastFetchedAt,j=T===0&&N===0;if(j&&Uu(h)&&h.value!=="")return v.jsx("span",{className:ne("inline-flex items-baseline text-xs text-foreground"),children:h.value});if(j)return null;const q=E,B=typeof q.unit=="string"?q.unit:void 0,F=typeof q.precision=="number"?q.precision:void 0,U=GL({display:t.display,capName:t.role==="numeric-sensor"?"numeric-sensor":void 0,roleDefault:t.role!=null?c?.defaults[t.role]:void 0,sliceUnit:B,slicePrecision:F,canonicalUnit:x.canonicalUnit}),H=U.unit,Q=$u(U.toDisplayValue(T),U.precision);return v.jsxs("span",{className:ne("inline-flex items-baseline gap-0.5 tabular-nums text-xs text-foreground"),children:[v.jsx("span",{children:Q}),H&&v.jsx("span",{className:"text-foreground-subtle",children:H})]})}if(x.kind==="binary"){if(!wPe(E))return null;const N=!!E[x.field],j=N?x.onLabel:x.offLabel;return v.jsx("span",{className:ne("inline-flex items-center rounded px-1.5 py-0.5 text-xs font-medium",N?"bg-warning/15 text-warning":"bg-surface-subtle text-foreground-subtle"),children:j})}if(x.kind==="string")return!Uu(E)||E.value===""?null:v.jsx("span",{className:ne("inline-flex items-baseline text-xs text-foreground"),children:E.value});if(x.kind==="datetime"){if(!Uu(E)||E.value==="")return null;const T=JL(E)??x.format,N=Ex(E.value,T);return v.jsx("span",{className:ne("inline-flex items-baseline text-xs text-foreground"),children:N})}if(!xPe(E))return null;const R=MPe(E.state);return v.jsx("span",{className:ne("inline-flex items-center rounded px-1.5 py-0.5 text-xs font-medium",E.state==="home"?"bg-success/15 text-success":"bg-surface-subtle text-foreground-subtle"),children:R})}function Vg(e){switch(e){case"opening":return{up:"accent",stop:"neutral",down:"neutral"};case"closing":return{up:"neutral",stop:"neutral",down:"accent"};case"open":return{up:"filled",stop:"neutral",down:"neutral"};case"closed":return{up:"neutral",stop:"neutral",down:"filled"};default:return{up:"neutral",stop:"neutral",down:"neutral"}}}function APe(e){switch(e){case"accent":return"bg-primary text-primary-foreground";case"filled":return"bg-primary/15 text-primary";case"neutral":return""}}function P1({label:e,busy:t,variant:a,onClick:r,children:c}){return v.jsx("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:m=>{m.stopPropagation(),r()},className:ne("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",APe(a),t&&"opacity-40 cursor-not-allowed"),children:c})}function IPe({trpc:e,deviceId:t,optimistic:a}){const{cap:r,slice:c,available:m}=Nt({trpc:e,deviceId:t,cap:E=>E.cover,slice:E=>E.state.cover}),{display:d,applyOptimistic:h}=ra(c,{enabled:a??!0});if(r===void 0)return null;const f=Vg(d?.state),k=!m,x=(E,R)=>{k||!E||(R!==void 0&&h(R),E({}))};return v.jsxs("div",{className:"inline-flex items-center gap-1",children:[v.jsx(P1,{label:"Open",busy:k,variant:f.up,onClick:()=>x(r?.open,{state:"opening"}),children:v.jsx(Lg,{className:"h-3.5 w-3.5"})}),v.jsx(P1,{label:"Stop",busy:k,variant:f.stop,onClick:()=>x(r?.stop,{state:"stopped"}),children:v.jsx(Hm,{className:"h-3 w-3"})}),v.jsx(P1,{label:"Close",busy:k,variant:f.down,onClick:()=>x(r?.close,{state:"closing"}),children:v.jsx(gl,{className:"h-3.5 w-3.5"})}),d!==void 0&&d.position!==null&&v.jsxs("span",{className:"tabular-nums text-xs text-foreground-subtle ml-1",children:[d.position,"%"]})]})}function N1({label:e,busy:t,variant:a,onClick:r,children:c}){return v.jsx("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:m=>{m.stopPropagation(),r()},className:ne("inline-flex h-10 w-10 items-center justify-center rounded-md text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",a==="accent"&&"bg-primary text-primary-foreground hover:bg-primary/90",a==="filled"&&"bg-primary/15 text-primary",t&&"opacity-40 cursor-not-allowed"),children:c})}function e8(){return v.jsxs(v.Fragment,{children:[v.jsx("div",{"aria-hidden":"true",className:"absolute inset-y-0 left-1/2 w-px -translate-x-px bg-white/60"}),v.jsx("div",{"aria-hidden":"true",className:"absolute inset-x-0 top-1/2 h-px -translate-y-px bg-white/60"})]})}function EPe({position:e,interactive:t,onSetPosition:a}){const r=(1-e/100)*100,c=P.useRef(null),m=P.useRef(!1),d=P.useRef(null),h=R=>{const T=c.current;if(T===null)return e;const N=T.getBoundingClientRect();if(N.height<=0)return e;const j=(R-N.top)/N.height,q=Math.round(100-j*100);return Math.min(100,Math.max(0,q))},f=R=>{if(a===void 0)return;const T=h(R);d.current!==T&&(d.current=T,a(T))},k=R=>{t&&(R.stopPropagation(),R.preventDefault(),m.current=!0,d.current=null,R.currentTarget.setPointerCapture(R.pointerId),f(R.clientY))},x=R=>{!t||!m.current||(R.stopPropagation(),f(R.clientY))},E=R=>{!t||!m.current||(R.stopPropagation(),m.current=!1,d.current=null,R.currentTarget.hasPointerCapture(R.pointerId)&&R.currentTarget.releasePointerCapture(R.pointerId))};return v.jsxs("div",{ref:c,"data-testid":"cover-window",...t?{"aria-label":"Drag to set position",role:"slider","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":e}:{"aria-hidden":"true"},onPointerDown:t?k:void 0,onPointerMove:t?x:void 0,onPointerUp:t?E:void 0,onPointerCancel:t?E:void 0,className:ne("relative w-28 h-36 rounded border-2 border-amber-700/60 bg-gradient-to-b from-sky-200 to-sky-50 overflow-hidden flex-shrink-0",t&&"cursor-ns-resize touch-none select-none"),style:{boxShadow:"inset 0 0 0 2px rgba(255,255,255,.5)"},children:[v.jsx(e8,{}),v.jsx("div",{className:"absolute inset-x-0 top-0 transition-all duration-200",style:{height:`${r}%`,background:"repeating-linear-gradient(#c9cdd2, #c9cdd2 6px, #b7bcc2 6px, #b7bcc2 8px)",borderBottom:r>0?"1px solid #9aa":"none"}}),v.jsxs("div",{"data-testid":"cover-lever",className:ne("absolute inset-x-0 h-4 flex items-center justify-center gap-1 z-10 transition-all duration-200",t&&"cursor-grab active:cursor-grabbing"),style:{top:`calc(${r}% - 8px)`},children:[v.jsx("div",{className:"absolute -inset-x-1.5 h-full rounded-lg bg-slate-600 shadow-md"}),v.jsx("span",{className:"h-1 w-1 rounded-full bg-white/70 relative z-10","aria-hidden":"true"}),v.jsx("span",{className:"h-1 w-1 rounded-full bg-white/70 relative z-10","aria-hidden":"true"}),v.jsx("span",{className:"h-1 w-1 rounded-full bg-white/70 relative z-10","aria-hidden":"true"}),v.jsxs("span",{"data-testid":"cover-position-pct",className:"absolute left-full ml-2 text-xs font-semibold text-foreground tabular-nums whitespace-nowrap",children:[e,"%"]})]})]})}function RPe({isOpen:e}){return v.jsxs("div",{"data-testid":"cover-window","aria-hidden":"true",className:"relative w-28 h-36 rounded border-2 border-amber-700/60 bg-gradient-to-b from-sky-200 to-sky-50 overflow-hidden flex-shrink-0",style:{boxShadow:"inset 0 0 0 2px rgba(255,255,255,.5)"},children:[v.jsx(e8,{}),!e&&v.jsx("div",{className:"absolute inset-0",style:{background:"repeating-linear-gradient(#c9cdd2, #c9cdd2 6px, #b7bcc2 6px, #b7bcc2 8px)"}})]})}function TPe({trpc:e,deviceId:t,features:a,optimistic:r}){const{cap:c,slice:m,available:d}=Nt({trpc:e,deviceId:t,cap:F=>F.cover,slice:F=>F.state.cover}),{display:h,applyOptimistic:f}=ra(m,{enabled:r??!0});if(c===void 0)return null;const k=!d,x=(a??[]).includes(Ht.CoverPositionable),E=(a??[]).includes(Ht.CoverTilt),R=Vg(h?.state),T=h?.position??null,N=T!==null,j=h?.state==="open"||h?.state==="opening",q=(F,U)=>{k||!F||(U!==void 0&&f(U),F({}))},B=F=>{k||(f({position:F}),c?.setPosition({position:F}))};return v.jsxs("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:[v.jsxs("div",{className:"flex items-center gap-6",children:[N?v.jsx(EPe,{position:T,interactive:x,onSetPosition:x?B:void 0}):v.jsx(RPe,{isOpen:j}),v.jsxs("div",{className:"flex flex-col gap-3 flex-1",children:[N&&v.jsxs("div",{className:"flex items-baseline gap-1",children:[v.jsx("span",{className:"text-3xl font-semibold tabular-nums text-foreground",children:T}),v.jsx("span",{className:"text-base text-foreground-subtle",children:"%"}),v.jsx("span",{className:"text-xs text-foreground-subtle ml-1",children:"open"})]}),!N&&v.jsx("div",{className:"flex items-baseline gap-1",children:v.jsx("span",{className:"text-3xl font-semibold capitalize text-foreground",children:h?.state??"—"})}),v.jsxs("div",{className:"flex items-center gap-2",children:[v.jsx(N1,{label:"Open",busy:k,variant:R.up,onClick:()=>q(c?.open,{state:"opening"}),children:v.jsx(Lg,{className:"h-5 w-5"})}),v.jsx(N1,{label:"Stop",busy:k,variant:R.stop,onClick:()=>q(c?.stop,{state:"stopped"}),children:v.jsx(Hm,{className:"h-4 w-4"})}),v.jsx(N1,{label:"Close",busy:k,variant:R.down,onClick:()=>q(c?.close,{state:"closing"}),children:v.jsx(gl,{className:"h-5 w-5"})})]})]})]}),x&&v.jsxs("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[v.jsx("span",{className:"w-12 shrink-0",children:"Position"}),v.jsx("input",{"aria-label":"Position",type:"range",min:0,max:100,step:1,value:T??0,disabled:k,className:"flex-1",onChange:F=>{B(Number(F.target.value))}}),v.jsxs("span",{className:"w-8 text-right tabular-nums",children:[T??"—","%"]})]}),!x&&T!==null&&v.jsxs("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[v.jsx("span",{className:"w-12 shrink-0",children:"Position"}),v.jsx("input",{"aria-label":"Position",type:"range",min:0,max:100,step:1,value:T,disabled:!0,readOnly:!0,className:"flex-1 opacity-60"}),v.jsxs("span",{className:"w-8 text-right tabular-nums",children:[T,"%"]})]}),E&&v.jsxs("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[v.jsx("span",{className:"w-12 shrink-0",children:"Tilt"}),v.jsx("input",{"aria-label":"Tilt position",type:"range",min:0,max:100,step:1,value:h?.tiltPosition??0,disabled:k,className:"flex-1",onChange:F=>{const U=Number(F.target.value);f({tiltPosition:U}),k||c?.setTiltPosition({tiltPosition:U})}}),v.jsxs("span",{className:"w-8 text-right tabular-nums",children:[h?.tiltPosition??"—","%"]})]})]})}function _Pe(e){return v.jsx("span",{className:"text-foreground-subtle text-xs select-none","aria-hidden":"true",children:"—"})}function PPe(e){return v.jsx("div",{className:"rounded border border-border bg-surface-subtle px-3 py-2 text-xs text-foreground-subtle",children:"Controls coming soon"})}function NPe(e){return{id:e.id,stableId:e.stableId,addonId:e.addonId,type:e.type,name:e.name,online:e.online,disabled:e.disabled,parentDeviceId:e.parentDeviceId,role:e.role??void 0,features:e.features}}function OPe({trpc:e,deviceId:t}){const{data:a}=v6({deviceId:t},{staleTime:6e4});return a===void 0?null:v.jsx(CPe,{trpc:e,device:NPe(a)})}function DPe(e){return typeof e=="object"&&e!==null}function L4(e){return typeof e=="object"&&e!==null}function jPe(e){return typeof e=="object"&&e!==null&&"state"in e&&typeof e.state=="string"}function zPe(e){return e==="home"?"Home":e==="not_home"?"Away":e.charAt(0).toUpperCase()+e.slice(1)}var qPe={low:"bg-danger",medium:"bg-warning",high:"bg-success"};function LPe(e){return e<=20?"low":e<=50?"medium":"high"}function BPe({percent:e}){const t=Math.min(100,Math.max(0,e)),a=LPe(t);return v.jsx("div",{"data-testid":"battery-bar","data-band":a,className:"h-2 w-24 overflow-hidden rounded-full bg-border",children:v.jsx("div",{className:ne("h-full rounded-full transition-all",qPe[a]),style:{width:`${t}%`}})})}function FPe({trpc:e,device:t}){const a=t.role!=null?aw[t.role]:aw["temperature-sensor"],r=ZL(t.role),{data:c}=g6({},{staleTime:6e4}),m=Vm(e,t.id),d=cs(m!==null&&a!==void 0?a.getSliceHandle(m.state):void 0),h=cs(m!==null&&r?m.state.binary:void 0),f=cs(m!==null&&!r?m.state.binary:void 0),k=r&&a?.kind==="numeric"&&!YL(d,a.field)&&h!==void 0,x=k?WL:a,E=k?h:d;if(x===void 0||E===void 0)return v.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4 min-h-[96px]",children:[v.jsx("span",{className:"text-sm text-foreground-subtle",children:t.name}),v.jsx("span",{className:"text-xs text-foreground-subtle italic",children:"Awaiting state…"})]});if(x.kind==="numeric"){if(!DPe(E))return null;const T=E[x.field];if(typeof T!="number")return null;const N=E,j=typeof N.unit=="string"?N.unit:void 0,q=typeof N.precision=="number"?N.precision:void 0,B=GL({display:t.display,capName:t.role==="numeric-sensor"?"numeric-sensor":void 0,roleDefault:t.role!=null?c?.defaults[t.role]:c?.defaults["temperature-sensor"],sliceUnit:j,slicePrecision:q,canonicalUnit:x.canonicalUnit}),F=B.unit,U=$u(B.toDisplayValue(T),B.precision),H=f!==void 0&&L4(f)&&typeof f.on=="boolean"?!!f.on:null;return v.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4",children:[v.jsxs("div",{className:"flex items-baseline gap-1",children:[v.jsx("span",{className:"text-3xl font-semibold tabular-nums text-foreground",children:U}),F&&v.jsx("span",{className:"text-base text-foreground-subtle",children:F})]}),r&&v.jsx(BPe,{percent:T}),H!==null&&v.jsx("span",{className:ne("inline-flex items-center rounded px-2 py-0.5 text-xs font-medium",H?"bg-warning/15 text-warning":"bg-surface-subtle text-foreground-subtle"),"data-testid":"sensor-hero-occupancy",children:H?"Occupied":"Clear"}),v.jsx("span",{className:"text-sm text-foreground-subtle",children:t.name})]})}if(x.kind==="binary"){if(!L4(E))return null;const N=!!E[x.field],j=N?x.onLabel:x.offLabel;return v.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4",children:[v.jsx("span",{className:ne("inline-flex items-center rounded px-3 py-1.5 text-lg font-semibold",N?"bg-warning/15 text-warning":"bg-surface-subtle text-foreground-subtle"),children:j}),v.jsx("span",{className:"text-sm text-foreground-subtle",children:t.name})]})}if(x.kind==="datetime"){if(!Uu(E))return null;if(E.value==="")return v.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4 min-h-[96px]",children:[v.jsx("span",{className:"text-sm text-foreground-subtle",children:t.name}),v.jsx("span",{className:"text-xs text-foreground-subtle italic",children:"Awaiting state…"})]});const T=JL(E)??x.format;return v.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4",children:[v.jsx("span",{className:"text-3xl font-semibold tabular-nums text-foreground",children:Ex(E.value,T)}),v.jsx("span",{className:"text-sm text-foreground-subtle",children:t.name})]})}if(x.kind==="string")return!Uu(E)||E.value===""?null:v.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4",children:[v.jsx("span",{className:"text-xl font-semibold text-foreground",children:E.value}),v.jsx("span",{className:"text-sm text-foreground-subtle",children:t.name})]});if(!jPe(E))return null;const R=zPe(E.state);return v.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4",children:[v.jsx("span",{className:ne("inline-flex items-center rounded px-3 py-1.5 text-lg font-semibold",E.state==="home"?"bg-success/15 text-success":"bg-surface-subtle text-foreground-subtle"),children:R}),v.jsx("span",{className:"text-sm text-foreground-subtle",children:t.name})]})}function $Pe({trpc:e,deviceId:t}){const{data:a}=v6({deviceId:t},{staleTime:6e4});return a===void 0?null:v.jsx(FPe,{trpc:e,device:a})}function t8(e){return e===void 0||e.inProgress?!1:e.availableVersion!==null&&e.currentVersion!==null&&e.availableVersion!==e.currentVersion}function a8(e,t){return Nt({trpc:e,deviceId:t,cap:a=>a.update,slice:a=>a.state.update})}function UPe({trpc:e,deviceId:t}){const{cap:a,slice:r}=a8(e,t);return a===void 0?null:r?.inProgress?v.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-foreground-subtle",children:[v.jsx($g,{className:"h-3.5 w-3.5 animate-spin"}),"Updating…"]}):t8(r)?v.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-warning/15 px-1.5 py-0.5 text-[10px] font-medium text-warning",children:[v.jsx(Pq,{className:"h-3 w-3"}),"Update"]}):v.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] text-foreground-subtle",children:[v.jsx(Iq,{className:"h-3 w-3 text-success"}),r?.currentVersion??"Up to date"]})}function HPe({trpc:e,deviceId:t}){const{cap:a,slice:r,available:c}=a8(e,t);if(a===void 0)return null;const m=r?.inProgress===!0,d=t8(r),h=r?.currentVersion??"—",f=()=>{!c||a===void 0||!d||a.installUpdate({})};return v.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4",children:[v.jsxs("div",{className:"flex items-baseline gap-1.5",children:[v.jsx("span",{className:"text-3xl font-semibold tabular-nums text-foreground",children:h}),d&&r?.availableVersion!=null&&v.jsxs(v.Fragment,{children:[v.jsx("span",{className:"text-base text-foreground-subtle",children:"→"}),v.jsx("span",{className:"text-base font-medium text-warning tabular-nums",children:r.availableVersion})]})]}),m?v.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded px-3 py-1.5 text-sm font-medium text-foreground-subtle",children:[v.jsx($g,{className:"h-4 w-4 animate-spin"}),"Installing…"]}):d?v.jsxs("button",{type:"button",onClick:k=>{k.stopPropagation(),f()},disabled:!c,className:"inline-flex items-center gap-1.5 rounded-lg bg-primary px-4 py-1.5 text-sm font-medium text-primary-foreground shadow-sm transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[v.jsx(Pq,{className:"h-4 w-4"}),"Install update"]}):v.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded bg-success/15 px-3 py-1 text-sm font-medium text-success",children:[v.jsx(Iq,{className:"h-4 w-4"}),"Up to date"]}),r?.state!=null&&r.state!==""&&v.jsx("span",{className:"text-[10px] text-foreground-subtle",children:r.state})]})}function QPe(e){switch(e){case"cleaning":return{label:"Cleaning",tone:"text-primary"};case"paused":return{label:"Paused",tone:"text-warning"};case"returning":return{label:"Returning",tone:"text-primary"};case"docked":return{label:"Docked",tone:"text-success"};case"drying":return{label:"Drying",tone:"text-warning"};case"idle":return{label:"Idle",tone:"text-foreground-subtle"};case"error":return{label:"Error",tone:"text-destructive"};case void 0:return{label:"Unknown",tone:"text-foreground-subtle"}}}function n8(e,t){return Nt({trpc:e,deviceId:t,cap:a=>a.vacuumControl,slice:a=>a.state.vacuumControl})}function O1({label:e,busy:t,active:a,onClick:r,children:c}){return v.jsx("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:m=>{m.stopPropagation(),r()},className:ne("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",a&&"bg-primary text-primary-foreground",t&&"opacity-40 cursor-not-allowed"),children:c})}function VPe(e){switch(e){case"cleaning":return{glow:"bg-primary/15",accent:"text-primary",docked:!1,active:!0};case"returning":return{glow:"bg-primary/10",accent:"text-primary",docked:!1,active:!0};case"docked":return{glow:"bg-success/10",accent:"text-success",docked:!0,active:!1};case"drying":return{glow:"bg-warning/10",accent:"text-warning",docked:!0,active:!1};case"paused":return{glow:"bg-warning/10",accent:"text-warning",docked:!1,active:!1};case"error":return{glow:"bg-destructive/10",accent:"text-destructive",docked:!1,active:!1};case"idle":return{glow:"bg-transparent",accent:"text-foreground-subtle",docked:!1,active:!1};case void 0:return{glow:"bg-transparent",accent:"text-foreground-subtle",docked:!1,active:!1}}}var KPe=`
85
85
  @keyframes rg-breathe { 0%,100%{opacity:.78;transform:scale(1)} 50%{opacity:1;transform:scale(1.05)} }
86
86
  @keyframes rg-zzz { 0%{opacity:0;transform:translateY(3px)} 30%{opacity:.85} 100%{opacity:0;transform:translateY(-9px)} }
@@ -114,4 +114,4 @@ ${a.slice(0,5).join(`
114
114
  @media (prefers-reduced-motion: reduce) {
115
115
  .acv-streak, .acv-fan, .acv-sway-wrap, .acv-glow, .acv-swing { animation: none !important; }
116
116
  }
117
- `;function b8({trpc:e,deviceId:t,layout:a,optimistic:r}){const{cap:c,slice:m,available:d}=Nt({trpc:e,deviceId:t,cap:F=>F.climateControl,slice:F=>F.state.climateControl}),{display:h,applyOptimistic:f}=ra(m,{enabled:r??!0});if(c===void 0||h===void 0)return null;const k=!d;if(a==="compact")return v.jsxs("div",{"data-mode":h.mode,className:"inline-flex items-center gap-1",children:[v.jsx("span",{className:ne("text-xs tabular-nums font-medium",QL[h.mode]),children:h.target!==null?v.jsxs(v.Fragment,{children:[h.target,"°",h.currentTemp!==null&&v.jsxs("span",{className:"text-foreground-subtle font-normal",children:[" ","(",h.currentTemp,"°)"]})]}):h.currentTemp!==null?v.jsxs("span",{className:"text-foreground-subtle",children:[h.currentTemp,"°"]}):null}),h.target!==null&&v.jsxs(v.Fragment,{children:[v.jsx("button",{type:"button","aria-label":"Decrease target",disabled:k,onClick:F=>{if(F.stopPropagation(),!k&&h.target!==null){const U=h.target-1;f({target:U}),c.setTarget({target:U})}},className:ne("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs",k&&"opacity-40 cursor-not-allowed"),children:"−"}),v.jsx("button",{type:"button","aria-label":"Increase target",disabled:k,onClick:F=>{if(F.stopPropagation(),!k&&h.target!==null){const U=h.target+1;f({target:U}),c.setTarget({target:U})}},className:ne("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs",k&&"opacity-40 cursor-not-allowed"),children:"+"})]}),v.jsx("select",{"aria-label":"Mode",value:h.mode,disabled:k,onChange:F=>{F.stopPropagation();const U=h.availableModes.find(H=>H===F.target.value);!k&&U&&(f({mode:U}),c.setMode({mode:U}))},className:ne("bg-transparent px-0.5 text-xs text-foreground-subtle hover:text-foreground cursor-pointer",k&&"opacity-40 cursor-not-allowed"),children:h.availableModes.map(F=>v.jsx("option",{value:F,children:U1[F]},F))})]});const x=LNe[h.mode],E=h.mode!=="off",R=$Ne(h.preset),T=h.preset==="turbo",N=Math.max(.55,UNe(h.fanMode)*(T?.6:1)),j=h.swingVertical!==null,q=h.swingHorizontal!==null,B=E&&(h.swingVertical===!0||h.swingHorizontal===!0);return v.jsxs("div",{"data-mode":h.mode,className:ne("relative flex flex-col items-stretch gap-2.5 overflow-hidden rounded-lg border p-3 transition-colors",Ix[h.mode]),children:[v.jsx("style",{children:HNe}),v.jsxs("div",{className:"relative z-10 flex flex-col items-center justify-center gap-1 overflow-hidden rounded-lg border border-border/50 bg-surface/30 px-3 py-3",children:[v.jsx("div",{className:"pointer-events-none absolute inset-0 opacity-60",children:v.jsx(KNe,{mode:h.mode,accent:x,periodSec:N,swaying:B})}),v.jsx("div",{className:"pointer-events-none absolute inset-0 bg-gradient-to-b from-surface/50 via-transparent to-surface/50"}),E&&v.jsx("span",{"aria-hidden":!0,className:"acv-glow pointer-events-none absolute left-1/2 top-1/2 h-16 w-16 -translate-x-1/2 -translate-y-1/2 rounded-full blur-2xl",style:{background:x,animation:"acv-glow 3.2s ease-in-out infinite"}}),v.jsxs("div",{className:"relative z-10 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide",style:{color:x},children:[v.jsx(K4,{mode:h.mode,className:"h-3.5 w-3.5"}),U1[h.mode],h.currentTemp!==null&&v.jsxs("span",{className:"normal-case text-foreground-subtle",children:["· ",h.currentTemp,"° now"]}),h.currentHumidity!==null&&v.jsxs("span",{className:"inline-flex items-center gap-0.5 normal-case text-foreground-subtle",children:[v.jsx(md,{className:"h-3 w-3"}),h.currentHumidity,"%"]})]}),h.target!==null?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"relative z-10 flex items-center gap-3",children:[v.jsx(G4,{label:"Decrease target",symbol:"−",disabled:k,onClick:()=>{if(k||h.target===null)return;const F=h.target-1;f({target:F}),c.setTarget({target:F})}}),v.jsxs("div",{className:"flex items-baseline gap-0.5",children:[v.jsx("span",{className:"text-4xl font-bold leading-none tabular-nums",style:{color:x},children:h.target}),v.jsx("span",{className:"text-lg text-foreground-subtle",children:"°"})]}),v.jsx(G4,{label:"Increase target",symbol:"+",disabled:k,onClick:()=>{if(k||h.target===null)return;const F=h.target+1;f({target:F}),c.setTarget({target:F})}})]}),v.jsx("div",{className:"relative z-10 w-36",children:v.jsx(VNe,{value:h.target,min:BNe,max:FNe,accent:x})})]}):v.jsxs("div",{className:"relative z-10 flex items-baseline gap-0.5",children:[v.jsx("span",{className:"text-4xl font-bold leading-none tabular-nums text-foreground",children:h.currentTemp??"—"}),v.jsx("span",{className:"text-lg text-foreground-subtle",children:"°"})]})]}),v.jsxs("div",{className:"relative z-10 grid grid-cols-3 gap-2",children:[v.jsx(H1,{label:"Mode",icon:v.jsx("span",{style:{color:x},className:"flex",children:v.jsx(K4,{mode:h.mode,className:"h-4 w-4"})}),value:h.mode,options:h.availableModes.map(F=>({value:F,label:U1[F]})),disabled:k,onChange:F=>{const U=h.availableModes.find(H=>H===F);U&&(f({mode:U}),c.setMode({mode:U}))}}),h.availableFanModes.length>0&&v.jsx(H1,{label:"Fan",icon:v.jsx(co,{className:"h-4 w-4 text-sky-500"}),value:h.fanMode,options:h.availableFanModes.map(F=>({value:F,label:V4(F)})),disabled:k,onChange:F=>{f({fanMode:F}),c.setFanMode({fanMode:F})}}),h.availablePresets.length>0&&v.jsx(H1,{label:"Preset",icon:v.jsx(R,{className:"h-4 w-4 text-emerald-500"}),value:h.preset,options:h.availablePresets.map(F=>({value:F,label:V4(F)})),disabled:k,onChange:F=>{f({preset:F}),c.setPreset({preset:F})}})]}),(j||q)&&v.jsx(QNe,{label:"Swing",children:v.jsxs("div",{className:"grid grid-cols-2 gap-1",children:[j&&v.jsx(W4,{axis:"vertical",on:h.swingVertical??!1,busy:k,onToggle:F=>{f({swingVertical:F}),c.setSwingVertical({on:F})}}),q&&v.jsx(W4,{axis:"horizontal",on:h.swingHorizontal??!1,busy:k,onToggle:F=>{f({swingHorizontal:F}),c.setSwingHorizontal({on:F})}})]})})]})}function QNe({label:e,children:t}){return v.jsxs("div",{className:"relative z-10 flex flex-col gap-1",children:[v.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle",children:e}),t]})}function K4({mode:e,className:t}){const a=qNe[e];return v.jsx(a,{className:t,"aria-hidden":!0})}function H1({label:e,icon:t,value:a,options:r,disabled:c,onChange:m}){return v.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[v.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle",children:e}),v.jsxs("div",{className:ne("flex items-center gap-1 overflow-hidden rounded-lg border border-border/60 bg-surface-subtle px-1.5 py-1.5",c&&"opacity-40"),children:[v.jsx("span",{className:"flex shrink-0",children:t}),v.jsx("select",{"aria-label":e,value:a,disabled:c,onChange:d=>{d.stopPropagation(),c||m(d.target.value)},className:"min-w-0 flex-1 cursor-pointer appearance-none truncate bg-transparent text-xs font-medium text-foreground outline-none",children:r.map(d=>v.jsx("option",{value:d.value,children:d.label},d.value))}),v.jsx(gl,{className:"h-3 w-3 shrink-0 text-foreground-subtle"})]})]})}function G4({label:e,symbol:t,disabled:a,onClick:r}){return v.jsx("button",{type:"button","aria-label":e,disabled:a,onClick:r,className:ne("flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border bg-surface text-lg leading-none text-foreground-subtle transition-colors hover:bg-surface-hover hover:text-foreground active:scale-95",a&&"opacity-40 cursor-not-allowed"),children:t})}function VNe({value:e,min:t,max:a,accent:r}){const c=`${Math.min(1,Math.max(0,(e-t)/(a-t)))*100}%`;return v.jsxs("div",{className:"mt-2 w-full",children:[v.jsxs("div",{className:"relative h-1.5 w-full rounded-full bg-surface-subtle",children:[v.jsx("div",{className:"absolute inset-y-0 left-0 rounded-full",style:{width:c,background:r}}),v.jsx("div",{className:"absolute top-1/2 h-3 w-3 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-surface shadow",style:{left:c,background:r}})]}),v.jsxs("div",{className:"mt-0.5 flex justify-between text-[9px] tabular-nums text-foreground-subtle",children:[v.jsxs("span",{children:[t,"°"]}),v.jsxs("span",{children:[a,"°"]})]})]})}function KNe({mode:e,accent:t,periodSec:a,swaying:r}){const c=[0,1,2,3,4,5],m=e==="heat",d=e==="dry";return v.jsx("div",{"aria-hidden":!0,className:"absolute inset-0 overflow-hidden",children:e==="off"?v.jsx("div",{className:"flex h-full items-center justify-center gap-2 opacity-30",children:c.map(h=>v.jsx("span",{className:"h-8 w-1 rounded-full bg-foreground-subtle opacity-40"},h))}):e==="fan_only"?v.jsx("div",{className:"flex h-full items-center justify-center",children:v.jsx(GNe,{color:t,periodSec:Math.max(.5,a*.7),size:56})}):v.jsx("div",{className:ne("acv-sway-wrap absolute inset-0",r&&"acv-sway"),style:r?{animation:"acv-sway 2.6s ease-in-out infinite"}:void 0,children:c.map(h=>v.jsx("span",{className:"acv-streak absolute rounded-full",style:{left:`${8+h*15}%`,width:d?"0.4rem":"0.3rem",height:d?"0.4rem":"1.9rem",background:t,boxShadow:`0 0 6px ${t}`,animationName:m?"acv-rise":"acv-fall",animationTimingFunction:"linear",animationIterationCount:"infinite",animationDuration:`${a}s`,animationDelay:`${h%3*(a/3)+h*.05}s`}},h))})})}function GNe({color:e,periodSec:t,size:a}){return v.jsxs("svg",{width:a,height:a,viewBox:"0 0 100 100",className:"acv-fan",style:{animation:`acv-spin ${t}s linear infinite`,transformOrigin:"50% 50%"},"aria-hidden":!0,children:[[0,120,240].map(r=>v.jsx("path",{d:"M50 50 C 58 30, 78 26, 84 12 C 66 20, 54 34, 50 50 Z",fill:e,opacity:.85,transform:`rotate(${r} 50 50)`},r)),v.jsx("circle",{cx:"50",cy:"50",r:"7",fill:e})]})}function W4({axis:e,on:t,busy:a,onToggle:r}){const c=e==="vertical"?"Vertical":"Horizontal",m=e==="vertical"?pIe:mIe,d=e==="vertical"?"acv-swing-v":"acv-swing-h";return v.jsxs("button",{type:"button","aria-label":`${c} swing`,"aria-pressed":t,disabled:a,onClick:()=>{a||r(!t)},className:ne("flex items-center justify-center gap-2 rounded-lg border px-2 py-1.5 text-xs font-medium transition-colors",t?"border-transparent bg-indigo-400 text-indigo-950 shadow-sm":"border-border/60 bg-surface-subtle text-foreground-subtle hover:bg-surface-hover hover:text-foreground",a&&"opacity-40 cursor-not-allowed"),children:[v.jsx(m,{className:"acv-swing h-4 w-4","aria-hidden":!0,style:t?{animation:`${d} 1.4s ease-in-out infinite`}:void 0}),c]})}var WNe=5,ZNe=35;function Q1(e,t,a){return Math.min(1,Math.max(0,(e-t)/(a-t)))}function V1(e,t,a){return Math.round(t+e*(a-t))}var ao=176,tg=76,bf=2*Math.PI*tg,bu=bf*(270/360),K1=ao/2-tg-10;function Z4(e){const t=ao/2,a=ao/2,r=bf-bu,c=e.mode==="band"?(()=>{const m=e.band.from*bu,d=Math.max(0,(e.band.to-e.band.from)*bu);return{dasharray:`${d} ${bf-d}`,dashoffset:-m}})():(()=>{const m=e.fraction*bu;return{dasharray:`${m} ${bf-m}`,dashoffset:void 0}})();return v.jsxs("svg",{width:ao,height:ao,viewBox:`0 0 ${ao} ${ao}`,"aria-hidden":"true",className:"absolute inset-0",style:{transform:"rotate(135deg)"},children:[v.jsx("circle",{cx:t,cy:a,r:tg,fill:"none",stroke:"var(--color-border)",strokeWidth:12,strokeDasharray:`${bu} ${r}`,strokeLinecap:"round"}),v.jsx("circle",{cx:t,cy:a,r:tg,fill:"none",stroke:e.color,strokeWidth:12,strokeDasharray:c.dasharray,...c.dashoffset!==void 0?{strokeDashoffset:c.dashoffset}:{},strokeLinecap:"round"})]})}var YNe={heat:"#f59e0b",cool:"#60a5fa",auto:"#c084fc",heat_cool:"#e879f9",fan_only:"#94a3b8",dry:"#22d3ee",off:"#d4d4d8"};function XNe({trpc:e,deviceId:t,features:a,optimistic:r}){const{cap:c,slice:m,available:d}=Nt({trpc:e,deviceId:t,cap:B=>B.climateControl,slice:B=>B.state.climateControl}),{display:h,applyOptimistic:f}=ra(m,{enabled:r??!0});if(c===void 0||h===void 0)return null;const k=!d,x=YNe[h.mode],E=h.mode==="heat_cool"||h.targetLow!==null&&h.targetHigh!==null,R=WNe,T=ZNe,N=!E&&h.target!==null?Q1(h.target,R,T):0,j=E&&h.targetLow!==null?Q1(h.targetLow,R,T):0,q=E&&h.targetHigh!==null?Q1(h.targetHigh,R,T):0;return v.jsxs("div",{"data-mode":h.mode,className:ne("flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4 transition-colors",Ix[h.mode]),children:[v.jsxs("div",{className:"flex flex-col items-center gap-3",children:[v.jsxs("div",{className:"relative",style:{width:ao,height:ao},children:[E?v.jsx(Z4,{mode:"band",band:{from:j,to:q},color:x}):v.jsx(Z4,{mode:"fill",fraction:N,color:x}),E?v.jsxs(v.Fragment,{children:[v.jsx("div",{"data-testid":"arc-knob",children:v.jsx(vf,{fraction:j,color:x,knobTopPx:K1,onDragFraction:B=>{if(k||h.targetHigh===null)return;const F=Math.min(V1(B,R,T),h.targetHigh);f({targetLow:F}),c.setTargetRange({targetLow:F,targetHigh:h.targetHigh})}})}),v.jsx("div",{"data-testid":"arc-knob",children:v.jsx(vf,{fraction:q,color:x,knobTopPx:K1,onDragFraction:B=>{if(k||h.targetLow===null)return;const F=Math.max(V1(B,R,T),h.targetLow);f({targetHigh:F}),c.setTargetRange({targetLow:h.targetLow,targetHigh:F})}})})]}):v.jsx("div",{"data-testid":"arc-knob",children:v.jsx(vf,{fraction:N,color:x,knobTopPx:K1,onDragFraction:B=>{if(k)return;const F=V1(B,R,T);f({target:F}),c.setTarget({target:F})}})}),v.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-0.5 pointer-events-none",children:[v.jsxs("div",{"data-testid":"current-temp",className:"text-4xl font-bold tabular-nums text-foreground leading-none",children:[h.currentTemp!==null?h.currentTemp:"—",v.jsx("span",{className:"text-lg text-foreground-subtle font-normal ml-0.5",children:"°"})]}),!E&&h.target!==null&&v.jsxs("div",{className:"text-xs font-semibold",style:{color:x},children:["set ",h.target,"°"]}),E&&h.targetLow!==null&&h.targetHigh!==null&&v.jsxs("div",{className:"text-xs font-semibold",style:{color:x},children:[h.targetLow,"° – ",h.targetHigh,"°"]})]})]}),!E&&h.target!==null&&v.jsx("div",{className:"w-[200px]",children:v.jsx(UL,{value:`${h.target}°`,onDelta:B=>{if(k||h.target===null)return;const F=h.target+B;f({target:F}),c.setTarget({target:F})}})})]}),v.jsx("select",{"aria-label":"Mode",value:h.mode,disabled:k,onChange:B=>{B.stopPropagation();const F=B.target.value;!k&&F&&(f({mode:h.availableModes.find(U=>U===F)??h.mode}),c.setMode({mode:h.availableModes.find(U=>U===F)??h.mode}))},className:ne("w-full rounded border border-border bg-surface px-3 py-1.5 text-sm",k&&"opacity-40 cursor-not-allowed"),children:h.availableModes.map(B=>v.jsx("option",{value:B,children:B},B))})]})}function JNe(e){return e==="locked"||e==="locking"}function k8(e){return e==="jammed"}var eOe={locked:{colorClass:"border-success/30 bg-success/10 text-success",icon:"locked"},locking:{colorClass:"border-success/30 bg-success/10 text-success",icon:"locked"},unlocked:{colorClass:"border-warning/30 bg-warning/10 text-warning",icon:"open"},unlocking:{colorClass:"border-warning/30 bg-warning/10 text-warning",icon:"open"},jammed:{colorClass:"border-danger/30 bg-danger/10 text-danger",icon:"locked"}};function tOe({state:e}){const t=eOe[e];return v.jsx("div",{"data-testid":"lock-glyph","data-state":e,className:ne("flex h-16 w-16 items-center justify-center rounded-full border-2",t.colorClass),children:t.icon==="locked"?v.jsx(Bm,{className:"h-8 w-8","aria-hidden":"true"}):v.jsx(NS,{className:"h-8 w-8","aria-hidden":"true"})})}function aOe({state:e}){return v.jsx("span",{className:ne("text-sm font-medium capitalize",k8(e)?"text-danger":"text-foreground-muted"),children:e})}function nOe({busy:e,onOpen:t}){return v.jsxs("button",{type:"button","aria-label":"Open (unlatch)",title:"Open (unlatch)",disabled:e,onClick:a=>{a.stopPropagation(),t()},className:ne("inline-flex items-center gap-1.5 rounded-md border border-border px-3 py-1.5 text-xs font-medium","text-foreground-muted hover:bg-surface-hover transition-colors",e&&"opacity-40 cursor-not-allowed"),children:[v.jsx(Zc,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Open"]})}function iOe({trpc:e,deviceId:t,features:a,optimistic:r}){const{cap:c,slice:m,available:d}=Nt({trpc:e,deviceId:t,cap:j=>j.lockControl,slice:j=>j.state.lockControl}),{display:h,applyOptimistic:f}=ra(m,{enabled:r??!0});if(c===void 0||h===void 0)return null;const k=JNe(h.state),x=k8(h.state)||!d,E=a?.includes(Ht.LockOpen)===!0,R=()=>{x||(k?(f({state:"unlocking"}),c.unlock({})):(f({state:"locking"}),c.lock({})))},T=()=>{x||c.open({})},N=k?"Unlock":"Lock";return v.jsxs("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:[v.jsxs("div",{className:"flex flex-col items-center gap-2",children:[v.jsx(tOe,{state:h.state}),v.jsx(aOe,{state:h.state})]}),v.jsx("div",{className:ne(x&&"pointer-events-none opacity-40"),children:v.jsx(H_e,{on:k,targetLabel:N,onConfirm:R})}),E&&v.jsx("div",{className:"flex justify-center",children:v.jsx(nOe,{busy:x,onOpen:T})})]})}var nw=500,S8=150,rOe="linear-gradient(90deg, #9ec9ff, #ffffff, #ffb24d)";function oOe(e,t,a){return Math.min(1,Math.max(0,(e-t)/(a-t)))}function sOe(e){return oOe(e,S8,nw)}var lOe="#f4b740",cOe="#d4d4d8";function dOe({trpc:e,deviceId:t,features:a,optimistic:r}){const c=Nt({trpc:e,deviceId:t,cap:H=>H.switch,slice:H=>H.state.switch}),m=Nt({trpc:e,deviceId:t,cap:H=>H.brightness,slice:H=>H.state.brightness}),d=Nt({trpc:e,deviceId:t,cap:H=>H.color,slice:H=>H.state.color}),h=ra(c.slice,{enabled:r??!0}),f=ra(m.slice,{enabled:r??!0}),k=ra(d.slice,{enabled:r??!0});if(c.cap===void 0||h.display===void 0)return null;const x=h.display.on===!0,E=!c.available,R=f.display?.percentage??0,T=!m.available,N=x?R/100:0,j=x?lOe:cOe,q=(a?.includes(Ht.LightColorMired)??!1)&&d.cap!==void 0,B=k.display?.mireds,F=!d.available,U=()=>{if(E)return;const H=!x;h.applyOptimistic({on:H}),c.cap?.setState({on:H})};return v.jsxs("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:[v.jsxs("div",{className:"flex flex-col items-center gap-3",children:[v.jsxs(HL,{fraction:N,color:j,children:[v.jsxs("div",{"data-testid":"brightness-readout",className:"text-3xl font-bold tabular-nums text-foreground leading-none",children:[R,v.jsx("span",{className:"text-base text-foreground-subtle font-normal ml-0.5",children:"%"})]}),v.jsx(Fg,{className:"h-5 w-5 text-foreground-subtle","aria-hidden":"true"})]}),m.cap!==void 0&&v.jsxs("label",{className:"flex w-full items-center gap-2 text-xs text-foreground-subtle",children:[v.jsx("span",{className:"w-16",children:"Brightness"}),v.jsx("input",{"aria-label":"Brightness",type:"range",min:0,max:100,step:1,className:"flex-1",value:R,disabled:T||!x,onChange:H=>{const Q=Number(H.target.value);f.applyOptimistic({percentage:Q}),T||m.cap?.setBrightness({percentage:Q})}}),v.jsxs("span",{className:"tabular-nums w-9 text-right",children:[R,"%"]})]})]}),v.jsxs("div",{className:"flex items-center justify-between",children:[v.jsx("span",{className:"text-sm font-medium text-foreground-muted",children:x?"On":"Off"}),v.jsx(Cx,{on:x,busy:E,onToggle:U})]}),q&&v.jsxs("div",{className:"flex items-center gap-2","data-testid":"color-temp-strip",children:[v.jsx(Ug,{className:"h-4 w-4 text-foreground-subtle","aria-hidden":"true"}),v.jsxs("label",{className:"flex-1",children:[v.jsx("span",{className:"sr-only",children:"Colour temperature"}),v.jsx("input",{"aria-label":"Colour temperature",type:"range",min:S8,max:nw,step:1,className:"w-full",value:B??nw,disabled:F||!x,onChange:H=>{const Q=Number(H.target.value);k.applyOptimistic({mode:"mired",mireds:Q}),F||d.cap?.setColor({color:{mode:"mired",mireds:Q}})}}),v.jsx("div",{className:"pointer-events-none mt-1",children:v.jsx(ew,{fraction:B!==void 0?sOe(B):.5,color:rOe})})]})]})]})}var uOe="#3aa6a0",mOe="#d4d4d8";function pOe({trpc:e,deviceId:t,features:a,optimistic:r}){const c=Nt({trpc:e,deviceId:t,cap:W=>W.switch,slice:W=>W.state.switch}),m=Nt({trpc:e,deviceId:t,cap:W=>W.fanControl,slice:W=>W.state.fanControl}),d=ra(c.slice,{enabled:r??!0}),h=ra(m.slice,{enabled:r??!0});if(c.cap===void 0||d.display===void 0)return null;const f=d.display.on===!0,k=!c.available,x=h.display?.percentage??0,E=!m.available,R=f?x/100:0,T=f?uOe:mOe,N=a?.includes(Ht.FanSpeed)??!1,j=(a?.includes(Ht.FanOscillating)??!1)&&m.cap!==void 0,q=h.display?.availablePresets??[],B=(a?.includes(Ht.FanPreset)??!1)&&m.cap!==void 0&&q.length>0,F=h.display?.preset??"",U=h.display?.oscillating===!0,H=()=>{if(k)return;const W=!f;d.applyOptimistic({on:W}),c.cap?.setState({on:W})},Q=()=>{if(E)return;const W=!U;h.applyOptimistic({oscillating:W}),m.cap?.setOscillating({oscillating:W})},te=W=>{if(E)return;const oe=h.display;if(oe===void 0)return;const he=oe.percentageStep!==void 0&&oe.percentageStep>0?oe.percentageStep:1,Ae=Math.min(100,Math.max(0,Math.round(W*100/he)*he));h.applyOptimistic({percentage:Ae}),m.cap?.setPercentage({percentage:Ae})},K=W=>{E||W===""||(h.applyOptimistic({preset:W}),m.cap?.setPreset({preset:W}))};return v.jsxs("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:[v.jsx("div",{className:"flex flex-col items-center gap-3",children:N?v.jsxs(HL,{fraction:R,color:T,onDragFraction:te,children:[v.jsxs("div",{"data-testid":"speed-readout",className:"text-3xl font-bold tabular-nums text-foreground leading-none",children:[x,v.jsx("span",{className:"text-base text-foreground-subtle font-normal ml-0.5",children:"%"})]}),v.jsx(Vf,{className:"h-5 w-5 text-foreground-subtle","aria-hidden":"true"})]}):v.jsx("div",{"data-testid":"fan-onoff-icon",className:"flex h-[150px] w-[150px] items-center justify-center",children:v.jsx(Vf,{className:"h-16 w-16",style:{color:T},"aria-hidden":"true"})})}),B&&v.jsx("div",{className:"flex justify-center",children:v.jsxs("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[v.jsx("span",{children:"Preset"}),v.jsxs("select",{"aria-label":"Fan preset",value:F,disabled:E,onChange:W=>{W.stopPropagation(),K(W.target.value)},className:ne("bg-surface border border-border rounded px-1 py-0.5",E&&"opacity-40 cursor-not-allowed"),children:[v.jsx("option",{value:"",disabled:!0,children:"—"}),q.map(W=>v.jsx("option",{value:W,children:W},W))]})]})}),v.jsxs("div",{className:"flex items-center justify-between gap-2",children:[j?v.jsxs("button",{type:"button","aria-label":"Oscillate","aria-pressed":U,disabled:E,onClick:W=>{W.stopPropagation(),Q()},className:ne("inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs font-medium transition-colors",U?"border-success/50 bg-success/10 text-success":"border-border text-foreground-muted hover:bg-surface-hover",E&&"opacity-40 cursor-not-allowed"),children:[v.jsx(dx,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Oscillate"]}):v.jsx("span",{className:"text-sm font-medium text-foreground-muted",children:f?"On":"Off"}),v.jsx(Cx,{on:f,busy:k,onToggle:H})]})]})}function hOe({trpc:e,deviceId:t,optimistic:a}){const{cap:r,slice:c,available:m}=Nt({trpc:e,deviceId:t,cap:E=>E.switch,slice:E=>E.state.switch}),{display:d,applyOptimistic:h}=ra(c,{enabled:a??!0});if(r===void 0||d===void 0)return null;const f=d.on===!0,k=!m,x=()=>{if(k)return;const E=!f;h({on:E}),r.setState({on:E})};return v.jsxs("div",{className:"flex flex-col items-center gap-4 rounded-lg border border-border bg-surface p-6",children:[v.jsx("div",{"data-testid":"switch-glyph","data-state":f?"on":"off",className:ne("flex h-16 w-16 items-center justify-center rounded-full border-2 transition-colors",f?"border-success/30 bg-success/10 text-success":"border-border bg-surface-subtle text-foreground-subtle"),children:v.jsx($m,{className:"h-8 w-8","aria-hidden":"true"})}),v.jsx("span",{className:"text-sm font-medium text-foreground-muted",children:f?"On":"Off"}),v.jsx(Cx,{on:f,busy:k,onToggle:x})]})}function fOe(e){return e==="playing"||e==="buffering"?"pause":"play"}function gOe(e,t){return e===null||t===null||t<=0?0:Math.min(1,Math.max(0,e/t))}function Y4(e){if(e===null)return"--:--";const t=Math.floor(e/1e3);return`${Math.floor(t/60)}:${(t%60).toString().padStart(2,"0")}`}function vOe({title:e,subtitle:t}){return v.jsxs("div",{className:"flex flex-col items-center gap-1 text-center",children:[v.jsx(Lq,{className:"h-6 w-6 text-foreground-subtle","aria-hidden":"true"}),v.jsx("span",{className:"text-base font-semibold text-foreground line-clamp-1",children:e??"Nothing playing"}),t&&v.jsx("span",{className:"text-xs text-foreground-subtle line-clamp-1",children:t})]})}function G1({label:e,busy:t,onPress:a,children:r,primary:c}){return v.jsx("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:m=>{m.stopPropagation(),t||a()},className:ne("inline-flex items-center justify-center rounded-full transition-colors",c?"h-12 w-12 bg-primary text-primary-foreground hover:bg-primary/90 shadow-md":"h-10 w-10 text-foreground-muted hover:bg-surface-hover",t&&"opacity-40 cursor-not-allowed"),children:r})}function yOe({trpc:e,deviceId:t,features:a,optimistic:r}){const{cap:c,slice:m,available:d}=Nt({trpc:e,deviceId:t,cap:U=>U.mediaPlayer,slice:U=>U.state.mediaPlayer}),{display:h,applyOptimistic:f}=ra(m,{enabled:r??!0});if(c===void 0||h===void 0)return null;const k=!d,x=fOe(h.state),E=(a?.includes(Ht.MediaPlayerSeek)??!1)&&h.durationMs!==null&&h.durationMs>0,R=a?.includes(Ht.MediaPlayerNext)??!1,T=a?.includes(Ht.MediaPlayerPrevious)??!1,N=(a?.includes(Ht.MediaPlayerVolume)??!1)&&h.volumeLevel!==null,j=()=>{k||(x==="play"?(f({state:"playing"}),c.play({})):(f({state:"paused"}),c.pause({})))},q=h.currentMedia?.artist??h.currentMedia?.album??null,B=gOe(h.positionMs,h.durationMs),F=h.volumeLevel??0;return v.jsxs("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-6",children:[v.jsx(vOe,{title:h.currentMedia?.title??null,subtitle:q}),E&&v.jsxs("div",{"data-testid":"media-seek",className:"flex flex-col gap-1",children:[v.jsxs("label",{className:"relative block",children:[v.jsx("span",{className:"sr-only",children:"Seek"}),v.jsx("input",{"aria-label":"Seek",type:"range",min:0,max:h.durationMs??0,step:1e3,className:"absolute inset-0 h-4 w-full cursor-pointer opacity-0",value:h.positionMs??0,disabled:k,onChange:U=>{if(k)return;const H=Number(U.target.value);f({positionMs:H}),c.seek({positionMs:H})}}),v.jsx("div",{className:"pointer-events-none",children:v.jsx(ew,{fraction:B})})]}),v.jsxs("div",{className:"flex justify-between text-[11px] tabular-nums text-foreground-subtle",children:[v.jsx("span",{children:Y4(h.positionMs)}),v.jsx("span",{children:Y4(h.durationMs)})]})]}),v.jsxs("div",{className:"flex items-center justify-center gap-4",children:[T&&v.jsx(G1,{label:"Previous",busy:k,onPress:()=>{c.previous({})},children:v.jsx(EIe,{className:"h-5 w-5","aria-hidden":"true"})}),v.jsx(G1,{label:x==="play"?"Play":"Pause",busy:k,onPress:j,primary:!0,children:x==="play"?v.jsx(vl,{className:"h-6 w-6","aria-hidden":"true"}):v.jsx(Fm,{className:"h-6 w-6","aria-hidden":"true"})}),R&&v.jsx(G1,{label:"Next",busy:k,onPress:()=>{c.next({})},children:v.jsx(RIe,{className:"h-5 w-5","aria-hidden":"true"})})]}),N&&v.jsxs("div",{"data-testid":"media-volume",className:"flex items-center gap-2",children:[v.jsx("button",{type:"button","aria-label":h.isMuted===!0?"Unmute":"Mute",title:h.isMuted===!0?"Unmute":"Mute",disabled:k,onClick:U=>{if(U.stopPropagation(),k||h.isMuted===null)return;const H=!h.isMuted;f({isMuted:H}),c.setMute({muted:H})},className:ne("inline-flex h-7 w-7 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",k&&"opacity-40 cursor-not-allowed"),children:h.isMuted===!0?v.jsx(Vq,{className:"h-4 w-4","aria-hidden":"true"}):v.jsx(Qm,{className:"h-4 w-4","aria-hidden":"true"})}),v.jsxs("label",{className:"relative block flex-1",children:[v.jsx("span",{className:"sr-only",children:"Volume"}),v.jsx("input",{"aria-label":"Volume",type:"range",min:0,max:100,step:1,className:"absolute inset-0 h-4 w-full cursor-pointer opacity-0",value:F,disabled:k,onChange:U=>{if(k)return;const H=Number(U.target.value);f({volumeLevel:H}),c.setVolume({volumeLevel:H})}}),v.jsx("div",{className:"pointer-events-none",children:v.jsx(ew,{fraction:F/100})})]}),v.jsxs("span",{className:"w-9 text-right text-[11px] tabular-nums text-foreground-subtle",children:[F,"%"]})]})]})}var w8={disarmed:{label:"Disarmed",colorClass:"border-border bg-surface-subtle text-foreground-subtle",icon:"disarmed"},armed_home:{label:"Armed Home",colorClass:"border-success/30 bg-success/10 text-success",icon:"armed"},armed_away:{label:"Armed Away",colorClass:"border-success/30 bg-success/10 text-success",icon:"armed"},armed_night:{label:"Armed Night",colorClass:"border-success/30 bg-success/10 text-success",icon:"armed"},armed_vacation:{label:"Armed Vacation",colorClass:"border-success/30 bg-success/10 text-success",icon:"armed"},armed_custom_bypass:{label:"Armed (Bypass)",colorClass:"border-success/30 bg-success/10 text-success",icon:"armed"},arming:{label:"Arming…",colorClass:"border-warning/30 bg-warning/10 text-warning",icon:"pending"},disarming:{label:"Disarming…",colorClass:"border-warning/30 bg-warning/10 text-warning",icon:"pending"},pending:{label:"Pending",colorClass:"border-warning/30 bg-warning/10 text-warning",icon:"pending"},triggered:{label:"Triggered",colorClass:"border-danger/30 bg-danger/10 text-danger",icon:"triggered"}},x8={home:"Home",away:"Away",night:"Night",vacation:"Vacation",custom_bypass:"Bypass"};function M8(e){return e.startsWith("armed_")}function Rx(e){return e==="arming"||e==="disarming"}function C8({icon:e,sizeClass:t="h-8 w-8"}){return e==="disarmed"?v.jsx(AIe,{className:t,"aria-hidden":"true"}):e==="triggered"?v.jsx(Um,{className:t,"aria-hidden":"true"}):e==="pending"?v.jsx(IIe,{className:t,"aria-hidden":"true"}):v.jsx(CIe,{className:t,"aria-hidden":"true"})}function X4({label:e,active:t,busy:a,onSelect:r}){return v.jsx("button",{type:"button","aria-label":e,"aria-pressed":t,disabled:a,onClick:c=>{c.stopPropagation(),a||r()},className:ne("flex-1 rounded-md px-3 py-2 text-sm font-medium transition-colors",t?"bg-primary text-primary-foreground shadow-sm":"text-foreground-muted hover:bg-surface-hover",a&&"opacity-40 cursor-not-allowed"),children:e})}function bOe({state:e,availableModes:t,busy:a,onDisarm:r,onArm:c}){const m=M8(e),d=Rx(e);return v.jsxs("div",{className:ne("flex min-w-0 items-stretch gap-1 rounded-lg border border-border bg-surface-subtle p-1"),children:[v.jsx(X4,{label:"Disarm",active:!m&&!d,busy:a,onSelect:r}),t.map(h=>v.jsx(X4,{label:x8[h],active:!d&&e===`armed_${h}`,busy:a,onSelect:()=>c(h)},h))]})}function J4(e){return e instanceof Error?e.message:String(e)}function A8(e,t,a){const{cap:r,slice:c,available:m}=Nt({trpc:e,deviceId:t,cap:q=>q.alarmPanel,slice:q=>q.state.alarmPanel}),{display:d,applyOptimistic:h,rollback:f}=ra(c,{enabled:a??!0}),[k,x]=P.useState(null),E=()=>x(null),R=P.useRef(0);P.useEffect(()=>{x(null)},[c]);const T=!m;return{display:d,capPresent:r!==void 0,busy:T,handleDisarm:()=>{if(r===void 0||T)return;const q=++R.current;h({state:"disarming"}),r.disarm({}).catch(B=>{R.current===q&&(f(),x(J4(B)))})},handleArm:q=>{if(r===void 0||T)return;const B=++R.current;h({state:"arming"}),r.arm({mode:q}).catch(F=>{R.current===B&&(f(),x(J4(F)))})},error:k,clearError:E}}function kOe({trpc:e,deviceId:t,optimistic:a}){const{display:r,capPresent:c,busy:m,handleDisarm:d,handleArm:h,error:f}=A8(e,t,a);if(!c||r===void 0)return null;const k=w8[r.state],x=M8(r.state)?r.state.replace("armed_",""):"";return v.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[v.jsxs("span",{className:ne("inline-flex shrink-0 items-center gap-1 rounded-md border px-1.5 py-0.5 text-[11px] font-medium whitespace-nowrap",k.colorClass,Rx(r.state)&&"animate-pulse"),children:[v.jsx(C8,{icon:k.icon,sizeClass:"h-3 w-3"}),k.label]}),v.jsxs("select",{"aria-label":"Alarm mode",disabled:m,value:x,onClick:E=>E.stopPropagation(),onChange:E=>{E.stopPropagation();const R=E.target.value;R===""?d():h(R)},className:ne("min-w-0 shrink rounded-md border border-border bg-surface-subtle px-1.5 py-0.5 text-xs text-foreground-muted",m&&"cursor-not-allowed opacity-40"),children:[v.jsx("option",{value:"",children:"Disarm"}),r.availableModes.map(E=>v.jsx("option",{value:E,children:x8[E]},E))]}),f!==null&&v.jsx("span",{"data-testid":"alarm-inline-error",role:"alert",title:f,className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-danger/10 text-danger",children:v.jsx(Um,{className:"h-3 w-3","aria-hidden":"true"})})]})}function SOe({trpc:e,deviceId:t,optimistic:a}){const{display:r,capPresent:c,busy:m,handleDisarm:d,handleArm:h,error:f,clearError:k}=A8(e,t,a);if(!c||r===void 0)return null;const x=w8[r.state];return v.jsxs("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-6",children:[v.jsxs("div",{className:"flex flex-col items-center gap-2",children:[v.jsx("div",{"data-testid":"alarm-state","data-state":r.state,className:ne("flex h-16 w-16 items-center justify-center rounded-full border-2",x.colorClass,Rx(r.state)&&"animate-pulse"),children:v.jsx(C8,{icon:x.icon})}),v.jsx("span",{className:ne("text-sm font-medium",x.colorClass,"border-0 bg-transparent"),children:x.label})]}),v.jsx(bOe,{state:r.state,availableModes:r.availableModes,busy:m,onDisarm:d,onArm:h}),f!==null&&v.jsxs("div",{"data-testid":"alarm-error",role:"alert",className:"flex items-start justify-between gap-2 rounded-md border border-danger/30 bg-danger/10 px-3 py-2 text-sm text-danger",children:[v.jsx("span",{children:f}),v.jsx("button",{type:"button","aria-label":"Dismiss",onClick:E=>{E.stopPropagation(),k()},className:"shrink-0 font-medium text-danger/80 hover:text-danger",children:"×"})]})]})}function wOe(e,t){if(e<=0)return null;const a=Math.max(0,Math.round((t-e)/1e3));return a<60?"just now":a<3600?`${Math.floor(a/60)} min ago`:a<86400?`${Math.floor(a/3600)} h ago`:new Date(e).toLocaleDateString()}function Tx({atMs:e,neverLabel:t}){const a=wOe(e,Date.now());return v.jsx("span",{className:"text-xs text-foreground-subtle","data-testid":"last-run",children:a===null?t:a})}function I8({error:e}){return e===null||e===""?null:v.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-danger",title:e,"data-testid":"last-error",children:[v.jsx(Yc,{className:"h-3 w-3 shrink-0","aria-hidden":"true"}),v.jsx("span",{className:"truncate",children:e})]})}function E8(e,t,a){const{cap:r,slice:c,available:m}=Nt({trpc:e,deviceId:t,cap:x=>x.scriptRunner,slice:x=>x.state.scriptRunner}),{display:d,applyOptimistic:h}=ra(c,{enabled:a??!0}),f=!m,k=d?.isRunning===!0;return{display:d,capPresent:r!==void 0,busy:f,running:k,run:()=>{r===void 0||f||k||(h({isRunning:!0}),r.run({}))},stop:()=>{r===void 0||f||!k||(h({isRunning:!1}),r.stop({}))}}}function R8({running:e,busy:t,large:a,onRun:r,onStop:c}){const m=e?"Stop":"Run";return v.jsxs("button",{type:"button","aria-label":m,title:m,disabled:t,"data-testid":"script-run","data-running":e?"true":"false",onClick:d=>{d.stopPropagation(),e?c():r()},className:ne("inline-flex items-center gap-1 rounded transition-colors",a?"h-10 px-4 text-sm":"h-5 px-1.5 text-xs",e?"bg-danger text-danger-foreground hover:bg-danger/90":"bg-primary text-primary-foreground hover:bg-primary/90",t&&"cursor-not-allowed opacity-40"),children:[e?v.jsx(V3e,{className:a?"h-4 w-4":"h-3 w-3","aria-hidden":"true"}):v.jsx(vl,{className:a?"h-4 w-4":"h-3 w-3","aria-hidden":"true"}),v.jsx("span",{children:m})]})}function xOe({trpc:e,deviceId:t,optimistic:a}){const{display:r,capPresent:c,busy:m,running:d,run:h,stop:f}=E8(e,t,a);return!c||r===void 0?null:v.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[v.jsx(R8,{running:d,busy:m,large:!1,onRun:h,onStop:f}),v.jsx(Tx,{atMs:r.lastRunAt,neverLabel:"never run"})]})}function MOe({trpc:e,deviceId:t,optimistic:a}){const{display:r,capPresent:c,busy:m,running:d,run:h,stop:f}=E8(e,t,a);return!c||r===void 0?null:v.jsxs("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-6",children:[v.jsxs("div",{className:"flex flex-col items-center gap-2",children:[v.jsx("div",{"data-testid":"script-state","data-running":d?"true":"false",className:ne("flex h-16 w-16 items-center justify-center rounded-full border-2",d?"border-primary text-primary animate-pulse":"border-border text-foreground-subtle"),children:v.jsx(vl,{className:"h-8 w-8","aria-hidden":"true"})}),v.jsx("span",{className:"text-sm font-medium",children:d?"Running":"Idle"}),v.jsx(Tx,{atMs:r.lastRunAt,neverLabel:"never run"}),v.jsx(I8,{error:r.lastError})]}),v.jsx("div",{className:"flex justify-center",children:v.jsx(R8,{running:d,busy:m,large:!0,onRun:h,onStop:f})})]})}function T8(e,t,a){const{cap:r,slice:c,available:m}=Nt({trpc:e,deviceId:t,cap:k=>k.automationControl,slice:k=>k.state.automationControl}),{display:d,applyOptimistic:h}=ra(c,{enabled:a??!0}),f=!m;return{display:d,capPresent:r!==void 0,busy:f,setEnabled:k=>{r===void 0||f||(h({enabled:k}),k?r.enable({}):r.disable({}))},trigger:()=>{r===void 0||f||r.trigger({})}}}function _8({enabled:e,busy:t,onToggle:a}){return v.jsx("button",{type:"button",role:"switch","aria-checked":e,"aria-label":"Automation enabled",disabled:t,"data-testid":"automation-enabled",onClick:r=>{r.stopPropagation(),a(!e)},className:ne("inline-flex shrink-0 items-center gap-1 rounded-md border px-1.5 py-0.5","text-[11px] font-medium whitespace-nowrap transition-colors",e?"border-success/40 bg-success/10 text-success":"border-border bg-surface-subtle text-foreground-subtle",t&&"cursor-not-allowed opacity-40"),children:e?"Enabled":"Disabled"})}function P8({busy:e,large:t,onTrigger:a}){return v.jsxs("button",{type:"button","aria-label":"Trigger",title:"Run this automation now",disabled:e,"data-testid":"automation-trigger",onClick:r=>{r.stopPropagation(),a()},className:ne("inline-flex items-center gap-1 rounded transition-colors",t?"h-10 px-4 text-sm":"h-5 px-1.5 text-xs","bg-primary text-primary-foreground hover:bg-primary/90",e&&"cursor-not-allowed opacity-40"),children:[v.jsx(is,{className:t?"h-4 w-4":"h-3 w-3","aria-hidden":"true"}),v.jsx("span",{children:"Trigger"})]})}function COe({trpc:e,deviceId:t,optimistic:a}){const{display:r,capPresent:c,busy:m,setEnabled:d,trigger:h}=T8(e,t,a);return!c||r===void 0?null:v.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[v.jsx(_8,{enabled:r.enabled,busy:m,onToggle:d}),v.jsx(P8,{busy:m,large:!1,onTrigger:h})]})}function AOe({trpc:e,deviceId:t,optimistic:a}){const{display:r,capPresent:c,busy:m,setEnabled:d,trigger:h}=T8(e,t,a);return!c||r===void 0?null:v.jsxs("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-6",children:[v.jsxs("div",{className:"flex flex-col items-center gap-2",children:[v.jsx("div",{"data-testid":"automation-state","data-enabled":r.enabled?"true":"false",className:ne("flex h-16 w-16 items-center justify-center rounded-full border-2",r.enabled?"border-success text-success":"border-border text-foreground-subtle"),children:v.jsx(is,{className:"h-8 w-8","aria-hidden":"true"})}),v.jsx("span",{className:"text-sm font-medium",children:r.enabled?"Enabled":"Disabled"}),v.jsx(Tx,{atMs:r.lastTriggeredAt,neverLabel:"never triggered"}),v.jsx(I8,{error:r.lastError})]}),v.jsxs("div",{className:"flex items-center justify-center gap-3",children:[v.jsx(_8,{enabled:r.enabled,busy:m,onToggle:d}),v.jsx(P8,{busy:m,large:!0,onTrigger:h})]})]})}function IOe({children:e}){return v.jsx("div",{className:"flex flex-col items-stretch gap-3 rounded-lg border border-border bg-surface p-4",children:e})}function N8(e,t){const{cap:a}=Nt({trpc:e,deviceId:t,cap:r=>r.switch,slice:r=>r.state.switch});return a!==void 0}function EOe({trpc:e,deviceId:t,features:a,optimistic:r}){return N8(e,t)?v.jsx(Ax,{trpc:e,deviceId:t,features:a,layout:"compact",optimistic:r}):null}function ROe(e,t){const{cap:a}=Nt({trpc:e,deviceId:t,cap:r=>r.lockControl,slice:r=>r.state.lockControl});return a!==void 0}function TOe({trpc:e,deviceId:t,features:a,optimistic:r}){return ROe(e,t)?v.jsx(J_e,{trpc:e,deviceId:t,features:a,layout:"compact",optimistic:r}):null}function _Oe({trpc:e,deviceId:t,features:a,optimistic:r}){return N8(e,t)?v.jsxs("div",{className:"inline-flex items-center gap-2",children:[v.jsx(Ax,{trpc:e,deviceId:t,features:a,layout:"compact",optimistic:r}),v.jsx(ePe,{trpc:e,deviceId:t,features:a,layout:"compact",optimistic:r})]}):null}function POe(e,t){const{cap:a}=Nt({trpc:e,deviceId:t,cap:r=>r.fanControl,slice:r=>r.state.fanControl});return a!==void 0}function NOe({trpc:e,deviceId:t,features:a,optimistic:r}){return POe(e,t)?v.jsxs("div",{className:"inline-flex items-center gap-2",children:[v.jsx(Ax,{trpc:e,deviceId:t,features:a,layout:"compact",optimistic:r}),v.jsx(tPe,{trpc:e,deviceId:t,features:a,layout:"compact",optimistic:r})]}):null}function _x(e,t){const{cap:a}=Nt({trpc:e,deviceId:t,cap:r=>r.climateControl,slice:r=>r.state.climateControl});return a!==void 0}function OOe({trpc:e,deviceId:t,features:a,optimistic:r}){return _x(e,t)?v.jsx(nPe,{trpc:e,deviceId:t,features:a,layout:"compact",optimistic:r}):null}function DOe({trpc:e,deviceId:t,features:a,optimistic:r}){return _x(e,t)?v.jsx(b8,{trpc:e,deviceId:t,features:a,layout:"compact",optimistic:r}):null}function jOe({trpc:e,deviceId:t,features:a,optimistic:r}){return _x(e,t)?v.jsx(b8,{trpc:e,deviceId:t,features:a,layout:"full",optimistic:r}):null}function zOe(e,t){const{cap:a}=Nt({trpc:e,deviceId:t,cap:r=>r.mediaPlayer,slice:r=>r.state.mediaPlayer});return a!==void 0}function qOe({trpc:e,deviceId:t,features:a,optimistic:r}){return zOe(e,t)?v.jsx(cPe,{trpc:e,deviceId:t,features:a,layout:"compact",optimistic:r}):null}function O8(e,t){const{cap:a}=Nt({trpc:e,deviceId:t,cap:r=>r.control,slice:r=>r.state.control});return a!==void 0}function LOe({trpc:e,deviceId:t,features:a,optimistic:r}){return O8(e,t)?v.jsx(KL,{trpc:e,deviceId:t,features:a,layout:"compact",optimistic:r}):null}function BOe({trpc:e,deviceId:t,features:a,optimistic:r}){return O8(e,t)?v.jsx(IOe,{children:v.jsx(KL,{trpc:e,deviceId:t,features:a,layout:"full",optimistic:r})}):null}var FOe={cover:{InlineControl:IPe,HeroCard:TPe},valve:{InlineControl:mNe,HeroCard:gNe},humidifier:{InlineControl:yNe,HeroCard:kNe},"water-heater":{InlineControl:xNe,HeroCard:CNe},switch:{InlineControl:EOe,HeroCard:hOe},light:{InlineControl:_Oe,HeroCard:dOe},fan:{InlineControl:NOe,HeroCard:pOe},sensor:{InlineControl:OPe,HeroCard:$Pe},thermostat:{InlineControl:OOe,HeroCard:XNe},climate:{InlineControl:DOe,HeroCard:jOe},button:{InlineControl:W_e,HeroCard:Z_e},update:{InlineControl:UPe,HeroCard:HPe},lock:{InlineControl:TOe,HeroCard:iOe},"media-player":{InlineControl:qOe,HeroCard:yOe},alarm:{InlineControl:kOe,HeroCard:SOe},control:{InlineControl:LOe,HeroCard:BOe},weather:{InlineControl:ENe,HeroCard:_Ne},vacuum:{InlineControl:eNe,HeroCard:tNe},"lawn-mower":{InlineControl:cNe,HeroCard:dNe},image:{InlineControl:PNe,HeroCard:NNe},"pet-feeder":{InlineControl:jNe,HeroCard:zNe},script:{InlineControl:xOe,HeroCard:MOe},automation:{InlineControl:COe,HeroCard:AOe},dummy:{InlineControl:_Pe,HeroCard:PPe}};Object.fromEntries(Object.values(O).map(e=>[e,FOe[JCe[e]]]));O.Cover+"",O.Valve+"",O.Thermostat+"",O.Climate+"",O.Control+"",O.Button+"",O.MediaPlayer+"",O.AlarmPanel+"",O.Lock+"",O.Vacuum+"",O.LawnMower+"",O.Humidifier+"",O.Switch+"",O.Siren+"",O.Light+"",O.Fan+"",O.WaterHeater+"",O.Sensor+"",O.Presence+"",O.EventEmitter+"",O.Notifier+"",O.Script+"",O.Automation+"",O.Camera+"",O.Hub+"",O.Update+"",O.Generic+"",O.Weather+"",O.Container+"",O.Image+"",O.PetFeeder+"";new Set(Object.values(O));P.createContext(null);O.Sensor,O.Presence;var $Oe={};P.createContext($Oe);Oi("camstack:device-quick-detail",null);o({id:i(),stableId:n(),addonId:n(),type:n(),name:n(),online:w(),disabled:w(),parentDeviceId:i().nullable(),role:n().nullable().optional(),features:y(n()).optional(),isCamera:w().optional()});function to(e){return e.deviceKey!==void 0?`${e.agentNodeId}::${e.deviceKey}`:e.agentNodeId}function D8(e){const t=[];for(const a of e){const r=t[t.length-1];if(r&&r.agentNodeId===a.agentNodeId){const c=[...r.columns,a];t[t.length-1]={...r,columns:c,grouped:c.length>1}}else t.push({agentNodeId:a.agentNodeId,engineLabel:a.engineLabel,columns:[a],grouped:!1})}return t}function UOe(e){const t=[],a=(r,c)=>{for(const m of r)t.push({node:m,depth:c}),a(m.children,c+1)};return a(e,0),t}function HOe(e,t,a,r=208,c=t){return e<=0?!1:t<=1?e<a+r*c:e<a+r*2}var eT={detector:{label:"detector",className:"text-emerald-500"},cropper:{label:"cropper",className:"text-blue-500"},classifier:{label:"classifier",className:"text-violet-500"},refiner:{label:"refiner",className:"text-amber-500"},"audio-classifier":{label:"audio classifier",className:"text-pink-500"}};function QOe({slot:e}){const t=eT[e]??eT.classifier;return v.jsx("span",{className:ne("text-[9px] font-semibold uppercase tracking-widest leading-none",t.className),children:t.label})}var tT="inline-flex items-center rounded bg-muted px-1.5 py-px text-[9px] font-medium text-foreground-subtle";function VOe({inputs:e,outputs:t}){return e.length===0&&t.length===0?null:v.jsxs("span",{className:"inline-flex items-center gap-1 flex-wrap",children:[e.map(a=>v.jsx("span",{className:ne(tT,"bg-blue-500/10 text-blue-500"),children:a},`in-${a}`)),e.length>0&&t.length>0&&v.jsx("span",{className:"text-foreground-subtle/60 text-[9px]",children:"→"}),t.map(a=>v.jsx("span",{className:ne(tT,"bg-emerald-500/10 text-emerald-500"),children:a},`out-${a}`))]})}function j8({column:e}){const t=e.deviceLabel??e.deviceKey;return v.jsxs(v.Fragment,{children:[(t!==void 0||e.disabled===!0)&&v.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[t!==void 0&&v.jsx("span",{className:"truncate text-[10px] font-medium text-foreground/90",children:t}),e.disabled===!0&&v.jsx("span",{className:"shrink-0 rounded bg-muted px-1 text-[8px] font-semibold uppercase text-foreground-subtle",children:"off"})]}),v.jsx("div",{className:"truncate text-[9px] text-foreground-subtle",children:e.engineLabel}),e.detail!==void 0&&v.jsx("div",{className:"truncate font-mono text-[9px] text-foreground-subtle",title:e.detail,children:e.detail})]})}function KOe({group:e}){const t=e.columns[0]?.nodeLabel??e.agentNodeId;return v.jsxs("div",{role:"columnheader",className:"sticky top-0 z-10 min-w-0 border-b border-l border-border bg-muted/60",style:{gridColumn:`span ${e.columns.length}`},children:[v.jsx("div",{className:"truncate px-3 pt-2 pb-1 text-xs font-semibold text-foreground",children:t}),v.jsx("div",{className:"mt-1 flex border-t border-border/50",children:e.columns.map((a,r)=>v.jsx("div",{className:ne("min-w-0 flex-1 px-3 py-1",r>0&&"border-l border-border/50",a.disabled===!0&&"opacity-70"),title:`${a.deviceLabel??a.deviceKey} · ${a.engineLabel}${a.detail?` · ${a.detail}`:""}`,children:v.jsx(j8,{column:a})},to(a)))})]})}function GOe({node:e}){return v.jsxs("div",{className:"flex flex-col gap-1 min-w-0 flex-1",children:[v.jsx(QOe,{slot:e.slot}),v.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[v.jsx("span",{className:"font-semibold truncate",children:e.addonName}),v.jsx(VOe,{inputs:e.inputClasses,outputs:e.outputClasses})]})]})}function WOe(e){return e.kind==="enabled"?v.jsxs("span",{className:"flex min-w-0 items-center gap-1",title:e.overridden?"override":void 0,children:[v.jsx("span",{className:ne("h-1.5 w-1.5 rounded-full shrink-0",e.overridden?"bg-amber-500":"bg-emerald-500")}),v.jsx("span",{className:"font-mono text-foreground truncate",children:e.modelId}),e.suppliedByRoot!==void 0&&v.jsx("span",{className:"ml-auto shrink-0 truncate rounded bg-primary/10 px-1 text-[8px] font-semibold uppercase text-primary",title:`Uses the root model ${e.suppliedByRoot} — this step's own model does not run here`,children:"root"}),e.clusterWide===!0&&v.jsx("span",{className:"ml-auto shrink-0 text-[8px] font-semibold uppercase text-primary",title:"One value for the whole cluster — this step writes into a shared vector index",children:"cluster"}),e.jumpTo!==void 0&&v.jsxs("span",{className:"ml-auto shrink-0 text-[8px] font-semibold text-sky-500",title:`runs on ${e.jumpTo}`,children:["→ ",e.jumpTo]}),e.overridden&&e.jumpTo===void 0&&v.jsx("span",{className:"ml-auto shrink-0 text-[8px] font-semibold uppercase text-amber-500",children:"ovr"})]}):e.kind==="disabled"?v.jsxs("span",{className:"flex min-w-0 items-center gap-1 text-foreground-subtle",title:e.overridden?"override":void 0,children:[v.jsx("span",{className:ne("h-1.5 w-1.5 rounded-full shrink-0",e.overridden?"bg-amber-500":"border border-foreground-subtle/60")}),v.jsx("span",{className:"truncate",children:"off"}),e.overridden&&v.jsx("span",{className:"ml-auto shrink-0 text-[8px] font-semibold uppercase text-amber-500",children:"ovr"})]}):e.kind==="skip"?e.jumpTo!==void 0?v.jsxs("span",{className:"flex min-w-0 items-center gap-1 text-sky-500",title:`no build for this device — auto-jumps to ${e.jumpTo}`,children:[v.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-sky-500 shrink-0"}),v.jsxs("span",{className:"truncate font-medium",children:["→ ",e.jumpTo]})]}):v.jsxs("span",{className:"flex min-w-0 items-center gap-1 text-amber-500",title:"Gated on for this camera, but no compatible model on this node — click to provision",children:[v.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-amber-500 shrink-0"}),v.jsx("span",{className:"truncate font-medium",children:"⚠ skip"})]}):v.jsxs("span",{className:"flex min-w-0 items-center gap-1 text-foreground-subtle/70",children:[v.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-muted shrink-0"}),v.jsx("span",{className:"truncate",children:"—"})]})}function ZOe(e,t,a){return ne("text-left text-xs hover:bg-muted/40",e.kind==="enabled"&&"bg-emerald-500/5",e.kind==="skip"&&"bg-amber-500/5",e.kind==="na"&&"bg-muted/30",t&&"ring-2 ring-primary ring-inset",a)}var z8=18,YOe=z8*16,XOe=11;function JOe(e,t,a,r){const c=(m,d)=>({r:Math.max(0,Math.min(a-1,m)),c:Math.max(0,Math.min(r-1,d))});switch(e){case"ArrowRight":return c(t.r,t.c+1);case"ArrowLeft":return c(t.r,t.c-1);case"ArrowDown":return c(t.r+1,t.c);case"ArrowUp":return c(t.r-1,t.c);case"Home":return c(t.r,0);case"End":return c(t.r,r-1);case"PageDown":return c(a-1,t.c);case"PageUp":return c(0,t.c);default:return null}}function eDe({node:e,depth:t,r:a,tabbable:r,selected:c,badge:m,onClick:d,sticky:h}){return v.jsx("div",{role:"rowheader",className:ne("min-w-0 border-b border-border bg-surface",h&&"sticky left-0 z-10"),children:v.jsxs("button",{type:"button","data-r":a,"data-c":0,"data-step":e.addonId,"data-col":"",tabIndex:r?0:-1,"aria-current":c?"true":void 0,onClick:d?f=>d(f.detail===0):void 0,className:ne("flex h-full w-full min-w-0 items-start gap-2 px-3 py-2 text-left text-xs outline-none","hover:bg-muted/40 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",c&&"bg-primary/10 shadow-[inset_3px_0_0_var(--color-primary)]"),style:{paddingLeft:`${12+t*14}px`},children:[v.jsx(GOe,{node:e}),m]})})}function tDe({nodes:e,selected:t,onSelect:a}){return v.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",role:"tablist","aria-label":"Node",children:[v.jsx(MIe,{className:"h-3.5 w-3.5 text-foreground-subtle"}),v.jsx("span",{className:"text-[10px] uppercase tracking-wider text-foreground-subtle",children:"Node"}),v.jsx("div",{className:"flex overflow-hidden rounded-md border border-border text-[11px] font-medium",children:e.map((r,c)=>{const m=r.agentNodeId===t;return v.jsx("button",{type:"button",role:"tab","aria-selected":m,onClick:()=>a(r.agentNodeId),title:`${r.columns[0]?.nodeLabel??r.agentNodeId} · ${r.engineLabel}`,className:ne("px-2.5 py-1 transition-colors",m?"bg-primary/15 text-primary":"bg-transparent text-foreground-subtle hover:bg-surface-hover hover:text-foreground",c>0&&"border-l border-border"),children:r.columns[0]?.nodeLabel??r.agentNodeId},r.agentNodeId)})})]})}var aDe=P.forwardRef(function({tree:t,agents:a,getCellState:r,onCellClick:c,onStepClick:m,stepBadge:d,selectedCell:h,single:f,reserveRightPx:k,label:x},E){const R=P.useMemo(()=>UOe(t),[t]),T=P.useMemo(()=>D8(a),[a]),N=P.useRef(null),j=f?XOe:z8,q=`${j}rem repeat(${a.length}, 13rem)`,B=a.length+1,[F,U]=P.useState(!0);P.useLayoutEffect(()=>{const he=N.current;if(!he||k<=0){U(!0);return}const Ae=()=>{const we=he.getBoundingClientRect().left;U(window.innerWidth-k-we>=j*16+208+24)};return Ae(),window.addEventListener("resize",Ae),()=>window.removeEventListener("resize",Ae)},[k,j]);const H=P.useMemo(()=>{if(h===null)return null;const he=R.findIndex(we=>we.node.addonId===h.addonId);if(he<0)return null;const Ae=a.findIndex(we=>to(we)===to(h));return{r:he,c:Ae<0?0:Ae+1}},[h,R,a]),[Q,te]=P.useState({r:0,c:0});P.useEffect(()=>{H!==null&&te(H)},[H]);const K=Q.r<R.length&&Q.c<B?Q:{r:0,c:0},W=(he,Ae)=>{N.current?.querySelector(`[data-r="${he}"][data-c="${Ae}"]`)?.focus()};P.useImperativeHandle(E,()=>({focusCell:(he,Ae)=>{const we=R.findIndex(Me=>Me.node.addonId===he);if(we<0)return;const Ee=Ae===null?-1:a.findIndex(Me=>to(Me)===Ae),Ie=Ee<0?0:Ee+1;te({r:we,c:Ie}),W(we,Ie)}}),[R,a]),P.useLayoutEffect(()=>{if(H===null)return;const he=N.current,Ae=he?.querySelector(`[data-r="${H.r}"][data-c="${H.c}"]`);if(!he||!Ae||(typeof Ae.scrollIntoView=="function"&&Ae.scrollIntoView({block:"nearest",inline:"nearest"}),k<=0))return;const we=window.innerWidth-k-12,Ee=Ae.getBoundingClientRect().right;Ee>we&&(he.scrollLeft+=Ee-we)},[H,k,F]);const oe=he=>{if(!(he.target instanceof HTMLElement)||he.target.dataset.r===void 0)return;const Ae={r:Number(he.target.dataset.r),c:Number(he.target.dataset.c)},we=JOe(he.key,Ae,R.length,B);we!==null&&(he.preventDefault(),te(we),W(we.r,we.c))};return v.jsx("div",{ref:N,className:"overflow-auto rounded border border-border",children:v.jsxs("div",{className:"flex w-max",children:[v.jsxs("div",{role:"grid","aria-label":x,"aria-rowcount":R.length+1,className:"grid w-max",style:{gridTemplateColumns:q},onKeyDown:oe,children:[v.jsxs("div",{role:"row",className:"contents",children:[v.jsx("div",{role:"columnheader",className:ne("top-0 z-20 border-b border-border bg-muted/60 px-3 py-2 text-[10px] uppercase tracking-widest text-foreground-subtle",F?"sticky left-0":"sticky"),children:"Step"}),T.map(he=>he.grouped?v.jsx(KOe,{group:he},he.agentNodeId):he.columns.map(Ae=>v.jsxs("div",{role:"columnheader",className:ne("sticky top-0 z-10 min-w-0 border-b border-l border-border bg-muted/60 px-3 py-2",Ae.disabled===!0&&"opacity-70"),children:[v.jsx("div",{className:"truncate text-xs font-semibold text-foreground",children:Ae.nodeLabel??Ae.agentNodeId}),v.jsx(j8,{column:Ae})]},to(Ae))))]}),R.map(({node:he,depth:Ae},we)=>v.jsxs("div",{role:"row",className:"contents",children:[v.jsx(eDe,{node:he,depth:Ae,r:we,tabbable:K.r===we&&K.c===0,selected:h?.addonId===he.addonId,badge:d?.(he.addonId),onClick:m?Ee=>m(he.addonId,Ee):void 0,sticky:F}),a.map((Ee,Ie)=>{const Me=r(he.addonId,Ee),Y=h!==null&&h.addonId===he.addonId&&to(h)===to(Ee),de=Me.kind==="enabled"||Me.kind==="skip";return v.jsx("div",{role:"gridcell",className:"min-w-0 border-b border-l border-border",children:v.jsx("button",{type:"button","data-r":we,"data-c":Ie+1,"data-step":he.addonId,"data-col":to(Ee),tabIndex:K.r===we&&K.c===Ie+1?0:-1,"aria-disabled":!de,"aria-selected":Y,onClick:Re=>{de&&c(he.addonId,Ee,Re.detail===0)},className:ZOe(Me,Y,ne("h-full w-full min-w-0 overflow-hidden px-3 py-2 outline-none","focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",!de&&"cursor-default hover:bg-transparent",Ee.disabled===!0&&"opacity-70")),children:WOe(Me)})},to(Ee))})]},he.addonId))]}),k>0&&v.jsx("div",{"aria-hidden":!0,style:{width:k},className:"shrink-0"})]})})});P.forwardRef(function({tree:t,agents:a,getCellState:r,onCellClick:c,selectedCell:m,fallbackNodeId:d,onFallbackNodeChange:h,onStepClick:f,stepBadge:k,reserveRightPx:x=0,label:E="Detection steps"},R){const T=P.useRef(null),[N,j]=P.useState(0);P.useLayoutEffect(()=>{const Q=T.current;if(!Q)return;const te=()=>j(Q.getBoundingClientRect().width);te();const K=typeof ResizeObserver<"u"?new ResizeObserver(te):null;return K?.observe(Q),()=>K?.disconnect()},[]);const q=P.useMemo(()=>D8(a),[a]),B=HOe(N,q.length,YOe,208,a.length),F=P.useMemo(()=>q.length===0?null:q.find(Q=>Q.agentNodeId===d)??q[0]??null,[q,d]),U=m?.agentNodeId;P.useEffect(()=>{B&&U!==void 0&&U!==d&&h(U)},[B,U,d,h]);const H=B&&F?F.columns:a;return v.jsxs("div",{ref:T,className:"w-full space-y-2",children:[B&&F&&q.length>1&&v.jsx(tDe,{nodes:q,selected:F.agentNodeId,onSelect:h}),v.jsx(aDe,{ref:R,tree:t,agents:H,getCellState:r,onCellClick:c,onStepClick:f,stepBadge:k,selectedCell:m,single:B&&F!==null,reserveRightPx:x,label:E})]})});ne(cTe,"min-w-0 max-w-full gap-1.5 py-1 pl-1 pr-2.5 text-xs font-normal","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40");ne(dTe,"font-medium");function nDe({dirtyCount:e,saving:t,status:a,error:r,onSave:c,onDiscard:m,scope:d}){const h=e>0,f=t?"Saving…":h?`${e} unsaved change${e===1?"":"s"}`:a==="saved"?"Saved":a==="error"?r??"Save failed":"No unsaved changes";return v.jsxs("footer",{className:"shrink-0 space-y-2 border-t border-border bg-surface px-4 py-2 pb-[max(0.5rem,env(safe-area-inset-bottom))] md:pb-2",children:[d!==void 0&&v.jsx("div",{"data-save-scope":!0,children:d}),v.jsxs("div",{className:"flex items-center gap-2",children:[v.jsx("span",{role:"status",className:ne("min-w-0 flex-1 truncate text-[11px]",a==="error"&&!h?"text-danger":h?"text-amber-500":"text-foreground-subtle"),children:f}),v.jsx(pm,{variant:"outline",size:"md",disabled:!h||t,onClick:m,children:"Discard"}),v.jsx(pm,{variant:"primary",size:"md",disabled:!h||t,onClick:c,children:"Save"})]})]})}P.forwardRef(function({title:t,subtitle:a,headerActions:r,headerExtra:c,leading:m,saveBar:d,onEscape:h,children:f,className:k},x){const E=P.useId(),R=T=>{T.key!=="Escape"||h===void 0||(T.stopPropagation(),h())};return v.jsxs("section",{"aria-labelledby":E,onKeyDown:R,className:ne("flex min-h-0 flex-1 flex-col overflow-hidden bg-surface",k),children:[v.jsxs("header",{className:"shrink-0 space-y-2 border-b border-border px-4 py-2.5",children:[v.jsxs("div",{className:"flex flex-wrap items-start gap-x-3 gap-y-2",children:[m,v.jsxs("div",{className:"min-w-[9rem] flex-1",children:[v.jsx("h2",{id:E,ref:x,tabIndex:-1,title:t,className:"line-clamp-2 break-words text-sm font-semibold leading-snug text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary rounded",children:t}),a!==void 0&&v.jsx("div",{className:"mt-0.5 text-[11px] text-foreground-subtle",children:a})]}),r]}),c]}),v.jsx("div",{"data-inspector-body":!0,className:"min-h-0 flex-1 overflow-y-auto overscroll-contain px-4 py-3",children:f}),d!==void 0&&v.jsx(nDe,{...d})]})});Oi("camstack:player-overlays-state",null);var iDe=Oi("camstack:player-overlays-actions",null);function q8e(e){const t=P.useContext(iDe);P.useEffect(()=>{if(!(!t||!e))return t.setLayer(e),()=>t.removeLayer(e.id)},[t,e])}Oi("camstack:zone-editing",null);var aT=500,W1=800;function ku(e,t,a){try{const r=e.live;if(!r)return null;const c=r.onEvent;return!c||typeof c.subscribe!="function"?null:c.subscribe({category:t},{onData:a})}catch{return null}}function Fh(e,t){return e?.id===t}function rDe(e,t){const[a,r]=P.useState(null),[c,m]=P.useState(null),[d,h]=P.useState(null),[f,k]=P.useState("watching"),x=P.useRef(void 0),E=P.useRef(void 0),R=P.useRef(void 0),T=P.useRef(0);return P.useEffect(()=>{if(t===null)return;const N=ku(e,"detection.motion-analysis",j=>{const q=j;if(!Fh(q?.source,t))return;const B=q.data;!B?.regions||B.regions.length===0||(r({zones:B.regions.map(F=>({...F.bbox,intensity:F.intensity})),frameWidth:B.frameWidth,frameHeight:B.frameHeight}),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>r(null),aT))});return()=>{N?.unsubscribe(),x.current&&clearTimeout(x.current)}},[e,t]),P.useEffect(()=>{if(t===null)return;const N=ku(e,"detection.motion-zones-raw",j=>{const q=j;if(!Fh(q?.source,t))return;const B=q.data;B?.zones&&(m({boxes:B.zones.map(F=>({bbox:F.bbox,changeScore:F.changeScore})),frameWidth:B.frameSize?.width??0,frameHeight:B.frameSize?.height??0,motionScore:B.zones.length>0?B.zones.reduce((F,U)=>F+U.changeScore,0)/B.zones.length:0}),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>m(null),aT))});return()=>{N?.unsubscribe(),E.current&&clearTimeout(E.current)}},[e,t]),P.useEffect(()=>{if(T.current=0,t===null)return;const N=ku(e,"pipeline-analytics.frame-tracked",j=>{const q=j?.data;!q||q.deviceId!==t||q.detections?.length&&typeof q.detections[0]?.kind=="string"&&(T.current=Date.now(),h({detections:q.detections,frameWidth:q.frameWidth,frameHeight:q.frameHeight}),R.current&&clearTimeout(R.current),R.current=setTimeout(()=>h(null),W1))});return()=>{N?.unsubscribe(),R.current&&clearTimeout(R.current)}},[e,t]),P.useEffect(()=>{if(t===null)return;const N=ku(e,"detection.result",j=>{const q=j;if(!Fh(q?.source,t)||Date.now()-T.current<W1)return;const B=q.data?.frame;B?.detections?.length&&(h({detections:B.detections,frameWidth:B.width,frameHeight:B.height}),R.current&&clearTimeout(R.current),R.current=setTimeout(()=>h(null),W1))});return()=>{N?.unsubscribe(),R.current&&clearTimeout(R.current)}},[e,t]),P.useEffect(()=>{if(t===null)return;const N=ku(e,"detection.phase-transition",j=>{const q=j;Fh(q?.source,t)&&q.data?.to&&k(q.data.to)});return()=>{N?.unsubscribe()}},[e,t]),{motion:a,motionRaw:c,detection:d,phase:f}}P.lazy(()=>Hc(()=>import("./MaskShapeCanvas-DI4BY7W2-DwhST5rm.js"),[],import.meta.url).then(e=>({default:e.MaskShapeCanvas})));P.lazy(()=>Hc(()=>import("./MotionZonesSettings-CiYjd-yl-Djy2GKmM.js"),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.MotionZonesSettings})));P.lazy(()=>Hc(()=>import("./SceneMonitorEditor-J4Ix_0tu-4MX1nGnM.js"),__vite__mapDeps([3,1]),import.meta.url).then(e=>({default:e.SceneMonitorEditor})));P.lazy(()=>Hc(()=>import("./PrivacyMaskSettings-BmRdUrPp-DpHYAfGf.js"),__vite__mapDeps([2,1]),import.meta.url).then(e=>({default:e.PrivacyMaskSettings})));const q8=7;function oDe(e,t){return t!==void 0?e.toLocaleTimeString(t,{hour:"2-digit",minute:"2-digit"}):`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`}function nT(e){const t=new Date(e);return t.setHours(0,0,0,0),t.getTime()}function sDe(e,t){return Math.round((nT(t)-nT(e))/864e5)}function lDe(e){const t=(e??"en").toLowerCase();return t.startsWith("it")?"Ieri":t.startsWith("de")?"Gestern":t.startsWith("fr")?"Hier":t.startsWith("es")?"Ayer":"Yesterday"}function cDe(e,t,a){const r=new Date(e),c=oDe(r,a),m=sDe(e,t);if(m===0)return c;if(m===1)return`${lDe(a)} ${c}`;if(m>1&&m<=q8)return`${r.toLocaleDateString(a,{weekday:"short"})} ${c}`;const d=String(r.getDate()).padStart(2,"0"),h=String(r.getMonth()+1).padStart(2,"0");return`${d}/${h} ${c}`}const iT=6e4,rT=36e5,Z1=864e5,oT={en:{now:"now",m:"m",h:"h",d:"d"},it:{now:"ora",m:"m",h:"h",d:"g"}};function dDe(e,t,a){const r=t-e;if(r>=0&&r<q8*Z1){const c=oT[(a??"en").toLowerCase().slice(0,2)]??oT.en;return r<iT?c.now:r<rT?`${Math.floor(r/iT)}${c.m}`:r<Z1?`${Math.floor(r/rT)}${c.h}`:`${Math.floor(r/Z1)}${c.d}`}return new Date(e).toLocaleDateString(a,{day:"numeric",month:"short"})}const Px={unassignedFace:"unassigned face",reviewed:"reviewed",debug:"debug",train:"train",trained:"training complete",favourite:"favourite",active:"active",loadingMore:"Loading more events"},uDe={unassignedFace:"volto non assegnato",reviewed:"verificata",debug:"debug",train:"addestramento",trained:"addestramento completato",favourite:"preferita",active:"attiva",loadingMore:"Caricamento altri eventi"};function mDe(e){return e==="it"?uDe:Px}const pDe=Object.keys(Px),L8=$(n(),n());function B8(e,t){const a=mDe(t);if(e===null||typeof e!="object")return a;const r=e,c={...a};for(const m of pDe){const d=r[m];typeof d=="string"&&d.trim()!==""&&(c[m]=d)}return{unassignedFace:c.unassignedFace??a.unassignedFace,reviewed:c.reviewed??a.reviewed,debug:c.debug??a.debug,train:c.train??a.train,trained:c.trained??a.trained,favourite:c.favourite??a.favourite,active:c.active??a.active,loadingMore:c.loadingMore??a.loadingMore}}const hDe="/addon/pipeline-analytics/event-media",fDe="o",sT=64,gDe=320;function vDe(e){return e.replace(/\/+$/,"")}function yDe(e){const t=Math.round(e);return Number.isFinite(t)?Math.max(sT,Math.min(gDe,t)):sT}function Nx(e,t,a){const r=vDe(e),c=encodeURIComponent(t);return`${r}${hDe}/${fDe}/track/${c}?kind=thumbnailSmall&variant=thumb&size=${yDe(a)}`}const bDe="audio";function lT(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kDe(e){return SDe(F8(e))}function F8(e){const t=[];if(!Array.isArray(e))return t;for(const a of e){if(!lT(a))continue;const r=a.kinds;if(Array.isArray(r))for(const c of r)lT(c)&&t.push(c)}return t}function SDe(e){const t=new Map;for(const a of e){const r=a.kind;if(typeof r!="string"||r.length===0)continue;const c=a.parentKind;t.set(r,typeof c=="string"&&c.length>0?c:r)}return t}function $8(e,t){return t.get(e)??e}const cT="audio-",dT="audio";function Km(e){const t=e.toLowerCase();return t.startsWith(cT)?t:`${cT}${t}`}function wDe(e){return xDe(F8(e))}function xDe(e){const t=new Map;for(const a of e){const r=a.kind,c=a.iconId;typeof r!="string"||r.length===0||typeof c!="string"||c.length===0||t.set(r,c)}return t}function U8(e,t,a=!1){if(a){const c=t.get(e);if(c!==void 0)return c;if(e.toLowerCase()===dT)return dT;const m=Km(e);return t.get(m)??m}const r=e.toLowerCase();return t.get(e)??t.get(r)??r}function H8(e){const t=new Map;for(const[a,r]of Object.entries(e)){if(a.length===0||r.length===0)continue;t.set(a,r);const c=a.toLowerCase();t.has(c)||t.set(c,r)}return t}const Kg=new Map;function kf(e,t){return t.get(e)??t.get(e.toLowerCase())??e}function Q8(e,t){const a=Km(e);return t.get(a)??t.get(e)??e}const MDe={primary:"#f59e42",primaryForeground:"#0c0a09",background:"#0c0a09",backgroundElevated:"#1c1917",surface:"#1c1917",surfaceHover:"#292524",border:"#292524",borderSubtle:"#1c1917",foreground:"#fafaf9",foregroundMuted:"#a8a29e",foregroundSubtle:"#78716c",foregroundDisabled:"#57534e",success:"#4ade80",warning:"#fbbf24",danger:"#f87171",info:"#60a5fa",successFill:"#4ade80",successOn:"#0c0a09",warningFill:"#fbbf24",warningOn:"#0c0a09",dangerFill:"#f87171",dangerOn:"#0c0a09",infoFill:"#60a5fa",infoOn:"#0c0a09",primaryFill:"#f59e42",primaryOn:"#0c0a09",neutralFill:"#44403c",neutralOn:"#fafaf9",live:"#22d3ee",onPicture:"#ffffff",onMedia:"#fafaf9",mediaBlack:"#000000",presence:"#34d399",presenceOff:"#71717a",stationary:"#8b98a5",eventsBackground:"#09090b",eventsCard:"#18181b",eventsRaised:"#27272a",eventsText:"#fafafa",eventsMuted:"#a1a1aa",eventsChip:"#3f3f46"},CDe={primary:"#e67e22",primaryForeground:"#ffffff",background:"#fafaf9",backgroundElevated:"#ffffff",surface:"#f5f5f4",surfaceHover:"#e7e5e4",border:"#d6d3d1",borderSubtle:"#e7e5e4",foreground:"#1c1917",foregroundMuted:"#57534e",foregroundSubtle:"#78716c",foregroundDisabled:"#a8a29e",success:"#16a34a",warning:"#d97706",danger:"#dc2626",info:"#2563eb",successFill:"#15803d",successOn:"#ffffff",warningFill:"#b45309",warningOn:"#ffffff",dangerFill:"#dc2626",dangerOn:"#ffffff",infoFill:"#2563eb",infoOn:"#ffffff",primaryFill:"#c2410c",primaryOn:"#ffffff",neutralFill:"#57534e",neutralOn:"#ffffff",live:"#0891b2",onPicture:"#ffffff",onMedia:"#fafaf9",mediaBlack:"#000000",presence:"#34d399",presenceOff:"#71717a",stationary:"#8b98a5",eventsBackground:"#ffffff",eventsCard:"#f4f4f5",eventsRaised:"#e4e4e7",eventsText:"#18181b",eventsMuted:"#71717a",eventsChip:"#d4d4d8"};function V8(e,t){const a=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(e);if(!a)return e;const r=a[1].length===3?a[1].replace(/./g,f=>f+f):a[1],c=Math.min(1,Math.max(0,t)),m=parseInt(r.slice(0,2),16),d=parseInt(r.slice(2,4),16),h=parseInt(r.slice(4,6),16);return`rgba(${m}, ${d}, ${h}, ${Number(c.toFixed(3))})`}const ADe=.72;function IDe(e){return V8(e.background,ADe)}const Yt={dark:MDe,light:CDe},K8=HP(),EDe={ready:K8,origin:"pending",reason:null,serverUrl:null};let iw=EDe;const rw=new Set;function ow(e,t,a){return{ready:K8,origin:e,reason:t,serverUrl:a}}function RDe(e,t){return e.serverUrl===t?e:{...e,serverUrl:t}}function TDe(e){const t=JK.safeParse(e);return t.success?t.data.status==="unknown"?ow("unknown",t.data.reason,null):{ready:t.data,origin:"hub",reason:null,serverUrl:null}:ow("unknown","unreadable",null)}function _De(e){return e instanceof Error&&e.message.length>0&&e.message.length<=120?e.message:"unreachable"}function ag(e,t){return QP(e.ready.swatches,e.ready.fallbacks,t)}function PDe(e,t){return e.origin!==t.origin||e.reason!==t.reason||e.serverUrl!==t.serverUrl?!1:e.ready===t.ready?!0:e.origin!=="hub"&&t.origin!=="hub"}function ng(){return iw}function NDe(e){return rw.add(e),()=>{rw.delete(e)}}function Y1(e){if(!PDe(iw,e)){iw=e;for(const t of rw)t()}}function pd(){return P.useSyncExternalStore(NDe,ng,ng)}const uT={background:Yt.dark.eventsBackground,card:Yt.dark.eventsCard,cardHover:Yt.dark.eventsRaised,border:Yt.dark.eventsRaised,text:Yt.dark.eventsText,textMuted:Yt.dark.eventsMuted,skeleton:Yt.dark.eventsRaised,chip:Yt.dark.eventsChip,colorScheme:"dark"},mT={background:Yt.light.eventsBackground,card:Yt.light.eventsCard,cardHover:Yt.light.eventsRaised,border:Yt.light.eventsRaised,text:Yt.light.eventsText,textMuted:Yt.light.eventsMuted,skeleton:Yt.light.eventsRaised,chip:Yt.light.eventsChip,colorScheme:"light"};function Ox(e,t){return e==="light"?mT:e==="dark"||t?uT:mT}function sw(e,t=!1,a=ng()){return t?ag(a,"audio"):ag(a,e)}const ODe=/[_\-/.]+/g;function G8(e){return e.toLowerCase().replace(ODe," ").replace(/\s+/g," ").trim()}function DDe(e){if(e===void 0)return[];const t=e.trim().toLowerCase();if(t.length===0)return[];const a=G8(e);return a===t||a.length===0?[t]:[t,a]}const Gg=new Map,jDe=new Set(["plate-detection","plate-ocr","operator:plate-gallery"]),pT=new Set(["face-recognizer","face-embedding","operator:face-gallery"]),zDe=[],qDe=[];function X1(e,t){if(!Dx(e))return!1;const a=e.stepId;return typeof a=="string"&&t.has(a)}function ig(e){return e.source==="audio"}function Dx(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function es(e){return typeof e=="string"&&e.length>0?e:void 0}function J1(e){if(!Array.isArray(e))return[];const t=[];for(const a of e)typeof a=="string"&&a.length>0&&!t.includes(a)&&t.push(a);return t}function LDe(e){if(!Array.isArray(e))return[];const t=[];for(const a of e){const r=Dx(a)?es(a.label):void 0;r!==void 0&&!t.includes(r)&&t.push(r)}return t}function W8(e,t){if(!Dx(e))return null;const a=es(e.trackId),r=es(e.className);if(a===void 0||r===void 0||typeof e.deviceId!="number"||typeof e.firstSeen!="number"||typeof e.lastSeen!="number")return null;const c=es(e.label),m=es(e.subLabel),d=es(e.producingDeviceName),h=es(e.source),f=J1(e.classes);return{trackId:a,deviceId:e.deviceId,cameraName:t.get(e.deviceId)??`Camera ${e.deviceId}`,className:r,...c!==void 0?{label:c}:{},...m!==void 0?{subLabel:m}:{},...typeof e.importance=="number"?{importance:e.importance}:{},firstSeen:e.firstSeen,lastSeen:e.lastSeen,state:typeof e.state=="string"?e.state:"idle",active:e.active===!0,zonesVisited:J1(e.zonesVisited),zoneNames:J1(e.zoneNames),classes:f.includes(r)?f:[r,...f],audioLabels:LDe(e.audioLabels),bestEventId:es(e.bestEventId)??a,...d!==void 0?{producingDeviceName:d}:{},...h!==void 0?{source:h}:{},...e.hasEmbeddedFace===!0||X1(e.subLabelMeta,pT)?{hasAssignableFace:!0}:{},...e.hasEmbeddedFace===!0&&!X1(e.subLabelMeta,pT)?{hasUnassignedFace:!0}:{},...X1(e.subLabelMeta,jDe)?{hasPlate:!0}:{},...e.debug===!0?{debug:!0}:{},...e.markForTrain===!0?{markForTrain:!0}:{},...e.favourited===!0?{favourited:!0}:{},...e.retrainStatus==="none"||e.retrainStatus==="staging"||e.retrainStatus==="trained"?{retrainStatus:e.retrainStatus}:{}}}function hT(e,t){if(!Array.isArray(e))return[];const a=[];for(const r of e){const c=W8(r,t);c!==null&&a.push(c)}return a}function BDe(e,t){const a=new Set;for(const r of[e.className,...e.classes])r.length!==0&&(a.add(r),a.add($8(r,t)));if(e.audioLabels.length>0){a.add(bDe);for(const r of e.audioLabels)a.add(Km(r))}return a}function FDe(e,t,a=Gg){if(t.size===0)return!0;const r=BDe(e,a);for(const c of t)if(r.has(c))return!0;return!1}function $De(e,t=Gg){const a=new Set,r=c=>{for(const m of DDe(c))a.add(m)};for(const c of[e.className,...e.classes])r(c),c.length>0&&r($8(c,t));r(e.label),r(e.subLabel),r(e.cameraName),r(e.producingDeviceName);for(const c of e.audioLabels)r(c),r(Km(c));for(const c of e.zoneNames)r(c);for(const c of[e.label,e.subLabel]){if(c===void 0)continue;const m=t.get(c.trim().toLowerCase());m!==void 0&&r(m)}return a}function UDe(e,t,a=Gg){const r=t.trim().toLowerCase();if(r.length===0)return!0;const c=G8(t);for(const m of $De(e,a))if(m.includes(r)||c.length>0&&m.includes(c))return!0;return!1}function HDe(e,t){return!!(t.size===0||t.has("face")&&e.hasAssignableFace===!0||t.has("plate")&&e.hasPlate===!0)}function QDe(e,t={}){const a=t.debug===!0,r=t.train===!0,c=t.favourited===!0;if(!a&&!r&&!c)return!0;const m=t.reviewedTrackIds?.includes(e.trackId)===!0;return!!(a&&e.debug===!0&&!m||r&&e.markForTrain===!0||c&&e.favourited===!0)}function VDe(e,t){return t.size===0?!0:!t.has(e.source??"pipeline")}function fT(e,t,a,r=Gg,c=zDe,m={},d=qDe){const h=new Set(t),f=new Set(c),k=new Set(d);return e.filter(x=>VDe(x,k)&&FDe(x,h,r)&&HDe(x,f)&&UDe(x,a,r)&&QDe(x,m))}function Z8(e,t=Kg){return e.producingDeviceName!==void 0?{text:kf(e.className,t),tier:"device",fullText:e.producingDeviceName}:e.subLabel!==void 0?{text:e.subLabel,tier:"identity"}:e.label!==void 0&&e.label!==e.className?{text:kf(e.label,t),tier:"kind"}:{text:kf(e.className,t),tier:"class"}}function KDe(e,t,a,r=Kg){if(t)return"";const c=[a];for(const m of e.audioLabels){if(m===e.className||m===e.label)continue;const d=Q8(m,r);c.includes(d)||c.push(d)}return c.join(" · ")}function gT(e,t){let a=!1;const r=e.map(c=>{const m=t.get(c.deviceId);return m===void 0||m===c.cameraName?c:(a=!0,{...c,cameraName:m})});return a?r:e}function vT(e,t){if(Object.keys(t).length===0)return e;let r=!1;const c=e.map(m=>{const d=t[m.trackId];if(d===void 0)return m;const h=WDe(m,d);return h!==m&&(r=!0),h});return r?c:e}function GDe(e){const{debug:t,markForTrain:a,favourited:r,...c}=e;return c}function WDe(e,t){const a=t.debug===!0?!0:t.debug===!1?void 0:e.debug,r=t.markForTrain===!0?!0:t.markForTrain===!1?void 0:e.markForTrain,c=t.favourited===!0?!0:t.favourited===!1?void 0:e.favourited;return a===e.debug&&r===e.markForTrain&&c===e.favourited?e:{...GDe(e),...a===!0?{debug:!0}:{},...r===!0?{markForTrain:!0}:{},...c===!0?{favourited:!0}:{}}}function ZDe(e){const t=e.filter(a=>a.isCamera===!0).map(a=>a.id);return t.length>0?t:e.map(a=>a.id)}const lw=11,yT=9,ek=3,YDe=8,XDe=12,Y8=24,JDe=.58,e5e=.85;function t5e(e,t){return[...e].length*t*JDe}function a5e(e){return Math.max(Y8,e-YDe-XDe)}function bT(e,t,a){const r=a5e(t),c=a.maxLines===1?r:r*a.maxLines*e5e;return t5e(e,a.fontSizePx)<=c}function n5e(e,t){for(let a=1;a<=ek;a+=1){const r={fontSizePx:lw,maxLines:a};if(bT(e,t,r))return r}for(let a=lw-1;a>=yT;a-=1){const r={fontSizePx:a,maxLines:ek};if(bT(e,t,r))return r}return{fontSizePx:yT,maxLines:ek}}const i5e=12,tk=9,r5e=.56;function o5e(e,t){const a=Math.max(Y8,t-4),r=Math.min(i5e,Math.max(tk,Math.round(t/8)));for(let c=r;c>=tk;c-=1)if([...e].length*c*r5e<=a)return{fontSizePx:c,maxLines:1};return{fontSizePx:tk,maxLines:2}}const s5e="/viewer/camstack/embed/index.html",l5e=["off","icon","label"],c5e=I(l5e),jx=o({tileLabelMode:c5e.optional(),tileDetailCamera:w().optional(),tileDetailZone:w().optional()});function d5e(e,t){return{tileLabelMode:t.tileLabelMode??(e.label?"label":"off"),tileDetailCamera:t.tileDetailCamera??e.camera,tileDetailZone:t.tileDetailZone??e.badges}}const u5e=I(["reel","gallery"]),m5e=I(["small","medium","large"]);I(["time","importance"]);const p5e=I(["text","semantic"]),h5e=["face","plate"],zx=I(h5e),f5e=["pipeline","sensor","audio"],X8=I(f5e),g5e=I(["auto","dark","light"]),v5e=qe([_("auto"),i().int().min(1).max(12)]),y5e=o({label:w(),sublabel:w(),camera:w(),time:w(),badges:w(),importance:w()});o({view:u5e,rows:i().int().min(1).max(6).optional(),columns:v5e.optional(),thumb:m5e,deviceIds:y(i().int().nonnegative()),classes:y(n()).optional(),attrs:y(zx).optional(),search:n().optional(),searchMode:p5e.optional(),semanticLimit:i().int().min(1).max(200).optional(),semanticMinScore:i().min(0).max(1).optional(),sinceMs:i().int().nonnegative().optional(),untilMs:i().int().nonnegative().optional(),deviceNames:$(n(),n()).optional(),fields:y5e,...jx.shape,pageSize:i().int().min(1).max(500).optional(),maxRows:i().int().min(1).max(5e3).optional(),refreshMs:i().int().min(0).max(6e5).optional(),maxAgeMs:i().int().min(6e4).optional(),theme:g5e});const J8=4,b5e=768,k5e=212;function kT(e){return{edge:e,cardHeight:e}}function S5e(e){const{viewportWidth:t,viewportHeight:a,presetEdge:r,gap:c,padX:m}=e,d=Math.max(1,Math.floor(e.rows));if(t<b5e||a<=0)return kT(r);const h=t-m-c,f=a-J8*2,k=Math.floor((f-(d-1)*c)/d),x=Math.max(r,Math.min(k,k5e));if(h<=x)return kT(r);const E=Math.max(1,Math.ceil((h+c)/(x+c))),R=Math.floor((h-(E-1)*c)/E*100)/100;return{edge:R,cardHeight:R}}function qx(e){return e.startsWith("/")&&!e.startsWith("//")}function w5e(e){return e!==void 0&&e.length>0?{Authorization:`Bearer ${e}`}:{}}function x5e(e,t,a){if(!t.endsWith(a))return e;const r=t.slice(0,t.length-a.length);return r.length>0?r:e}function e7(e,t){e.token===void 0&&(qx(e.serverUrl)||t.addIssue({code:"custom",path:["token"],message:"token is required unless serverUrl is a same-origin path served through an authenticating relay"}))}const M5e=60,C5e=5e3,A5e=600,I5e=720*60*60*1e3,t7=I(["reel","gallery"]),a7=I(["small","medium","large"]),n7=I(["auto","dark","light"]),Lx=["en","it"];function i7(e){const t=(e??"").toLowerCase().split(/[-_]/)[0];return Lx.find(a=>a===t)}function Bx(e,t){return e??i7(t)??"en"}const E5e=o({label:w(),sublabel:w(),camera:w(),time:w(),badges:w(),importance:w().default(!1)}),R5e=o({label:w().optional(),sublabel:w().optional(),camera:w().optional(),time:w().optional(),badges:w().optional(),importance:w().optional()}),r7={label:!0,sublabel:!1,camera:!0,time:!0,badges:!0,importance:!1},o7=I(["text","semantic"]),s7=qe([_("auto"),i().int().min(1).max(12)]);function T5e(e){return e.view==="reel"?Math.min(e.maxRows,A5e):e.maxRows}const _5e=0,P5e=o({serverUrl:n().min(1),token:n().min(1).optional(),view:t7.default("reel"),rows:i().int().min(1).max(6).default(1),columns:s7.default("auto"),thumbSize:a7.default("medium"),fields:E5e.default(r7),...jx.shape,deviceIds:y(i().int().nonnegative()).default([]),classes:y(n()).default([]),attrs:y(zx).catch([]).default([]),deviceNames:$(n(),n()).default({}),kindLabels:$(n(),n()).default({}),labels:L8.default({}),strings:o({empty:n().optional(),emptyFiltered:n().optional(),error:n().optional(),retry:n().optional(),end:n().optional(),loadOlder:n().optional()}).default({}),search:n().default(""),searchMode:o7.default("text"),semanticLimit:i().int().min(1).max(200).default(50),semanticMinScore:i().min(0).max(1).optional(),filterDebug:w().default(!1),filterTrain:w().default(!1),filterFavourited:w().default(!1),showStationary:w().default(!1),excludeSources:y(X8).default([]),reviewedTrackIds:y(n()).default([]),showAdminFlags:w().default(!1),sinceMs:i().int().nonnegative().optional(),untilMs:i().int().nonnegative().optional(),pageSize:i().int().min(1).max(500).default(M5e),maxRows:i().int().min(1).max(5e3).default(C5e),refreshMs:i().int().min(0).max(6e5).default(_5e),maxAgeMs:i().int().min(6e4).default(I5e),theme:n7.default("auto"),locale:I(Lx).optional(),nativePullToRefresh:w().default(!1)}).superRefine(e7),l7=o({view:t7.optional(),rows:i().int().min(1).max(6).optional(),columns:s7.optional(),thumbSize:a7.optional(),fields:R5e.optional(),...jx.shape,deviceIds:y(i().int().nonnegative()).optional(),classes:y(n()).optional(),attrs:y(zx).optional(),deviceNames:$(n(),n()).optional(),kindLabels:$(n(),n()).optional(),labels:L8.optional(),strings:o({empty:n().optional(),emptyFiltered:n().optional(),error:n().optional(),retry:n().optional(),end:n().optional(),loadOlder:n().optional()}).optional(),search:n().optional(),searchMode:o7.optional(),semanticLimit:i().int().min(1).max(200).optional(),semanticMinScore:i().min(0).max(1).nullable().optional(),filterDebug:w().optional(),filterTrain:w().optional(),filterFavourited:w().optional(),showStationary:w().optional(),excludeSources:y(X8).optional(),reviewedTrackIds:y(n()).optional(),showAdminFlags:w().optional(),sinceMs:i().int().nonnegative().nullable().optional(),untilMs:i().int().nonnegative().nullable().optional(),pageSize:i().int().min(1).max(500).optional(),maxRows:i().int().min(1).max(5e3).optional(),refreshMs:i().int().min(0).max(6e5).optional(),maxAgeMs:i().int().min(6e4).optional(),theme:n7.optional(),locale:I(Lx).optional(),nativePullToRefresh:w().optional()});function cw(e){return e==="small"?60:e==="large"?106:80}function N5e(e,t=1){const a=Number.isFinite(t)&&t>0?t:1,r=Math.round(e*a);return Math.max(O5e,Math.min(D5e,r))}const O5e=64,D5e=320;function j5e(e){return cw(e)}function Fx(e){if(e==null)return{ok:!1,error:"config is required"};const t=P5e.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(a=>`${a.path.join(".")||"(root)"}: ${a.message}`).join("; ")}}function dw(e,t){const a=t.fields!==void 0?{...e.fields,...t.fields}:e.fields,{sinceMs:r,untilMs:c,semanticMinScore:m,...d}=t,{sinceMs:h,untilMs:f,semanticMinScore:k,...x}=e,E=ak(r,h),R=ak(c,f),T=ak(m,k);return{...x,...d,fields:a,...E!==void 0?{sinceMs:E}:{},...R!==void 0?{untilMs:R}:{},...T!==void 0?{semanticMinScore:T}:{}}}function ak(e,t){if(e!==null)return e??t}function z5e(e,t,a){const r=a[String(e)];return r!==void 0&&r.trim().length>0?r:t}const q5e={empty:"No events",emptyFiltered:"No events match this filter",error:"Couldn't load events",retry:"Retry",end:"·",loadOlder:"Load older events"};function mc(e,t){const a=e.strings[t];return a!==void 0&&a.trim().length>0?a:q5e[t]}const L5e=1e4;function c7(){try{return window.parent!==window}catch{return!0}}let uw=null;function d7(e){uw=e}function B5e(e){if(uw===null||typeof e!="object"||e===null)return e;const t=e;if(t.type!=="log")return e;const a=typeof t.data=="object"&&t.data!==null?t.data:{};return{...t,data:{deviceId:uw,...a}}}function qt(e){const t=B5e(e),a=window.ReactNativeWebView;if(a){a.postMessage(JSON.stringify(t));return}c7()&&window.parent.postMessage(t,"*")}function Gm(e){const t=a=>{const r=a.data;if(typeof r!="object"||r===null)return;const c=r;c.type!=="embed-command"||typeof c.command!="object"||c.command===null||e(c.command)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}function F5e(e,t,a,r,c){const m=t();if(m!=null)return Promise.resolve(a(m));if(c?.urlFirst===!0){const d=r!==void 0?r():null;if(d!==null)return Promise.resolve(d)}if(!c7()){const d=r!==void 0?r():null;return d!==null?Promise.resolve(d):Promise.resolve({ok:!1,error:`config global for mode "${e}" is not set`})}return new Promise(d=>{let h;const f=k=>{const x=k.data;if(typeof x!="object"||x===null)return;const E=x;E.type==="embed-config"&&(clearTimeout(h),window.removeEventListener("message",f),d(a(E.config)))};window.addEventListener("message",f),h=setTimeout(()=>{window.removeEventListener("message",f),d({ok:!1,error:"config handshake timed out"})},L5e),window.parent.postMessage({type:"embed-ready",mode:e},"*")})}function Wm(e,t,a,r,c){const[m,d]=P.useState(null),h=P.useRef(t);h.current=t;const f=P.useRef(a);f.current=a;const k=P.useRef(r);k.current=r;const x=c?.urlFirst===!0;return P.useEffect(()=>{let E=!0;return F5e(e,()=>h.current(),R=>f.current(R),()=>k.current!==void 0?k.current():null,{urlFirst:x}).then(R=>{E&&d(R)}),()=>{E=!1}},[e,x]),m}const tr=1,$5e=["window","semantic-search","macro-classes","device-names","kind-labels","heartbeat","track-list","attr-filters","flag-filters","debug-status","native-pull-refresh","track-list-delta"];function U5e(e){return{v:tr,type:"ready",view:e,features:[...$5e]}}function H5e(e){return{v:tr,type:"error",message:e}}function Sf(e,t){return t!==void 0?{v:tr,type:"state",state:e,message:t}:{v:tr,type:"state",state:e}}function Q5e(e){return{v:tr,type:"trackClick",...e}}function V5e(e,t){return{v:tr,type:"trackList",tracks:e,seq:t}}function K5e(e){return{v:tr,type:"trackListDelta",...e}}function ST(e,t,a,r="feed"){return{v:tr,type:"countChanged",loaded:e,shown:t,hasMore:a,mode:r}}function G5e(){return{v:tr,type:"heartbeat"}}function W5e(e){return{v:tr,type:"scroll",atTop:e}}function Z5e(){return{v:tr,type:"refreshed"}}function Ei(e){qt(e)}function qc(e,t,a="feed"){qt({type:"log",scope:a,msg:e,...t!==void 0?{data:t}:{}})}const Y5e=I(["full","delta"]),X5e=o({debug:w().optional(),markForTrain:w().optional(),favourited:w().optional()}),J5e=$(n(),X5e);function Su(e){if(typeof e!="object"||e===null)return null;const t=e,a=t.type;if(a==="refresh"||a==="reload"||a==="loadMore"||a==="scrollToTop"||a==="ping")return{type:a};if(a==="setWindow"){const c=eje.safeParse(t);return c.success?{type:"setWindow",...c.data.sinceMs!==void 0?{sinceMs:c.data.sinceMs}:{},...c.data.untilMs!==void 0?{untilMs:c.data.untilMs}:{}}:null}if(a==="setTrackListMode"){const c=Y5e.safeParse(t.mode);return c.success?{type:"setTrackListMode",mode:c.data}:null}if(a==="setTrackFlagPatches"){const c=J5e.safeParse(t.patches);return c.success?{type:"setTrackFlagPatches",patches:c.data}:null}if(a!=="setConfig")return null;const r=l7.safeParse(t.patch);return r.success?{type:"setConfig",patch:r.data}:null}const eje=o({sinceMs:i().int().nonnegative().nullable().optional(),untilMs:i().int().nonnegative().nullable().optional()});function tje(e){return{...e.sinceMs!==void 0?{sinceMs:e.sinceMs}:{},...e.untilMs!==void 0?{untilMs:e.untilMs}:{}}}const aje={blockedMs:0,maxLagMs:0,samples:0};function nje(e,t,a){if(a<=t)return aje;let r=0,c=0,m=0;for(const d of e){const h=d.at-d.lagMs,f=Math.min(d.at,a)-Math.max(h,t);f<=0||(r+=f,c=Math.max(c,d.lagMs),m+=1)}return{blockedMs:Math.round(r),maxLagMs:Math.round(c),samples:m}}function mw(e,t){const a=Math.min(Math.round(e),t.blockedMs);return{ms:Math.round(e),blockedMs:a,netMs:Math.max(0,Math.round(e)-a),maxLagMs:t.maxLagMs,lagSamples:t.samples}}const ije=250,wT=600,rje=8;let kc=[],xT=null;function oje(e){e.lagMs<rje||(kc.push(e),kc.length>wT&&(kc=kc.slice(kc.length-wT)))}function pw(e,t){return nje(kc,e,t)}function sje(e=ije,t=()=>performance.now(),a=(r,c)=>{const m=setInterval(r,c);return()=>clearInterval(m)}){if(xT!==null)return;let r=t()+e;xT={stop:a(()=>{const m=t();oje({at:m,lagMs:Math.max(0,m-r)}),r=m+e},e)}}function lje(e){return e.responseEnd<=0||e.requestStart===0&&e.responseStart===0?null:{totalMs:Math.round(e.responseEnd-e.startTime),queuedMs:Math.round(Math.max(0,e.requestStart-e.startTime)),ttfbMs:Math.round(Math.max(0,e.responseStart-e.requestStart)),transferSize:Math.round(e.transferSize??0)}}function cje(e,t){let a=null;for(const r of e)r.startTime+1<t||(a===null||r.startTime<a.startTime)&&(a=r);return a}function dje(){if(typeof performance>"u")return null;const e=performance;if(typeof e!="object"||e===null||!("getEntriesByName"in e))return null;const t=e.getEntriesByName;return typeof t!="function"?null:{getEntriesByName:(a,r)=>t.call(performance,a,r)}}function uje(e,t,a=dje()){if(a===null)return null;try{const r=cje(a.getEntriesByName(e,"resource"),t);return r===null?null:lje(r)}catch{return null}}const mje=250,ro=new Map,nk=new Map,pje=6,hje=1e4,fje=5e3,ik=[250,750];let rk=5;const MT=32;function gje(e){try{const t=new URL(e),a=t.pathname.lastIndexOf("/"),r=a>=0?`${t.pathname.slice(0,a)}/<id>`:t.pathname;return{origin:t.origin,path:r,query:t.search}}catch{const t=e.slice(0,MT);return{origin:"(unparseable)",path:e.length>MT?`${t}…`:t,query:""}}}function vje(e){return e instanceof Error?{errorName:e.name,errorMessage:e.message}:{errorName:"unknown",errorMessage:String(e)}}let rg=0,u7=[];async function yje(){if(rg<pje){rg+=1;return}await new Promise(e=>{u7.push(e)})}function bje(){const e=u7.shift();if(e!==void 0){e();return}rg=Math.max(0,rg-1)}function kje(e,t){for(ro.set(e,t);ro.size>mje;){const a=ro.keys().next();if(a.done===!0)break;const r=ro.get(a.value);ro.delete(a.value),r!==void 0&&URL.revokeObjectURL(r)}}async function m7(e,t){const a=ro.get(e);if(a!==void 0)return ro.delete(e),ro.set(e,a),{status:"ready",src:a};const r=nk.get(e);if(r!==void 0)return r;const c=(async()=>{const m=performance.now(),d=gje(e);let h={lastStatus:null,errorName:null,errorMessage:null},f=0;try{for(let k=0;k<=ik.length;k+=1){const x=performance.now();await yje(),f+=performance.now()-x;const E=performance.now(),R=new AbortController,T=setTimeout(()=>R.abort(),hje);try{const j=await fetch(e,{headers:w5e(t),signal:R.signal});if(j.ok){const q=Math.round(performance.now()-E),B=await j.blob(),F=Math.round(performance.now()-m),U=Math.round(performance.now()-E),H=URL.createObjectURL(B);if(kje(e,H),rk>0||F>=500){rk=Math.max(0,rk-1);const Q=uje(e,E),te=mw(performance.now()-E,pw(E,performance.now()));qc("thumbnail ready",{ms:F,queuedMs:Math.round(f),headersMs:q,blobMs:U-q,blockedMs:te.blockedMs,maxLagMs:te.maxLagMs,netTotalMs:Q?.totalMs??null,netQueuedMs:Q?.queuedMs??null,netTtfbMs:Q?.ttfbMs??null,bytes:B.size,attempt:k+1,serverTiming:j.headers?.get("server-timing")??null},"media")}return{status:"ready",src:H}}if(j.status===401||j.status===403||j.status===404)return qc("thumbnail missing",{ms:Math.round(performance.now()-m),queuedMs:Math.round(f),status:j.status,attempt:k+1,...d},"media"),{status:"missing"};h={lastStatus:j.status,errorName:null,errorMessage:null}}catch(j){h={lastStatus:null,...vje(j)}}finally{clearTimeout(T),bje()}const N=ik[k];N!==void 0&&await new Promise(j=>setTimeout(j,N))}return qc("thumbnail transient failure",{ms:Math.round(performance.now()-m),queuedMs:Math.round(f),attempts:ik.length+1,...h,...d},"media"),{status:"transient-failure"}}finally{nk.delete(e)}})();return nk.set(e,c),c}async function Sje(e,t){const a=await m7(e,t);return a.status==="ready"?a.src:null}function p7(e,t){const[a,r]=P.useState({status:"loading"}),[c,m]=P.useState(0);return P.useEffect(()=>{if(e===null){r({status:"loading"});return}const d=ro.get(e);if(d!==void 0){r({status:"ready",src:d});return}let h=!0,f;return r({status:"loading"}),m7(e,t).then(k=>{if(h){if(k.status==="ready"){r({status:"ready",src:k.src});return}if(k.status==="missing"){r({status:"failed"});return}f=setTimeout(()=>m(x=>x+1),fje)}}),()=>{h=!1,f!==void 0&&clearTimeout(f)}},[e,t,c]),a}function wje(e){const t=e?.clientHeight??0;return t>0?t:600}function xje(e,t){const{root:a,disabled:r}=t,[c,m]=P.useState(r===!0),d=P.useRef(c);return d.current=c,P.useEffect(()=>{if(d.current)return;if(r===!0){m(!0);return}const h=e.current;if(!h||typeof IntersectionObserver!="function"){m(!0);return}const f=new IntersectionObserver(k=>{k.some(x=>x.isIntersecting)&&(m(!0),f.disconnect())},{root:a,rootMargin:`${wje(a)}px`});return f.observe(h),()=>f.disconnect()},[e,a,r]),c}const Mje={display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:14,height:14,padding:"0 3px",borderRadius:4,fontSize:9,fontWeight:700,lineHeight:"14px",letterSpacing:.2},Cje=P.memo(function({row:t,serverUrl:a,token:r,thumbPx:c,width:m,heroPx:d,fields:h,display:f,palette:k,nowMs:x,locale:E,variant:R,iconId:T,kindLabels:N=Kg,labels:j=Px,scrollRoot:q,eagerImages:B,showAdminFlags:F,onClick:U}){const H=pd(),Q=Yt[k.colorScheme],te=IDe({background:k.background}),K=k.text,W=Yt.light.primaryForeground,oe={...Mje,background:te,color:K},he=P.useRef(null),we=xje(he,{root:q,...B===!0?{disabled:!0}:{}})?Nx(a,t.trackId,c):null,Ee=p7(we,r),Ie=sw(t.className,ig(t),H),Me=R==="reel",Y=d,de=Z8(t,N),Re=f.tileLabelMode!=="off",Qe=f.tileLabelMode==="label"&&de.tier!=="class",re=Re&&!Qe,V=n5e(de.text,d),ie=f.tileLabelMode==="label",fe=KDe(t,ie,de.text,N),be=jS(T),ee=v.jsxs("div",{style:{position:"relative",width:Me?d:"100%",height:Me?d:void 0,aspectRatio:Me?void 0:"1 / 1",borderRadius:10,overflow:"hidden",background:k.skeleton,border:`1px solid ${k.border}`,boxSizing:"border-box",flex:"0 0 auto"},children:[v.jsx("div",{className:Ee.status==="loading"?"events-skeleton":void 0,"data-testid":"card-image-backing",style:{position:"absolute",inset:0,background:Ee.status==="failed"?`${Ie}22`:k.skeleton,boxShadow:`inset 0 0 0 1px ${k.border}`}}),Ee.status==="ready"?v.jsx("img",{src:Ee.src,alt:"",draggable:!1,style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover",display:"block"}}):null,Re&&v.jsxs("div",{style:{position:"absolute",left:4,right:4,bottom:4,display:"flex",flexWrap:Me?"nowrap":"wrap",gap:3,alignItems:"center",pointerEvents:"none"},children:[re&&v.jsx("span",{"data-testid":"card-class-glyph",title:kf(t.className,N),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",background:`${Ie}E6`,color:W,borderRadius:4,padding:"2px 4px",flex:"0 0 auto"},children:v.jsx(be,{size:13,color:W})}),Qe&&v.jsx("span",{"data-testid":"card-title",title:de.fullText??de.text,style:{background:te,color:K,fontSize:Me?lw:V.fontSizePx,fontWeight:700,lineHeight:1.35,padding:"2px 6px",borderRadius:4,overflow:"hidden",minWidth:0,...Me?{textOverflow:"ellipsis",whiteSpace:"nowrap"}:{display:"-webkit-box",WebkitLineClamp:V.maxLines,WebkitBoxOrient:"vertical",whiteSpace:"normal",overflowWrap:"anywhere"}},children:de.text}),!Me&&Re&&t.audioLabels.filter(wt=>wt!==t.className&&wt!==t.label).map(wt=>{const sa=Km(wt),nt=jS(sa);return v.jsx("span",{title:Q8(wt,N),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",background:`${sw("audio",!0,H)}E6`,color:W,borderRadius:4,padding:"2px 4px",flex:"0 0 auto"},children:v.jsx(nt,{size:13,color:W})},`audio-${wt}`)})]}),(F===!0&&(t.debug===!0||t.reviewed===!0||t.markForTrain===!0||t.retrainStatus==="trained")||t.favourited===!0)&&v.jsxs("span",{"data-testid":"card-flags",style:{position:"absolute",top:4,left:4,display:"inline-flex",gap:2,zIndex:2},children:[F===!0&&t.reviewed===!0&&v.jsx("span",{title:j.reviewed,style:oe,children:"✓"}),F===!0&&t.debug===!0&&t.reviewed!==!0&&v.jsx("span",{title:j.debug,style:oe,children:"D"}),F===!0&&t.markForTrain===!0&&v.jsx("span",{title:j.train,style:oe,children:"T"}),F===!0&&t.retrainStatus==="trained"&&t.markForTrain!==!0&&v.jsx("span",{title:j.trained,"data-testid":"retrain-status-trained",style:oe,children:"✓T"}),t.favourited===!0&&v.jsx("span",{title:j.favourite,style:{...oe,color:Q.warning},children:"★"})]}),h.badges&&t.active&&v.jsx("span",{title:j.active,style:{position:"absolute",top:4,right:4,width:8,height:8,borderRadius:999,background:Q.success,boxShadow:`0 0 0 2px ${V8(k.background,.35)}`}}),h.time?v.jsx("span",{"data-testid":"card-time",style:{position:"absolute",top:4,right:h.badges&&t.active?16:4,background:te,color:K,fontSize:9,fontWeight:700,fontVariantNumeric:"tabular-nums",padding:"1px 5px",borderRadius:5,zIndex:2},children:dDe(t.lastSeen,x,E)}):null]});if(Me)return v.jsx("button",{ref:he,type:"button",onClick:()=>U(t),"data-track-id":t.trackId,"data-device-id":t.deviceId,style:{width:m,height:Y,minWidth:m,minHeight:Y,display:"flex",flexDirection:"column",alignItems:"center",padding:0,border:"none",background:"transparent",cursor:"pointer",font:"inherit",color:k.text,boxSizing:"border-box",contain:"layout paint",overflow:"hidden"},children:ee});const Se=t.cameraName,_e=f.tileDetailCamera,Be=f.tileDetailZone&&t.zonesVisited.length>0,Ge=h.sublabel&&fe.length>0,Ft=_e||Be||Ge,Ot=o5e(Se,d);return v.jsxs("button",{ref:he,type:"button",onClick:()=>U(t),"data-track-id":t.trackId,"data-device-id":t.deviceId,style:{width:m,display:"flex",flexDirection:"column",gap:2,padding:0,border:"none",background:"transparent",cursor:"pointer",textAlign:"left",font:"inherit",color:k.text,boxSizing:"border-box"},children:[ee,Ft&&v.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:1,minWidth:0,paddingBottom:1},children:[Ge&&v.jsx("span",{style:{fontSize:Math.max(9,Ot.fontSizePx-1),color:k.textMuted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:fe}),_e&&v.jsx("span",{"data-testid":"card-camera",title:Se,style:{fontSize:Ot.fontSizePx,fontWeight:600,lineHeight:1.2,display:"-webkit-box",WebkitLineClamp:Ot.maxLines,WebkitBoxOrient:"vertical",overflow:"hidden",overflowWrap:"anywhere"},children:Se}),Be&&v.jsx("span",{"data-testid":"card-zone",style:{fontSize:Math.max(9,Ot.fontSizePx-2),color:k.textMuted,background:k.chip,borderRadius:5,padding:"1px 5px",alignSelf:"flex-start",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"100%"},children:t.zonesVisited.join(" · ")})]})]})}),h7=new Map,CT=new Set;function AT(e,t){const a=`${e}|${t??""}`;CT.has(a)||(CT.add(a),qt({type:"log",scope:"palette",msg:"display palette unknown; painting the bundled preset",data:{reason:t,serverUrl:e}}))}async function IT(e){const t=e.serverUrl;try{const a=await e.trpcClient.displayPalette.getPalette.query(),r=RDe(TDe(a),t);return r.origin==="unknown"?AT(t,r.reason):h7.set(t,r),r}catch(a){const r=_De(a);return AT(t,r),ow("unknown",r,t)}}function Aje(e){P.useEffect(()=>{const t=h7.get(e.serverUrl);t!==void 0&&Y1(t);let a=!1;return IT(e).then(r=>{a||Y1(r)}),()=>{a=!0}},[e]),P.useEffect(()=>{let t=null;return e.subscribeConnectionEvents(a=>{const r=t;t=a,r!==null&&r!=="connected"&&a==="connected"&&IT(e).then(c=>Y1(c))})},[e])}function Wg({system:e}){Aje(e);const t=pd();return t.origin!=="unknown"||t.reason===null?null:v.jsx("p",{role:"status","data-testid":"palette-unknown",style:{margin:0,padding:"6px 10px",fontSize:12,color:Yt.dark.warning,background:Yt.dark.background},children:`Palette unreadable (${t.reason}). Using the CamStack preset.`})}function Ije(e){return{listRecentTracks:t=>e.trpcClient.pipelineAnalytics.listRecentTracks.query(t),listDevices:()=>e.trpcClient.deviceManager.listAll.query({isCamera:!0,projection:"slim"}),searchObjectEvents:t=>e.trpcClient.pipelineAnalytics.searchObjectEvents.query(t),listEventKinds:t=>e.trpcClient.pipelineAnalytics.listEventKindsBatch.query({deviceIds:t})}}const ET=200,Eje=45;function hw(e){return{trackId:e.trackId,deviceId:e.deviceId,bestEventId:e.bestEventId,className:e.className,firstSeen:e.firstSeen,lastSeen:e.lastSeen}}function fw(e,t){if(e.length!==t.length)return!1;for(let a=0;a<e.length;a+=1)if(e[a]!==t[a])return!1;return!0}function Rje(e,t){const a=t.map(T=>T.trackId);if(fw(e,a))return{kind:"unchanged"};if(e.length===0)return{kind:"reset"};const r=new Set(e);let c=a.length-1,m=e.length-1,d=a.length;for(;c>=0&&!r.has(a[c]);)d=c,c-=1;const h=[];for(;c>=0&&m>=0;){if(a[c]===e[m]){c-=1,m-=1;continue}h.push(e[m]),m-=1}const f=c+1;for(;m>=0;)h.push(e[m]),m-=1;const k=new Set(h),x=[...a.slice(0,f),...e.filter(T=>!k.has(T)),...a.slice(d)];if(!fw(x,a))return{kind:"reset"};const E=f+(a.length-d);return ET*E+Eje*h.length>=ET*a.length?{kind:"reset"}:{kind:"delta",prepend:t.slice(0,f).map(hw),append:d===a.length?[]:t.slice(d).map(hw),removeIds:h}}const Tje={seq:0,sentIds:null,mode:"full"};function wf(e,t,a){const r=e.seq+1;return{state:{seq:r,sentIds:a,mode:e.mode},message:V5e(t.map(hw),r)}}function _je(e,t){const a=t.map(m=>m.trackId);if(e.sentIds===null)return wf(e,t,a);if(e.mode==="full")return fw(e.sentIds,a)?{state:e,message:null}:wf(e,t,a);const r=Rje(e.sentIds,t);if(r.kind==="unchanged")return{state:e,message:null};if(r.kind==="reset")return wf(e,t,a);const c=e.seq+1;return{state:{seq:c,sentIds:a,mode:e.mode},message:K5e({seq:c,baseSeq:e.seq,prepend:r.prepend,append:r.append,removeIds:r.removeIds,count:a.length})}}function Pje(e,t,a){const r=a.map(c=>c.trackId);return wf({...e,mode:t},a,r)}function Nje(e){let t=Tje,a=[];const r=c=>{t=c.state,c.message!==null&&e(c.message)};return{report:c=>{a=c,r(_je(t,c))},setMode:c=>{r(Pje(t,c,a))}}}const Oje=2e3,Dje=1e3;function RT(e,t){const a=Math.max(1,Math.floor(e)),r=Math.max(1,Math.floor(t)),c=Math.max(1,Math.floor(Oje/r));return Math.min(a,Dje,c)}function f7(e,t){return e.lastSeen!==t.lastSeen?t.lastSeen-e.lastSeen:e.trackId===t.trackId?0:e.trackId<t.trackId?1:-1}const Tu={rows:[],cursor:null,exhausted:!1,rebuild:null},jje=8;function gw(e,t){const a=new Map;for(const r of e)a.set(r.trackId,r);for(const r of t)a.set(r.trackId,r);return[...a.values()].sort(f7)}function zje(e,t,a){const r=e.rebuild;if(r===null)return{rows:gw(e.rows,t),cursor:a,exhausted:a===null,rebuild:null};const c=gw(r.rows,t),m=r.pages+1,d=c.length>=r.floor;return a===null||d||m>=jje?{rows:c,cursor:a,exhausted:a===null,rebuild:null}:{...e,rebuild:{rows:c,cursor:a,exhausted:!1,floor:r.floor,pages:m}}}function qje(e){return e.rows.length===0?Tu:{...e,rebuild:{rows:[],cursor:null,exhausted:!1,floor:e.rows.length,pages:0}}}function Lje(e){return e.rebuild===null?e:{...e,rebuild:null}}function Bje(e){return e.rebuild!==null}function TT(e){return e.rebuild!==null?e.rebuild.cursor:e.cursor}function Fje(e,t,a){const r=new Set(e.rows.map(m=>m.trackId));let c=0;for(const m of t)r.has(m.trackId)||(c+=1);return{state:{...e,rows:gw(e.rows,t)},gap:a!==null,deltaCursor:a,added:c}}function $je(e){const t=e.rows[0];return t!==void 0?t.lastSeen:null}function g7(e,t){const a=e.rebuild??e;return a.exhausted?"exhausted":a.rows.length<Math.max(1,t)?"more":"ceiling"}function _T(e,t){return g7(e,t)==="more"}function Uje(e,t){return Math.max(0,e-Math.max(0,t))}function Hje(e){const t=e.sinceMs??Uje(e.anchorMs,e.maxAgeMs);return e.untilMs!==void 0?{since:t,until:e.untilMs}:{since:t}}function Qje(e,t){return e===void 0||e>t}function Vje(e,t){return e}function Kje(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wu(e){return typeof e=="string"&&e.length>0?e:void 0}function Gje(e,t,a){const r=t.length===1?t[0]:void 0;return{text:e,limit:a.semanticLimit,...a.semanticMinScore!==void 0?{minScore:a.semanticMinScore}:{},...r!==void 0?{deviceId:r}:{},...a.sinceMs!==void 0?{since:a.sinceMs}:{},...a.untilMs!==void 0?{until:a.untilMs}:{}}}function Wje(e,t){if(!Kje(e))return null;const a=wu(e.id),r=wu(e.className);if(a===void 0||r===void 0||typeof e.deviceId!="number"||typeof e.timestamp!="number"||typeof e.score!="number")return null;const c=wu(e.trackId),m=typeof e.mediaId=="number"?String(e.mediaId):void 0,d=wu(e.label),h=wu(e.subLabel);return{trackId:c??a,deviceId:e.deviceId,cameraName:t.get(e.deviceId)??`Camera ${e.deviceId}`,className:r,...d!==void 0?{label:d}:{},...h!==void 0?{subLabel:h}:{},...typeof e.importance=="number"?{importance:e.importance}:{},firstSeen:e.timestamp,lastSeen:e.timestamp,state:"idle",active:!1,zonesVisited:[],zoneNames:[],classes:[r],audioLabels:[],bestEventId:m??c??a,score:e.score}}function Zje(e,t){if(!Array.isArray(e))return[];const a=new Map;for(const r of e){const c=Wje(r,t);if(c===null)continue;const m=a.get(c.trackId);(m===void 0||c.score>m.score)&&a.set(c.trackId,c)}return[...a.values()].sort((r,c)=>r.score!==c.score?c.score-r.score:c.lastSeen-r.lastSeen)}function Yje(e,t,a){const r=new Map;for(const c of e)r.set(c.trackId,c);for(const c of t)r.set(c.trackId,c);return Vje([...r.values()].sort(f7))}function Xje(e,t){if(e.length===0)return e;const a=Math.max(1,Math.floor(t.rowsPerColumn)),r=Math.max(1,t.cardWidth+t.gap),c=Math.max(0,Math.floor(Math.max(0,t.scrollLeft)/r)),m=t.viewportWidth>0?t.viewportWidth:t.cardWidth,d=Math.max(c+1,Math.ceil((Math.max(0,t.scrollLeft)+m*2)/r));return e.slice(c*a,Math.min(e.length,d*a))}const Jje=18;function eze(e){const t=Math.max(0,e.gap),a=Math.max(1,e.cardWidth),r=Math.max(0,e.viewportWidth),c=e.columns??"auto",m=c==="auto"?Math.max(1,Math.floor((r+t)/(a+t))):Math.max(1,Math.floor(c)),d=r>0?(r-(m-1)*t)/m:a;return{columns:m,columnWidth:d,rowStridePx:Math.max(1,d+Jje+t)}}const tze=2,aze={startRow:0,endRow:0,padTopPx:0,padBottomPx:0,totalPx:0};function nze(e){const t=Math.max(0,Math.floor(e.rowCount));if(t===0)return aze;const a=e.estimatedRowPx>0?e.estimatedRowPx:1,r=q=>{const B=e.measuredPx.get(q);return B!==void 0&&B>0?B:a};let c=0;for(let q=0;q<t;q+=1)c+=r(q);if(e.viewportHeight<=0)return{startRow:0,endRow:t,padTopPx:0,padBottomPx:0,totalPx:c};const m=Math.max(0,e.scrollTop),d=m+e.viewportHeight;let h=0,f=0;for(;h<t-1&&f+r(h)<=m;)f+=r(h),h+=1;let k=h,x=f;for(;k<t&&x<d;)x+=r(k),k+=1;const E=Math.max(0,Math.floor(e.overscanRows??tze)),R=Math.max(0,h-E),T=Math.min(t,k+E);let N=0;for(let q=0;q<R;q+=1)N+=r(q);let j=0;for(let q=R;q<T;q+=1)j+=r(q);return{startRow:R,endRow:T,padTopPx:N,padBottomPx:Math.max(0,c-N-j),totalPx:c}}function ize(e,t){let a=0,r=0;for(const c of e.values())c>0&&(a+=c,r+=1);return r===0?Math.max(1,t):Math.max(1,a/r)}const rze=24,oze=2;function sze(e,t,a){if(e.length===0)return e;const r=Math.max(1,Math.floor(a)),c=Math.max(0,t.startRow)*r,m=Math.max(1,t.endRow-t.startRow+oze),d=Math.min(e.length,c+Math.min(m*r,rze));return e.slice(c,d)}function lze(e){const{rowCount:t,scrollTop:a,viewportHeight:r,fallbackRowPx:c,geometryKey:m}=e,d=P.useRef(new Map),h=P.useRef(new Map),[f,k]=P.useState(()=>new Map),x=P.useRef(m);P.useEffect(()=>{x.current!==m&&(x.current=m,h.current=new Map,k(new Map))},[m]);const E=P.useCallback(T=>{const N=h.current.get(T);if(N!==void 0)return N;const j=q=>{q===null?d.current.delete(T):d.current.set(T,q)};return h.current.set(T,j),j},[]);return P.useLayoutEffect(()=>{let T=null;for(const[N,j]of d.current){const q=Math.round(j.getBoundingClientRect().height);q<=0||f.get(N)!==q&&(T??=new Map(f),T.set(N,q))}T!==null&&k(T)}),{window:P.useMemo(()=>nze({rowCount:t,scrollTop:a,viewportHeight:r,estimatedRowPx:ize(f,c),measuredPx:f}),[t,a,r,c,f]),measureRow:E}}const cze=1,dze=s5e,uze=["label","sublabel","camera","time","badges","importance"];function pc(e,t){const a=e.get(t);if(a===null||a.trim()==="")return;const r=Number.parseInt(a,10);return Number.isFinite(r)?r:void 0}function PT(e,t){const a=e.get(t)?.trim().toLowerCase();if(a==="1"||a==="true")return!0;if(a==="0"||a==="false")return!1}function mze(e){if(e===null)return;if(e.trim()==="")return[];const t=[];for(const a of e.split(",")){const r=Number.parseInt(a.trim(),10);Number.isFinite(r)&&r>=0&&t.push(r)}return t}function vw(e){if(e!==null)return e.trim()===""?[]:e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function pze(e){if(e===null)return;const t=new Set((vw(e)??[]).map(r=>r.toLowerCase())),a={};for(const r of uze)a[r]=t.has(r.toLowerCase());return a}function hze(e,t){const a=e.startsWith("?")?e.slice(1):e;for(const r of a.split("&")){if(r.length===0)continue;const c=r.indexOf("=");if((c===-1?r:r.slice(0,c))===t)return c===-1?"":r.slice(c+1)}return null}function fze(e){if(e===null)return;const t={};if(e.trim()==="")return t;for(const a of e.split(",")){const r=a.indexOf(":");if(r<=0)continue;const c=a.slice(0,r).trim();if(!/^\d+$/.test(c))continue;let m;try{m=decodeURIComponent(a.slice(r+1))}catch{continue}m.trim().length!==0&&(t[c]=m)}return t}function NT(e,t){const a=e.get(t);if(a===null)return;if(a.trim()==="")return null;const r=Number.parseInt(a,10);return Number.isFinite(r)&&r>=0?r:void 0}function gze(e){if(e===null||e.trim()==="")return;if(e==="auto")return"auto";const t=Number.parseInt(e,10);return Number.isFinite(t)?t:void 0}function vze(e){const t=e.startsWith("#")?e.slice(1):e;if(t.length===0)return null;const a=new URLSearchParams(t).get("t");return a!==null&&a.length>0?a:null}function v7(e){const t=new URLSearchParams(e.startsWith("?")?e.slice(1):e),a=t.get("v");if(a===null)return null;if(Number.parseInt(a,10)!==cze)return{ok:!1,error:`unsupported events URL version "${a}"`};const c={},m=t.get("view");m!==null&&(c.view=m);const d=pc(t,"rows");d!==void 0&&(c.rows=d);const h=gze(t.get("cols"));h!==void 0&&(c.columns=h);const f=t.get("thumb");f!==null&&(c.thumbSize=f);const k=pze(t.get("fields"));k!==void 0&&(c.fields=k);const x=t.get("tileLabelMode");x!==null&&(c.tileLabelMode=x);const E=PT(t,"tileDetailCamera");E!==void 0&&(c.tileDetailCamera=E);const R=PT(t,"tileDetailZone");R!==void 0&&(c.tileDetailZone=R);const T=mze(t.get("devices"));T!==void 0&&(c.deviceIds=T);const N=vw(t.get("classes"));N!==void 0&&(c.classes=N);const j=vw(t.get("attrs"));j!==void 0&&(c.attrs=j);const q=t.get("q");q!==null&&(c.search=q);const B=pc(t,"page");B!==void 0&&(c.pageSize=B);const F=pc(t,"max");F!==void 0&&(c.maxRows=F);const U=pc(t,"refresh");U!==void 0&&(c.refreshMs=U);const H=pc(t,"age");H!==void 0&&(c.maxAgeMs=H);const Q=t.get("theme");Q!==null&&(c.theme=Q);const te=i7(t.get("lang"));te!==void 0&&(c.locale=te);const K=t.get("smode");K!==null&&(c.searchMode=K);const W=pc(t,"slimit");W!==void 0&&(c.semanticLimit=W);const oe=t.get("sscore");if(oe!==null&&oe.trim()!==""){const Ie=Number.parseFloat(oe);Number.isFinite(Ie)&&(c.semanticMinScore=Ie)}const he=NT(t,"since");he!==void 0&&(c.sinceMs=he);const Ae=NT(t,"until");Ae!==void 0&&(c.untilMs=Ae);const we=fze(hze(e,"names"));we!==void 0&&(c.deviceNames=we);const Ee=l7.safeParse(c);return Ee.success?{ok:!0,patch:Ee.data}:{ok:!1,error:Ee.error.issues.map(Ie=>`${Ie.path.join(".")||"(root)"}: ${Ie.message}`).join("; ")}}function yze(e,t,a,r=""){const c=v7(e);if(c===null)return null;if(!c.ok)return{ok:!1,error:c.error};const m=x5e(a,r,dze),d=vze(t);return d===null&&!qx(m)?null:Fx({serverUrl:m,...d!==null?{token:d}:{},fields:r7,...c.patch})}function y7(){const e=yze(location.search,location.hash,location.origin,location.pathname);return e!==null&&location.hash!==""&&history.replaceState(null,"",location.pathname+location.search),e}function bze(){const e=v7(location.search);return e===null||!e.ok?null:e.patch}function kze(e,t){return!e.ok||t===null?e:{ok:!0,config:dw(e.config,t)}}const Sze=/^(10\.|127\.|192\.168\.|169\.254\.|172\.(1[6-9]|2\d|3[01])\.)/;function wze(e){let t;try{const m=qx(e)&&typeof location<"u"?location.href:void 0;t=new URL(e,m).host}catch{return"unknown:(unparseable)"}const a=t.trim().toLowerCase().replace(/^\[([^\]]*)\].*$/,"$1"),r=a.lastIndexOf(":"),c=r!==-1&&a.indexOf(":")===r?a.slice(0,r):a;return c==="localhost"||c==="::1"||c.startsWith("127.")?`loopback:${t}`:Sze.test(c)||/^f[cd][0-9a-f]{2}:/.test(c)||c.startsWith("fe80:")||c.endsWith(".local")?`lan:${t}`:c.includes(".")?`public:${t}`:`unknown:${t}`}const xze=4,Mze=1e3,OT=4e3,Cze=new Set(["UNAUTHORIZED","FORBIDDEN","NOT_FOUND"]),Aze=new Set([401,403,404]),Ize=.8,Eze=.4;function yw(e,t){if(typeof e!="object"||e===null)return null;const a=Reflect.get(e,t);return typeof a=="string"?a:null}function DT(e,t){if(typeof e!="object"||e===null)return null;const a=Reflect.get(e,t);return typeof a=="number"?a:null}function jT(e){return typeof e!="object"||e===null?null:Reflect.get(e,"data")}function zT(e){if(typeof e!="object"||e===null)return null;const t=Reflect.get(e,"shape");return typeof t!="object"||t===null?null:Reflect.get(t,"data")}function Rze(e){return typeof e=="string"?e:yw(e,"message")}function qT(e){return e!==null&&Cze.has(e)}function LT(e){return e!==null&&Aze.has(e)}function Tze(e){return e===null?!1:e.includes("UNAUTHORIZED")||e.includes("FORBIDDEN")||e.includes("NOT_FOUND")}function b7(e){return qT(yw(jT(e),"code"))||LT(DT(jT(e),"httpStatus"))||qT(yw(zT(e),"code"))||LT(DT(zT(e),"httpStatus"))?!0:Tze(Rze(e))}function _ze(e,t,a=Math.random){if(b7(t)||!Number.isInteger(e)||e<0||e+1>=xze)return null;const r=Math.min(OT,Mze*2**e),c=Math.min(1,Math.max(0,a())),m=Math.round(r*(Ize+c*Eze));return Math.min(OT,m)}const BT=5;let Pze=0;function Nze(e){if(typeof e!="object"||e===null)return!1;const t=e;return"tracks"in t&&(t.nextCursor===null||typeof t.nextCursor=="string")}const Oze=()=>{},Dze=[];function jze(e){const{client:t,deviceIds:a,nameById:r,pageSize:c,maxRows:m,refreshMs:d,maxAgeMs:h}=e,f=e.log??Oze,k=P.useRef(f);P.useEffect(()=>{k.current=f},[f]);const{sinceMs:x,untilMs:E,devicesResolved:R}=e,T=e.includeStationary===!0,N=e.excludeSources??Dze,j=[...N].sort().join(","),[q,B]=P.useState(Tu),[F,U]=P.useState(!1),[H,Q]=P.useState(!1),[te,K]=P.useState(null),[W,oe]=P.useState(0),[he,Ae]=P.useState(m),we=P.useRef(m);we.current=he;const Ee=P.useRef(Tu);Ee.current=q;const Ie=P.useRef(!1),Me=P.useRef(!1),Y=P.useRef(0),de=P.useRef(null),Re=P.useRef(Date.now()),Qe=P.useRef(r);Qe.current=r;const re=P.useRef(e.channel);re.current=e.channel;const V=P.useRef(null);P.useEffect(()=>{sje()},[]);const ie=a.join(","),fe=P.useCallback(async(ft,lt=0)=>{const Dt=`feed-${String(++Pze)}`,bt=performance.now();try{const ve=await t.listRecentTracks(ft),Fe=performance.now(),Le=mw(Fe-bt,pw(bt,Fe)),ot={requestId:Dt,waitMs:Math.round(lt),...Le};return Nze(ve)?{ok:!0,page:ve,timing:ot}:(k.current("request invalid",{...ot,channel:re.current}),{ok:!1,message:"unexpected response shape",error:new Error("unexpected response shape")})}catch(ve){const Fe=ve instanceof Error?ve.message:String(ve),Le=performance.now();return k.current("listRecentTracks failed",{error:Fe,devices:ft.deviceIds.length,limit:ft.limit,since:ft.since,cursor:ft.cursor??null,requestId:Dt,channel:re.current,waitMs:Math.round(lt),...mw(Le-bt,pw(bt,Le))}),{ok:!1,message:Fe,error:ve}}},[t]),be=P.useCallback((ft,lt)=>{k.current("request complete",{...ft,channel:re.current,...lt})},[]),ee=P.useCallback(()=>{if(Ie.current){Me.current=!0,V.current===null&&(V.current=performance.now());return}const ft=Ee.current;if(!_T(ft,we.current)||a.length===0)return;const lt=V.current;V.current=null;const Dt=lt===null?0:performance.now()-lt;Ie.current=!0,Q(!0);const bt=RT(c,a.length),ve=Hje({anchorMs:Re.current,maxAgeMs:h,...x!==void 0?{sinceMs:x}:{},...E!==void 0?{untilMs:E}:{}}),Fe=TT(ft)!==null;fe({deviceIds:[...a],since:ve.since,limit:bt,projection:"slim",...T?{includeStationary:!0}:{},...N.length>0?{excludeSources:[...N]}:{},...ve.until!==void 0?{until:ve.until}:{},...(()=>{const Le=TT(ft);return Le!==null?{cursor:Le}:{}})()},Dt).then(Le=>{if(Le.ok){const $t=performance.now(),ze=hT(Le.page.tracks,Qe.current),st=zje(Ee.current,ze,Le.page.nextCursor);Ee.current=st,B(st),be(Le.timing,{rows:ze.length,devices:a.length,limit:bt,paged:Fe,parseMs:Math.round(performance.now()-$t)}),Y.current=0,K(null),U(!0);return}const ot=Y.current,He=_ze(ot,Le.error);if(He!==null){Y.current=ot+1,k.current("page failed — retrying",{attempt:ot+1,backoffMs:He}),de.current=setTimeout(()=>{de.current=null,Se.current()},He);return}k.current("page failed — giving up",{attempt:ot+1,terminal:b7(Le.error)}),Y.current=0;const ea=Lje(Ee.current);Ee.current=ea,B(ea),K(Le.message),U(!0)}).finally(()=>{if(Ie.current=!1,Q(!1),Bje(Ee.current)){Se.current();return}Me.current&&(Me.current=!1,Se.current())})},[fe,be,a,ie,c,h,x,E,T,j]),Se=P.useRef(ee);Se.current=ee;const _e=P.useCallback(()=>{if(Ie.current||a.length===0)return Promise.resolve();const ft=$je(Ee.current);if(ft===null)return Ot.current(),Promise.resolve();Ie.current=!0;const lt=RT(c,a.length);return(async()=>{let Dt=null,bt=0,ve=!0;for(;ve&&bt<BT;){const Fe=await fe({deviceIds:[...a],since:ft,limit:lt,projection:"slim",...T?{includeStationary:!0}:{},...N.length>0?{excludeSources:[...N]}:{},...E!==void 0?{until:E}:{},...Dt!==null?{cursor:Dt}:{}});if(!Fe.ok)return;const Le=Fe.page,ot=performance.now(),He=hT(Le.tracks,Qe.current),ea=Fje(Ee.current,He,Le.nextCursor);Ee.current=ea.state,B(ea.state),be(Fe.timing,{rows:He.length,devices:a.length,limit:lt,paged:Dt!==null,delta:!0,parseMs:Math.round(performance.now()-ot)}),K(null),ve=ea.gap,Dt=ea.deltaCursor,bt+=1}ve&&k.current("delta drain hit its page bound — newer rows may be missing",{since:ft,pages:bt,bound:BT})})().finally(()=>{Ie.current=!1,Me.current&&(Me.current=!1,Se.current())})},[fe,be,a,ie,c,ee,E,T,j]),Be=P.useCallback(()=>{de.current!==null&&(clearTimeout(de.current),de.current=null),Y.current=0},[]),Ge=P.useCallback(()=>{const ft=we.current+Math.max(1,m);we.current=ft,Ae(ft),Se.current()},[m]),Ft=P.useCallback(()=>{Be(),K(null),U(!1),Se.current()},[Be]),Ot=P.useRef(()=>{}),wt=P.useCallback(()=>{Be(),Re.current=Date.now(),Me.current=!1,Ee.current=Tu,B(Tu),U(!1),Q(!1),K(null),we.current=m,Ae(m),oe(ft=>ft+1)},[Be,m]),sa=P.useCallback(()=>{Be(),Re.current=Date.now(),Me.current=!1;const ft=qje(Ee.current);Ee.current=ft,B(ft),ft.rows.length===0&&U(!1),Q(!1),K(null),oe(lt=>lt+1)},[Be]),nt=`${ie}|${h}|${x??""}|${E??""}|${T?"1":"0"}|${j}`,za=P.useRef(nt);return P.useEffect(()=>{za.current!==nt&&(za.current=nt,!(Ee.current.rows.length===0&&!F)&&wt())},[nt,wt,F]),P.useEffect(()=>{if(a.length===0){R&&U(!0);return}ee()},[W,ie,R]),P.useEffect(()=>{if(d<=0||a.length===0||!Qje(E,Date.now()))return;const ft=setInterval(()=>{_e()},d);return()=>clearInterval(ft)},[d,_e,a.length,E]),Ot.current=Ft,P.useEffect(()=>Be,[Be]),{rows:q.rows,retry:Ft,loading:!F,loadingMore:H&&F,error:te,hasMore:_T(q,he),tail:g7(q,he),loadMore:ee,loadOlder:Ge,refresh:_e,reload:sa}}const zze=3,qze=250;function Lze(e){const{urls:t,token:a,paused:r,enabled:c}=e,m=P.useRef(0),d=P.useRef(0),h=P.useRef(!1),f=P.useRef(t),k=P.useRef(t[0]??"");f.current=t;const x=t[0]??"";k.current!==x&&(k.current=x,m.current=0),P.useEffect(()=>{if(h.current=!1,!c||r)return;let E=!1;const R=()=>{if(!(E||h.current))for(;d.current<zze;){const T=f.current,N=m.current;if(N>=T.length)return;m.current=N+1;const j=T[N];j===void 0||j.length===0||(d.current+=1,Sje(j,a).finally(()=>{d.current=Math.max(0,d.current-1),R()}))}};return R(),()=>{E=!0,h.current=!0}},[c,r,a,t.length])}const Bze=.5,k7=56,Fze=88;function $ze(e){return e<=0?0:Math.min(e*Bze,Fze)}function FT(e){return e>=k7}function Uze(e,t,a){return e==="gallery"&&!t&&!a}function Hze(e){const{root:t,onRefresh:a,enabled:r}=e,[c,m]=P.useState(0),d=P.useRef(null),h=P.useRef(0);h.current=c;const f=P.useRef(a);f.current=a;const k=P.useCallback(()=>{d.current=null,m(0)},[]);return P.useEffect(()=>{if(!r||t===null)return;const x=N=>{if(t.scrollTop>0){d.current=null;return}const j=N.touches[0];d.current=j!==void 0?j.clientY:null},E=N=>{const j=d.current;if(j===null)return;const q=N.touches[0];if(q!==void 0){if(t.scrollTop>0){d.current=null,m(0);return}m($ze(q.clientY-j))}},R=()=>{if(d.current===null)return;const N=h.current;k(),FT(N)&&f.current()},T={passive:!0};return t.addEventListener("touchstart",x,T),t.addEventListener("touchmove",E,T),t.addEventListener("touchend",R,T),t.addEventListener("touchcancel",k,T),()=>{t.removeEventListener("touchstart",x),t.removeEventListener("touchmove",E),t.removeEventListener("touchend",R),t.removeEventListener("touchcancel",k)}},[t,r,k]),{distance:c,armed:FT(c)}}const ok=8,$h=3,$T=10,UT=4,Qze=400;function Vze(e){return Math.max(Qze,Math.round(e))}function S7(e,t){return{display:"flex",alignItems:"center",justifyContent:"center",padding:e?"0 12px":"10px 0",width:e?"max-content":"100%",height:e?t:void 0,...e?{gridColumn:"auto"}:{},whiteSpace:"nowrap"}}function HT(e,t,a){return{...S7(e,t),font:"inherit",fontSize:12,color:a.text,background:a.card,border:`1px solid ${a.border}`,borderRadius:8,cursor:"pointer"}}const Kze=8;function QT({message:e,palette:t}){return P.useEffect(()=>{Ei(H5e(e)),Ei(Sf("error",e))},[e]),v.jsxs("div",{style:{position:"fixed",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:t.background,color:"var(--color-danger)",fontFamily:"system-ui, sans-serif",fontSize:13,padding:16,textAlign:"center"},children:["Events embed config error: ",e]})}function Gze({client:e,initialConfig:t}){const[a,r]=P.useState(t),[c,m]=P.useState({}),[d,h]=P.useState(()=>window.matchMedia?.("(prefers-color-scheme: dark)").matches??!0),[f,k]=P.useState(()=>Date.now()),[x,E]=P.useState(null);P.useEffect(()=>{let xe=!1;return e.listDevices().then(Oe=>{xe||E(Oe)}).catch(()=>{xe||E([])}),()=>{xe=!0}},[e]);const R=P.useMemo(()=>{const xe=new Map;for(const Oe of x??[])xe.set(Oe.id,z5e(Oe.id,Oe.name??`Camera ${Oe.id}`,a.deviceNames));for(const[Oe,xt]of Object.entries(a.deviceNames)){const ha=Number(Oe);Number.isInteger(ha)&&!xe.has(ha)&&xt.trim().length>0&&xe.set(ha,xt)}return xe},[x,a.deviceNames]),[T,N]=P.useState(()=>new Map),[j,q]=P.useState(()=>new Map),B=P.useMemo(()=>H8(a.kindLabels),[a.kindLabels]),F=Bx(a.locale,typeof navigator>"u"?void 0:navigator.language),U=P.useMemo(()=>B8(a.labels,F),[a.labels,F]),H=P.useMemo(()=>a.deviceIds.length>0?a.deviceIds:x===null?[]:ZDe(x),[a.deviceIds,x]);P.useEffect(()=>{if(H.length===0)return;let xe=!1;return e.listEventKinds([...H]).then(Oe=>{xe||(N(kDe(Oe)),q(wDe(Oe)))}).catch(()=>{qc("event-kind taxonomy unavailable — class filter is exact-id only")}),()=>{xe=!0}},[e,H]);const Q=jze({client:e,log:qc,deviceIds:H,nameById:R,pageSize:a.pageSize,maxRows:T5e(a),refreshMs:a.refreshMs,maxAgeMs:a.maxAgeMs,channel:wze(a.serverUrl),devicesResolved:a.deviceIds.length>0||x!==null,...a.showStationary?{includeStationary:!0}:{},excludeSources:a.excludeSources,...a.sinceMs!==void 0?{sinceMs:a.sinceMs}:{},...a.untilMs!==void 0?{untilMs:a.untilMs}:{}}),te=a.searchMode==="semantic"?a.search.trim():"",[K,W]=P.useState({query:"",rows:[],loading:!1});P.useEffect(()=>{if(te.length===0||H.length===0){W({query:"",rows:[],loading:!1});return}let xe=!1;return W(Oe=>({...Oe,query:te,loading:!0})),e.searchObjectEvents(Gje(te,H,{semanticLimit:a.semanticLimit,semanticMinScore:a.semanticMinScore,sinceMs:a.sinceMs,untilMs:a.untilMs})).then(Oe=>{xe||W({query:te,rows:Zje(Oe,R),loading:!1})}).catch(Oe=>{xe||(qc("searchObjectEvents failed",{error:Oe instanceof Error?Oe.message:String(Oe)}),W({query:te,rows:[],loading:!1}))}),()=>{xe=!0}},[e,te,H,R,a.semanticLimit,a.semanticMinScore,a.sinceMs,a.untilMs]);const oe=te.length>0,he=P.useMemo(()=>new Set(a.reviewedTrackIds),[a.reviewedTrackIds]),Ae=xe=>he.size===0?[...xe]:xe.map(Oe=>he.has(Oe.trackId)?{...Oe,reviewed:!0}:Oe),we=P.useMemo(()=>Ae(vT(gT(Q.rows,R),c)),[Q.rows,R,he,c]),Ee=P.useMemo(()=>Ae(vT(gT(K.rows,R),c)),[K.rows,R,he,c]),Ie=P.useMemo(()=>{const xe={debug:a.filterDebug,train:a.filterTrain,favourited:a.filterFavourited,reviewedTrackIds:a.reviewedTrackIds},Oe=fT(we,a.classes,a.search,T,a.attrs,xe,a.excludeSources);if(oe){const xt=fT(Ee,a.classes,"",T,a.attrs,xe,a.excludeSources);return Yje(xt,Oe)}return Oe},[oe,Ee,we,a.classes,a.attrs,a.filterDebug,a.filterTrain,a.filterFavourited,a.reviewedTrackIds,a.search,a.excludeSources,T]),Me=Ox(a.theme,d),Y=F,de=P.useRef(null),[Re,Qe]=P.useState(null),re=P.useRef(null),V=P.useRef(Q.loadMore);V.current=Q.loadMore;const ie=P.useRef(Q.refresh);ie.current=Q.refresh;const fe=P.useRef(Q.reload);fe.current=Q.reload;const[be]=P.useState(()=>Nje(Ei)),ee=P.useCallback(xe=>{if(xe.type==="setConfig"){r(Oe=>dw(Oe,xe.patch));return}if(xe.type==="setWindow"){r(Oe=>dw(Oe,tje(xe)));return}if(xe.type==="setTrackFlagPatches"){m(xe.patches);return}if(xe.type==="setTrackListMode"){be.setMode(xe.mode);return}if(xe.type==="refresh"){ie.current().finally(()=>Ei(Z5e()));return}if(xe.type==="reload"){fe.current();return}if(xe.type==="loadMore"){V.current();return}if(xe.type==="ping"){Ei(G5e());return}de.current?.scrollTo({top:0,left:0,behavior:"smooth"})},[be]);P.useEffect(()=>(window.__camstackEvents={setConfig:xe=>{const Oe=Su({type:"setConfig",patch:xe});Oe!==null&&ee(Oe)},setWindow:xe=>{const Oe=Su({type:"setWindow",...xe});Oe!==null&&ee(Oe)},setTrackFlagPatches:xe=>{const Oe=Su({type:"setTrackFlagPatches",patches:xe});Oe!==null&&ee(Oe)},setTrackListMode:xe=>{const Oe=Su({type:"setTrackListMode",mode:xe});Oe!==null&&ee(Oe)},refresh:()=>ee({type:"refresh"}),reload:()=>ee({type:"reload"}),loadMore:()=>ee({type:"loadMore"}),scrollToTop:()=>ee({type:"scrollToTop"}),ping:()=>ee({type:"ping"})},Gm(xe=>{const Oe=Su(xe);Oe!==null&&ee(Oe)})),[ee]),P.useEffect(()=>{Ei(U5e(a.view))},[]),P.useEffect(()=>{Ei(oe?ST(K.rows.length,Ie.length,!1,"semantic"):ST(Q.rows.length,Ie.length,Q.hasMore,"feed"))},[Q.rows.length,Ie.length,Q.hasMore,oe,K.rows.length]),P.useEffect(()=>{be.report(Ie)},[be,Ie]),P.useEffect(()=>{if(Q.error!==null&&!oe){Ei(Sf("error",Q.error));return}if(oe?K.loading:Q.loading){Ei(Sf("loading"));return}Ei(Sf(Ie.length===0?"empty":"ready"))},[Q.loading,Q.error,Ie.length,oe,K.loading]),P.useEffect(()=>{const xe=window.matchMedia?.("(prefers-color-scheme: dark)");if(!xe)return;const Oe=xt=>h(xt.matches);return xe.addEventListener("change",Oe),()=>xe.removeEventListener("change",Oe)},[]),P.useEffect(()=>{document.documentElement.style.colorScheme=Me.colorScheme,document.body.style.background=Me.background},[Me]),P.useEffect(()=>{const xe="camstack-events-keyframes";if(document.getElementById(xe)!==null)return;const Oe=document.createElement("style");Oe.id=xe,Oe.textContent="@keyframes camstack-spin{to{transform:rotate(360deg)}}",document.head.appendChild(Oe)},[]),P.useEffect(()=>{const xe=setInterval(()=>k(Date.now()),6e4);return()=>clearInterval(xe)},[]);const[Se,_e]=P.useState(0);P.useEffect(()=>{const xe=Re;if(xe===null)return;const Oe=()=>{const ha=a.view==="reel"?xe.clientWidth:xe.clientHeight;_e(xn=>xn===ha?xn:ha)};if(Oe(),typeof ResizeObserver!="function")return;const xt=new ResizeObserver(Oe);return xt.observe(xe),()=>xt.disconnect()},[Re,a.view]);const Be=Q.rows.length,Ge=Be>0;P.useEffect(()=>{const xe=de.current,Oe=re.current;if(!xe||!Oe||oe||!Ge)return;const xt=Vze(a.view==="reel"?xe.clientWidth:xe.clientHeight),ha=new IntersectionObserver(xn=>{xn.some(Yn=>Yn.isIntersecting)&&V.current()},{root:xe,rootMargin:`${xt}px`});return ha.observe(Oe),()=>ha.disconnect()},[a.view,Q.hasMore,oe,Ge,Se]);const Ft=P.useRef(0),Ot=P.useRef(0);P.useEffect(()=>{if(oe||Q.loading||Q.loadingMore||!Q.hasMore)return;const xe=de.current;if(!xe||Be===0)return;const Oe=a.view==="reel";if((Oe?xe.clientWidth:xe.clientHeight)===0)return;if(Oe?xe.scrollWidth>xe.clientWidth+1:xe.scrollHeight>xe.clientHeight+1){Ft.current=0,Ot.current=Be;return}Be>Ot.current&&(Ft.current=0,Ot.current=Be),!(Ft.current>=Kze)&&(Ft.current+=1,V.current())},[Ie.length,Be,Q.loading,Q.loadingMore,Q.hasMore,oe,a.view]);const wt=Hze({root:Re,enabled:Uze(a.view,oe,a.nativePullToRefresh),onRefresh:()=>{ie.current()}}),sa=P.useRef(null);P.useEffect(()=>{const xe=Re;if(!a.nativePullToRefresh||xe===null){sa.current=null;return}const Oe=()=>{const xt=a.view==="gallery"&&!oe&&xe.scrollTop<=0;sa.current!==xt&&(sa.current=xt,Ei(W5e(xt)))};return Oe(),xe.addEventListener("scroll",Oe,{passive:!0}),()=>xe.removeEventListener("scroll",Oe)},[Re,a.nativePullToRefresh,a.view,oe]);const nt=a.view==="reel",[za,ft]=P.useState(!1),[lt,Dt]=P.useState({scrollLeft:0,scrollTop:0,viewportWidth:0,viewportHeight:0});P.useEffect(()=>{const xe=Re;if(xe===null)return;let Oe=null;const xt=()=>{Dt({scrollLeft:xe.scrollLeft,scrollTop:xe.scrollTop,viewportWidth:xe.clientWidth,viewportHeight:xe.clientHeight})},ha=()=>{xt(),ft(!0),Oe!==null&&clearTimeout(Oe),Oe=setTimeout(()=>ft(!1),qze)};return xt(),xe.addEventListener("scroll",ha,{passive:!0}),window.addEventListener("resize",xt),()=>{xe.removeEventListener("scroll",ha),window.removeEventListener("resize",xt),Oe!==null&&clearTimeout(Oe)}},[Re]);const bt=P.useMemo(()=>S5e({viewportWidth:lt.viewportWidth,viewportHeight:lt.viewportHeight,rows:a.rows,presetEdge:cw(a.thumbSize),gap:ok,padX:$T}),[lt.viewportWidth,lt.viewportHeight,a.rows,a.thumbSize]),ve=nt?bt.edge:cw(a.thumbSize),Fe=nt?bt.cardHeight:j5e(a.thumbSize),Le=N5e(ve,window.devicePixelRatio||1),ot=P.useMemo(()=>eze({viewportWidth:lt.viewportWidth-2*UT,cardWidth:ve,gap:$h,columns:a.columns}),[lt.viewportWidth,ve,a.columns]),He=P.useMemo(()=>d5e(a.fields,{tileLabelMode:a.tileLabelMode,tileDetailCamera:a.tileDetailCamera,tileDetailZone:a.tileDetailZone}),[a.fields,a.tileLabelMode,a.tileDetailCamera,a.tileDetailZone]),ea=nt?0:Math.ceil(Ie.length/ot.columns),$t=lze({rowCount:ea,scrollTop:lt.scrollTop,viewportHeight:lt.viewportHeight,fallbackRowPx:ot.rowStridePx,geometryKey:`${ot.columns}|${ve}|${a.fields.sublabel?"s":""}${He.tileDetailCamera?"c":""}${He.tileDetailZone?"z":""}`}),ze=P.useMemo(()=>nt?Xje(Ie,{scrollLeft:lt.scrollLeft,viewportWidth:lt.viewportWidth,cardWidth:ve,gap:ok,rowsPerColumn:a.rows}):sze(Ie,$t.window,ot.columns),[nt,Ie,lt.scrollLeft,lt.viewportWidth,ve,a.rows,$t.window,ot.columns]),st=P.useMemo(()=>ze.map(xe=>Nx(a.serverUrl,xe.trackId,Le)),[ze,a.serverUrl,Le]);Lze({urls:st,token:a.token,paused:za,enabled:!Q.loading&&Ie.length>0});const Lt=P.useCallback(xe=>{Ei(Q5e({trackId:xe.trackId,deviceId:xe.deviceId,bestEventId:xe.bestEventId,className:xe.className,firstSeen:xe.firstSeen,lastSeen:xe.lastSeen}))},[]),Kt=nt?{display:"grid",gridTemplateRows:`repeat(${a.rows}, ${Fe}px)`,gridAutoFlow:"column",gridAutoColumns:`${ve}px`,gap:ok,alignContent:"start"}:{display:"grid",gridTemplateColumns:`repeat(${ot.columns}, minmax(0, 1fr))`,columnGap:$h,rowGap:$h,paddingBottom:$h,alignContent:"start"},qa=oe?K.loading:Q.loading,fn=!oe&&Q.loadingMore&&Be>0,ct=!oe&&Q.error!==null,Ut=!oe&&!Q.loadingMore&&Be>0,La=Ut&&ct,Sa=Ut&&!ct&&Q.tail==="exhausted",Di=Ut&&!ct&&Q.tail==="ceiling",Zn=ct&&Ie.length===0,ji=!qa&&!ct&&!Q.loadingMore&&Ie.length===0,gn=ji&&Be>0,Pn=(xe,Oe)=>v.jsx(Cje,{row:xe,eagerImages:!nt&&Oe<8,serverUrl:a.serverUrl,token:a.token,thumbPx:Le,width:nt?`${ve}px`:"100%",heroPx:nt?ve:ot.columnWidth,variant:nt?"reel":"gallery",iconId:U8(xe.className,j,ig(xe)),kindLabels:B,labels:U,scrollRoot:Re,fields:a.fields,display:He,showAdminFlags:a.showAdminFlags===!0,palette:Me,nowMs:f,locale:Y,onClick:Lt},xe.trackId),vn=v.jsxs(v.Fragment,{children:[fn&&v.jsx("div",{"data-testid":"tail-loading","aria-label":U.loadingMore,style:{width:nt?ve:"100%",height:nt?Fe:void 0,aspectRatio:nt?void 0:"1 / 1",borderRadius:10,background:Me.skeleton,border:`1px solid ${Me.border}`,boxSizing:"border-box",opacity:.6,display:"flex",alignItems:"center",justifyContent:"center"},children:v.jsx("span",{style:{width:14,height:14,borderRadius:999,border:`2px solid ${Me.chip}`,borderTopColor:Me.textMuted,animation:"camstack-spin 700ms linear infinite"}})}),Sa&&v.jsx("div",{"data-testid":"tail-end",style:{...S7(nt,ve),color:Me.textMuted,fontSize:11,opacity:.75},children:mc(a,"end")}),Di&&v.jsx("button",{type:"button","data-testid":"tail-more",onClick:()=>Q.loadOlder(),style:HT(nt,ve,Me),children:mc(a,"loadOlder")}),La&&v.jsx("button",{type:"button","data-testid":"tail-error",onClick:()=>Q.retry(),style:{...HT(nt,ve,Me),color:"var(--color-danger)"},children:mc(a,"retry")}),v.jsx("div",{ref:re,style:{width:1,height:1,gridRow:nt?1:"auto"},"aria-hidden":!0})]});return v.jsxs("div",{ref:xe=>{de.current=xe,Qe(Oe=>Oe===xe?Oe:xe)},"data-testid":"events-scroller",className:nt?"events-reel-scroller":void 0,style:{position:"fixed",inset:0,background:Me.background,color:Me.text,fontFamily:"system-ui, -apple-system, sans-serif",overflowX:nt?"auto":"hidden",overflowY:nt?"hidden":"auto",padding:nt?`${J8}px ${$T}px`:UT,boxSizing:"border-box",WebkitOverflowScrolling:"touch"},children:[wt.distance>0&&v.jsx("div",{"data-testid":"pull-indicator","data-armed":wt.armed?"true":"false","aria-hidden":!0,style:{position:"absolute",top:Math.max(0,wt.distance-28),left:0,right:0,display:"flex",justifyContent:"center",pointerEvents:"none",zIndex:2,opacity:Math.min(1,wt.distance/k7)},children:v.jsx("span",{style:{width:22,height:22,borderRadius:999,border:`2px solid ${Me.chip}`,borderTopColor:Me.textMuted,background:Me.card,boxShadow:"0 1px 4px rgba(0,0,0,0.25)",transform:`rotate(${wt.distance*4}deg)`,animation:Q.loadingMore?"camstack-spin 700ms linear infinite":void 0}})}),Zn&&v.jsxs("div",{"data-testid":"state-error",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",color:"var(--color-danger)",fontSize:13,padding:16,textAlign:"center"},children:[v.jsx("span",{children:mc(a,"error")}),v.jsx("button",{type:"button","data-testid":"state-retry",onClick:()=>Q.retry(),style:{marginTop:10,font:"inherit",fontSize:12,color:Me.text,background:Me.card,border:`1px solid ${Me.border}`,borderRadius:8,padding:"5px 14px",cursor:"pointer"},children:mc(a,"retry")})]}),ji&&v.jsx("div",{"data-testid":gn?"state-empty-filtered":"state-empty",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:Me.textMuted,fontSize:13,padding:"0 24px",textAlign:"center"},children:mc(a,gn?"emptyFiltered":"empty")}),qa&&Ie.length===0&&v.jsx("div",{"data-testid":"state-loading",style:Kt,children:Array.from({length:nt?8:12},(xe,Oe)=>v.jsx("div",{style:{width:nt?ve:"100%",height:nt?Fe:void 0,aspectRatio:nt?void 0:"1 / 1",borderRadius:10,background:Me.skeleton,border:`1px solid ${Me.border}`,boxSizing:"border-box",opacity:.6}},`skeleton-${Oe}`))}),nt?v.jsxs("div",{style:Kt,children:[Ie.map(Pn),vn]}):v.jsxs("div",{"data-testid":"events-gallery",children:[v.jsx("div",{"data-testid":"gallery-pad-top",style:{height:$t.window.padTopPx},"aria-hidden":!0}),Array.from({length:$t.window.endRow-$t.window.startRow},(xe,Oe)=>{const xt=$t.window.startRow+Oe,ha=xt*ot.columns;return v.jsx("div",{"data-row-index":xt,ref:$t.measureRow(xt),style:Kt,children:Ie.slice(ha,ha+ot.columns).map((xn,Yn)=>Pn(xn,ha+Yn))},xt)}),v.jsx("div",{"data-testid":"gallery-pad-bottom",style:{height:$t.window.padBottomPx},"aria-hidden":!0}),vn]})]})}function Wze(){const e=Wm("events",()=>window.__CAMSTACK_EVENTS__,Fx,y7,{urlFirst:!0}),t=P.useMemo(()=>bze(),[]),a=P.useMemo(()=>e===null?null:kze(e,t),[e,t]),r=P.useMemo(()=>{if(a===null||!a.ok)return null;const m=xm({serverUrl:a.config.serverUrl,token:a.config.token});return{system:m,client:Ije(m)}},[a]);P.useEffect(()=>{if(r)return()=>r.system.close()},[r]);const c=Ox(a!==null&&a.ok?a.config.theme:"auto",window.matchMedia?.("(prefers-color-scheme: dark)").matches??!0);return a===null?null:a.ok?r?v.jsxs(v.Fragment,{children:[v.jsx(Wg,{system:r.system}),v.jsx(Gze,{client:r.client,initialConfig:a.config})]}):v.jsx(QT,{message:"Failed to initialise the events embed",palette:c}):v.jsx(QT,{message:a.error,palette:c})}const og={play:"Play",pause:"Pause",listen:"Listen",mute:"Mute",talk:"Talk",stopTalk:"Stop talk",ptz:"PTZ",linkedDevices:"Linked devices",viewOptions:"View options",moreActions:"More actions",open:"Open",removeFromView:"Remove from view",resizeWidth:"Resize width",resizeHeight:"Resize height",noActiveCameras:"No active cameras",camera:"Camera"},Zze=Object.keys(og),Yze=$(n(),n()).optional();function Xze(e){if(e===null||typeof e!="object")return og;const t=e,a={...og};for(const r of Zze){const c=t[r];typeof c=="string"&&c.trim()!==""&&(a[r]=c)}return a}const w7=I(["auto","high","mid","low"]).catch("auto"),Jze=qe([_("auto"),i().int().min(1)]),x7=o({enabled:w(),motion:w(),motionHoldSec:i().optional(),audio:I(["off","sensor","level"]),audioDb:i(),audioHoldSec:i(),detection:w(),detectionHoldSec:i(),detectionClasses:y(n()).optional(),appearance:o({motionColor:n(),audioColor:n(),detectionColor:n(),thickness:i()}).optional()}),xu=I(["off","top-left","top-center","top-right","left-center","right-center","bottom-left","bottom-center","bottom-right"]),eqe=o({motionBoxes:w().optional(),motionBadge:xu.optional(),audioMeter:xu.optional(),occupancy:xu.optional(),stats:w().optional(),statsAt:xu.exclude(["off"]).optional(),viewers:xu.optional(),size:I(["small","medium","large"]).optional()}),tqe=o({cw:i(),ch:i()}),aqe=o({serverUrl:n().min(1),token:n().min(1).optional(),devices:y(i().int().nonnegative()).min(1),layout:Jze,quality:w7,showName:w(),showBadges:w(),muted:w(),paused:w(),highlight:x7.optional(),activeOnly:w().optional(),showBoxes:w().optional(),audioOnIds:y(i().int().nonnegative()).optional(),pausedIds:y(i().int().nonnegative()).optional(),snapshots:$(n(),n()).optional(),ptzIds:y(i().int().nonnegative()).optional(),overlays:$(n(),eqe).optional(),editable:w().optional(),cellPanels:w().optional(),spans:$(n(),tqe).optional(),labels:Yze}).superRefine(e7);function M7(e){if(e==null)return{ok:!1,error:"config is required"};const t=aqe.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(a=>`${a.path.join(".")||"(root)"}: ${a.message}`).join("; ")}}const nqe=1,C7=I(["auto","high","mid","low"]),iqe=qe([_("auto"),i().int().min(1)]),A7=o({enabled:w(),motion:w(),audio:I(["off","sensor","level"]),audioDb:i(),audioHoldSec:i(),detection:w(),detectionHoldSec:i(),detectionClasses:y(n()).optional(),appearance:o({motionColor:n(),audioColor:n(),detectionColor:n(),thickness:i()}).optional()}),rqe=o({devices:y(i().int().nonnegative()).min(1),layout:iqe,quality:C7,showName:w(),audioOnIds:y(i().int().nonnegative()).optional(),activeOnly:w().optional(),boxes:w().optional(),highlight:A7.optional()}),oqe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function sqe(e){let t="",a=0;for(;a<e.length;){const r=e[a];if(r===void 0)return null;let c,m;if(r<128)c=r,m=0;else if((r&224)===192)c=r&31,m=1;else if((r&240)===224)c=r&15,m=2;else if((r&248)===240)c=r&7,m=3;else return null;for(let d=1;d<=m;d++){const h=e[a+d];if(h===void 0||(h&192)!==128)return null;c=c<<6|h&63}a+=m+1,t+=String.fromCodePoint(c)}return t}function lqe(e){if(e.length%4===1)return null;const t=[];for(const c of e){const m=oqe.indexOf(c);if(m<0)return null;t.push(m)}const a=[];for(let c=0;c<t.length;c+=4){const m=t[c],d=t[c+1];if(m===void 0||d===void 0)return null;const h=t[c+2],f=t[c+3];a.push(m<<2|d>>4),h!==void 0&&a.push((d&15)<<4|h>>2),f!==void 0&&h!==void 0&&a.push((h&3)<<6|f)}const r=sqe(a);if(r===null)return null;try{return JSON.parse(r)}catch{return null}}function $x(e,t){return e.startsWith(t)?e.slice(t.length):e}function I7(e){const a=new URLSearchParams($x(e,"#")).get("t");return a!==null&&a.length>0?a:null}function cqe(e,t){return new URLSearchParams($x(e,"?")).has("v")||I7(t)!==null}function VT(e){if(e.length===0)return null;const t=[];for(const a of e.split(",")){if(!/^\d+$/.test(a))return null;t.push(Number(a))}return t}function Xi(e){return{ok:!1,error:e}}function dqe(e,t){const a=new URLSearchParams($x(e,"?")),r=a.get("mode");if(r!==null&&r!=="grid")return Xi(`unsupported mode "${r}"`);const c=a.get("v");if(c===null)return Xi("missing share-link version (v)");if(c!==String(nqe))return Xi(`unsupported share-link version "${c}"`);const m=a.get("devices"),d=m===null?null:VT(m);if(d===null||d.length===0)return Xi("invalid or missing devices list");const h=a.get("layout");let f;if(h===null||h==="auto")f="auto";else if(/^\d+$/.test(h)&&Number(h)>=1)f=Number(h);else return Xi(`invalid layout "${h}"`);const k=a.get("q")??"auto",x=C7.safeParse(k),E=x.success?x.data:"auto",R=a.get("names")??"0";if(R!=="0"&&R!=="1")return Xi(`invalid names flag "${R}"`);const T=a.get("audio");let N;if(T!==null){const K=VT(T);if(K===null)return Xi(`invalid audio list "${T}"`);N=K}const j=a.get("activeOnly");if(j!==null&&j!=="0"&&j!=="1")return Xi(`invalid activeOnly flag "${j}"`);const q=j==="1",B=a.get("boxes");if(B!==null&&B!=="0"&&B!=="1")return Xi(`invalid boxes flag "${B}"`);const F=B==="1",U=a.get("hl");let H;if(U!==null){const K=lqe(U),W=A7.safeParse(K);if(K===null||!W.success)return Xi("invalid highlight config (hl)");H=W.data}const Q={devices:[...d],layout:f,quality:E,showName:R==="1",...N!==void 0&&N.length>0?{audioOnIds:[...N]}:{},...q?{activeOnly:!0}:{},...F?{boxes:!0}:{},...H!==void 0?{highlight:H}:{}},te=rqe.safeParse(Q);return te.success?{ok:!0,params:te.data,token:I7(t)}:Xi(te.error.issues.map(K=>`${K.path.join(".")||"(root)"}: ${K.message}`).join("; "))}function uqe(e,t,a){if(!cqe(e,t))return null;const r=dqe(e,t);if(!r.ok)return{ok:!1,error:r.error};if(r.token===null)return{ok:!1,error:"share token missing — the link must end with #t=<token>"};const c=r.params,m={serverUrl:a,token:r.token,devices:[...c.devices],layout:c.layout,quality:c.quality,showName:c.showName,showBadges:!0,muted:!0,paused:!1,...c.highlight!==void 0?{highlight:c.highlight}:{},...c.activeOnly===!0?{activeOnly:!0}:{},...c.boxes===!0?{showBoxes:!0}:{},...c.audioOnIds!==void 0&&c.audioOnIds.length>0?{audioOnIds:[...c.audioOnIds]}:{}};return M7(m)}function mqe(){const e=uqe(location.search,location.hash,location.origin);return e!==null&&location.hash!==""&&history.replaceState(null,"",location.pathname+location.search),e}const sg=16/9,KT={cols:0,rows:0,cellW:0,cellH:0,wallW:0,wallH:0};function GT(e,t,a,r,c){const m=Math.min(r/e,c/t*sg),d=m/sg;return{cols:e,rows:t,cellW:m,cellH:d,wallW:Math.min(e,a)*m,wallH:t*d,empty:e*t-a}}function WT(e){return{cols:e.cols,rows:e.rows,cellW:e.cellW,cellH:e.cellH,wallW:e.wallW,wallH:e.wallH}}const ZT=1e-9;function pqe(e,t){const a=e.cellW*e.cellH,r=t.cellW*t.cellH,c=Math.max(a,r,1);return a-r>c*ZT?!0:r-a>c*ZT?!1:e.empty!==t.empty?e.empty<t.empty:e.rows<t.rows}function hqe(e,t,a,r){if(e<=0||t<=0||a<=0)return KT;if(typeof r=="number"&&r>=1){const m=Math.floor(r);return WT(GT(m,Math.ceil(e/m),e,t,a))}let c=null;for(let m=1;m<=e;m++){const d=Math.ceil(e/m);if(Math.ceil(e/d)!==m)continue;const h=GT(d,m,e,t,a);(c===null||pqe(h,c))&&(c=h)}return c===null?KT:WT(c)}function fqe(e,t){if(e.length===0)return[];const a=t>=1?Math.floor(t):e.length,r=[];for(let c=0;c<e.length;c+=a)r.push(e.slice(c,c+a));return r}function gqe(e,t){if(e.length===0||t.cellW<=0||t.cellH<=0)return[];const a=[];return fqe(e,t.cols).forEach((c,m)=>{const d=(t.wallW-c.length*t.cellW)/2;c.forEach((h,f)=>{a.push({deviceId:h,x:d+f*t.cellW,y:m*t.cellH,w:t.cellW,h:t.cellH})})}),a}const YT={wallW:0,wallH:0,placements:[]};function vqe(e,t){const a=e!==void 0&&Number.isFinite(e.cw)?Math.round(e.cw):1,r=e!==void 0&&Number.isFinite(e.ch)?Math.round(e.ch):1;return{cw:Math.min(Math.max(a,1),Math.max(t,1)),ch:Math.max(r,1)}}function yqe(e){if(e===void 0)return!1;for(const t of Object.keys(e)){const a=e[t];if(a!==void 0&&(a.cw!==1||a.ch!==1))return!0}return!1}function bqe(e,t,a){const r=new Set,c=[];let m=0;const d=(h,f,k,x)=>{for(let E=h;E<h+x;E++)for(let R=f;R<f+k;R++)if(r.has(`${E}:${R}`))return!1;return!0};for(const h of e){const{cw:f,ch:k}=vqe(t[String(h)],a),x=m+k+e.length;let E=!1;for(let R=0;R<=x&&!E;R++)for(let T=0;T+f<=a;T++)if(d(R,T,f,k)){for(let N=R;N<R+k;N++)for(let j=T;j<T+f;j++)r.add(`${N}:${j}`);c.push({deviceId:h,col:T,row:R,cw:f,ch:k}),m=Math.max(m,R+k),E=!0;break}}return{cells:c,rows:m,cols:a}}function kqe(e,t,a,r,c){const m=hqe(e.length,t,a,r);if(!yqe(c)||m.cols<=0)return{wallW:m.wallW,wallH:m.wallH,placements:gqe(e,m)};if(e.length===0||t<=0||a<=0)return YT;const d=bqe(e,c??{},m.cols);if(d.rows<=0)return YT;const h=Math.min(t/d.cols,a/d.rows*sg),f=h/sg;return{wallW:d.cells.reduce((x,E)=>Math.max(x,E.col+E.cw),0)*h,wallH:d.rows*f,placements:d.cells.map(x=>({deviceId:x.deviceId,x:x.col*h,y:x.row*f,w:x.cw*h,h:x.ch*f}))}}function E7(){const[e,t]=P.useState(null),[a,r]=P.useState("idle"),c=P.useRef(null),m=P.useRef(null),d=P.useRef(null),h=P.useRef(0),f=P.useRef(null),k=XEe(),x=JEe(),E=eRe(),R=P.useRef({start:k.mutateAsync,answer:x.mutateAsync,stop:E.mutateAsync});R.current={start:k.mutateAsync,answer:x.mutateAsync,stop:E.mutateAsync};const T=P.useCallback(()=>{if(c.current){try{c.current.close()}catch{}c.current=null}if(m.current){for(const B of m.current.getTracks())try{B.stop()}catch{}m.current=null}},[]),N=P.useCallback(async()=>{const B=d.current;if(d.current=null,T(),B)try{await R.current.stop({deviceId:B.deviceId,sessionId:B.sessionId})}catch{}},[T]),j=P.useCallback(async B=>{if(f.current===B){h.current+=1,f.current=null,t(null),r("idle"),await N();return}h.current+=1;const F=h.current;f.current=B,t(B),r("starting");let U;try{U=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}catch{F===h.current&&(f.current=null,t(null),r("error"));return}if(F!==h.current){for(const Q of U.getTracks())Q.stop();return}if(await N(),F!==h.current){for(const Q of U.getTracks())Q.stop();return}let H=null;try{m.current=U;const Q=await R.current.start({deviceId:B});if(F!==h.current){try{await R.current.stop({deviceId:B,sessionId:Q.sessionId})}catch{}T();return}d.current={deviceId:B,sessionId:Q.sessionId},H=new RTCPeerConnection,c.current=H,H.oniceconnectionstatechange=()=>{if(F!==h.current||!H)return;const K=H.iceConnectionState;K==="connected"||K==="completed"?r("talking"):(K==="failed"||K==="closed"||K==="disconnected")&&(f.current=null,t(null),r("idle"),N())};for(const K of U.getAudioTracks())H.addTrack(K,U);await H.setRemoteDescription({type:"offer",sdp:Q.sdpOffer});const te=await H.createAnswer();if(await H.setLocalDescription(te),F!==h.current)return;await R.current.answer({deviceId:B,sessionId:Q.sessionId,sdpAnswer:H.localDescription?.sdp??te.sdp??""})}catch{if(H)try{H.close()}catch{}T();const Q=d.current;if(d.current=null,Q)try{await R.current.stop({deviceId:Q.deviceId,sessionId:Q.sessionId})}catch{}F===h.current&&(f.current=null,t(null),r("error"))}},[N,T]),q=P.useCallback(B=>{if(B===null){h.current+=1,f.current=null,t(null),r("idle"),N();return}f.current!==B&&j(B)},[N,j]);return P.useEffect(()=>()=>{h.current+=1,N()},[N]),{activeMicId:e,micState:a,toggleMic:B=>{j(B)},setActiveMic:q}}const Sqe=6e3,wqe=500;function xqe(e,t){const a=P.useRef(new Map),[,r]=P.useState(0),c=t?.motion??!1,m=t?.audio??"off",d=t?.audioDb??-30,h=t?.audioHoldSec??5,f=t?.detection??!1,k=t?.detectionHoldSec??3,x=t?.detectionClasses??[],E=(N,j)=>{a.current.set(N,Date.now()+j),r(q=>q+1)};kr(Ke.MotionOnMotionChanged,N=>{if(!c)return;const j=N.data;j&&j.detected&&E(j.deviceId,Sqe)}),kr(Ke.PipelineAudioInferenceResult,N=>{if(m==="off")return;const j=N.data;if(!j)return;(m==="sensor"?j.frame.detections.length>0:(j.frame.level?.dbfs??Number.NEGATIVE_INFINITY)>=d)&&E(j.deviceId,h*1e3)}),kr(Ke.DetectionResult,N=>{if(!f)return;const j=N.data;if(!j)return;j.frame.detections.some(B=>x.length===0||x.includes(B.macroClass))&&E(j.frame.deviceId,k*1e3)}),P.useEffect(()=>{const N=setInterval(()=>r(j=>j+1),wqe);return()=>clearInterval(N)},[]);const R=Date.now(),T=new Set;for(const N of e){const j=a.current.get(N);j!==void 0&&R<j&&T.add(N)}return T}function Mqe(e){return{type:"tileOpen",deviceId:e}}function Cqe(e){return{type:"audioToggle",deviceId:e}}function Aqe(e){return{type:"pauseToggle",deviceId:e}}function Iqe(e){return{type:"ptzOpen",deviceId:e}}function Eqe(e,t){return{type:"cellPanelOpen",deviceId:e,panel:t}}function Rqe(e){return{type:"tileRemove",deviceId:e}}function Tqe(e,t,a){return{type:"tileResize",deviceId:e,cw:t,ch:a}}function R7(e,t,a){return{type:"state",state:e,...t!==void 0?{message:t}:{},...a!==void 0?{commands:a}:{}}}function _qe(e){return{type:"layout",tiles:e}}function vr(e){qt(e)}const Pqe=["top-left","top-center","top-right","left-center","right-center","bottom-left","bottom-center","bottom-right"];function sk(e){return typeof e=="string"&&Pqe.includes(e)}const Nqe={"top-left":{top:8,left:8},"top-center":{top:8,left:0,right:0,justifyContent:"center"},"top-right":{top:8,right:8},"left-center":{left:8,top:0,bottom:0,alignItems:"center"},"right-center":{right:8,top:0,bottom:0,alignItems:"center"},"bottom-left":{bottom:8,left:8},"bottom-center":{bottom:8,left:0,right:0,justifyContent:"center"},"bottom-right":{bottom:8,right:8}};function Zg(e){return{position:"absolute",display:"flex",...Nqe[e]}}const T7=[-60,-53,-46,-39,-32,-24],Oqe=T7.length,lk=["#22c55e","#84cc16","#eab308","#f59e0b","#f97316","#ef4444"];function Dqe(e){const t=Math.min(Math.max(0,e),lk.length-1);return lk[t]??lk[0]}function jqe(e){if(e===null||!Number.isFinite(e))return 0;let t=0;for(const a of T7)e>=a&&(t+=1);return t}function zqe(e){if(e==="off")return null;const t=e.split("-"),a=t.includes("top")?"top":t.includes("bottom")?"bottom":"center",r=t.includes("left")?"left":t.includes("right")?"right":"center";return a!=="center"&&r!=="center"?"compact":r==="center"?"horizontal":"vertical"}const XT=[8,11,14,17,21,26],ck={horizontal:{width:8,height:16},vertical:{width:24,height:7},compactWidth:4};function qqe(e,t){if(e==="vertical")return ck.vertical;if(e==="horizontal")return ck.horizontal;const a=XT[t]??XT[0];return{width:ck.compactWidth,height:a}}function Lqe(e){const t=Array.from({length:Oqe},(a,r)=>r);return e==="vertical"?[...t].reverse():t}function al(e){return typeof e=="object"&&e!==null}function Bqe(e){if(!al(e))return[];if(e.detected!==!0)return[];const t=typeof e.frameWidth=="number"?e.frameWidth:0,a=typeof e.frameHeight=="number"?e.frameHeight:0;if(t<=0||a<=0)return[];const r=e.regions;if(!Array.isArray(r))return[];const c=[];for(const m of r){if(!al(m)||!al(m.bbox))continue;const{x:d,y:h,w:f,h:k}=m.bbox;typeof d!="number"||typeof h!="number"||typeof f!="number"||typeof k!="number"||!(f>0)||!(k>0)||c.push({x:d/t,y:h/a,w:f/t,h:k/a,pixelCount:typeof m.pixelCount=="number"?m.pixelCount:0})}return c}function Fqe(e){return!Number.isFinite(e)||e<=0?.08:Math.min(.28,.08+e/4e3*.28)}function JT(e){if(!al(e))return[];const t=al(e.frame)?e.frame.byClass:void 0,a=al(t)?t:e.byClass;if(!al(a))return[];const r=[];for(const[c,m]of Object.entries(a))typeof m!="number"||!Number.isFinite(m)||m<=0||r.push({className:c,count:Math.round(m)});return r.sort((c,m)=>m.count-c.count||c.className.localeCompare(m.className))}function $qe(e,t,a){if(a<=0)return 0;const r=t-e;return r<=0?0:Math.round(r*1e3/a)}function Uqe(e){if(e===null)return"—";const t=[e.resolution,`${e.fps}fps`];return e.dropped>0&&t.push(`${e.dropped} dropped`),t.join(" · ")}const Hqe="medium",Qqe=11,Vqe={small:.012,medium:.018,large:.028},Kqe={small:.5,medium:.6,large:.75},Gqe=2;function Wqe(e,t){if(!Number.isFinite(e)||e<=0)return 1;const a=e*Vqe[t]/Qqe;return Math.min(Gqe,Math.max(Kqe[t],a))}const _7="--ov";function ba(e){return`calc(${e}px * var(${_7}, 1))`}function Zqe(e){return{[_7]:e}}const Yqe=1e4;function Xqe(e){return typeof e=="object"&&e!==null}function Jqe(e){if(!Array.isArray(e))return null;const t={};for(const a of e){if(!Xqe(a))continue;const{deviceId:r,viewers:c}=a;typeof r!="number"||!Number.isInteger(r)||r<0||typeof c!="number"||!Number.isFinite(c)||c<1||(t[r]=Math.floor(c))}return t}function e6e(e,t){return e===null?null:e[t]??0}async function t6e(e){if(typeof e!="object"||e===null)return null;const t=Reflect.get(e,"streamBroker");if(typeof t!="object"||t===null)return null;const a=Reflect.get(t,"getLiveViewerCounts");if(typeof a!="object"||a===null)return null;const r=Reflect.get(a,"query");if(typeof r!="function")return null;try{return Jqe(await r.call(a))}catch{return null}}class a6e{constructor(t){this.deps=t}deps;counts=null;listeners=new Set;timer=null;getSnapshot=()=>this.counts;subscribe=t=>(this.listeners.add(t),this.listeners.size===1&&this.start(),()=>{this.listeners.delete(t),this.listeners.size===0&&this.stop()});get isRunning(){return this.timer!==null}start(){this.tick(),this.timer=this.deps.setInterval(()=>{this.tick()},Yqe)}stop(){this.timer!==null&&this.deps.clearInterval(this.timer),this.timer=null,this.counts=null}async tick(){const t=await this.deps.fetchCounts();if(this.listeners.size!==0){this.counts=t;for(const a of this.listeners)a()}}}const n6e=1200,i6e=1e3;function r6e({deviceId:e}){const[t,a]=P.useState([]),r=P.useRef(void 0);return kr(Ke.MotionAnalysis,c=>{const m=c.data;!m||m.deviceId!==e||(a(Bqe(m)),r.current&&clearTimeout(r.current),r.current=setTimeout(()=>a([]),n6e))}),P.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[e]),t.length===0?null:v.jsx("div",{style:{position:"absolute",inset:0,overflow:"hidden",pointerEvents:"none"},children:t.map((c,m)=>v.jsx("div",{style:{position:"absolute",left:`${c.x*100}%`,top:`${c.y*100}%`,width:`${c.w*100}%`,height:`${c.h*100}%`,border:"1px dashed #f59e0b",borderRadius:2,background:`rgba(245,158,11,${Fqe(c.pixelCount)})`}},`${c.x}:${c.y}:${c.w}:${c.h}:${m}`))})}function o6e({deviceId:e,anchor:t}){const[a,r]=P.useState(null);kr(Ke.PipelineAudioInferenceResult,f=>{const k=f.data;!k||k.deviceId!==e||r(k.frame.level?.dbfs??null)});const c=jqe(a),m=zqe(t);if(m===null)return null;const d=m==="horizontal",h=m==="vertical";return v.jsx("div",{style:{...Zg(t),pointerEvents:"none"},children:v.jsx("span",{className:"cs-chip",style:{display:"flex",flexDirection:h?"column":"row",alignItems:h||d?"center":"flex-end",gap:ba(h||d?4:3),padding:d||h?`${ba(4)} ${ba(8)}`:`${ba(3)} ${ba(6)}`,borderRadius:ba(8)},children:Lqe(m).map(f=>{const k=f<c,x=qqe(m,f);return v.jsx("span",{style:{width:ba(x.width),height:ba(x.height),borderRadius:ba(2),background:k?Dqe(f):"#71717a",opacity:k?1:.35}},f)})})})}function s6e(e,t){if(typeof e!="object"||e===null)return null;const a=Reflect.get(e,"zoneAnalytics");if(typeof a!="object"||a===null)return null;const r=Reflect.get(a,"getCurrentSnapshot");if(typeof r!="object"||r===null)return null;const c=Reflect.get(r,"query");if(typeof c!="function")return null;const m=c.call(r,{deviceId:t});return m instanceof Promise?m:Promise.resolve(m)}function l6e({system:e,deviceId:t,anchor:a}){const[r,c]=P.useState([]);return P.useEffect(()=>{let m=!1;const d=s6e(e.trpcClient,t);if(d!==null)return d.then(h=>{m||c(JT(h))}).catch(()=>{m||c([])}),()=>{m=!0}},[e,t]),kr(Ke.ZoneAnalyticsOccupancyChanged,m=>{const d=m.data;d.deviceId===t&&c(JT(d))}),r.length===0?null:v.jsx("div",{style:{...Zg(a),gap:ba(4),pointerEvents:"none"},children:r.slice(0,4).map(m=>v.jsx("span",{className:"cs-chip",style:{padding:`${ba(2)} ${ba(6)}`,borderRadius:ba(6),fontSize:ba(11),fontWeight:700,fontFamily:"system-ui, sans-serif",whiteSpace:"nowrap"},children:`${m.className} ${m.count}`},m.className))})}const c6e="top-right";function d6e({containerRef:e,anchor:t}){const[a,r]=P.useState(null),c=P.useRef(null);return P.useEffect(()=>{const m=()=>{const h=e.current?.querySelector("video");if(!h){r(null);return}const f=typeof h.getVideoPlaybackQuality=="function"?h.getVideoPlaybackQuality():null,k=f?.totalVideoFrames??0,x=Date.now(),E=c.current;c.current={frames:k,at:x},r({resolution:h.videoWidth>0?`${h.videoWidth}x${h.videoHeight}`:"—",fps:E===null?0:$qe(E.frames,k,x-E.at),dropped:f?.droppedVideoFrames??0})};m();const d=setInterval(m,i6e);return()=>{clearInterval(d),c.current=null}},[e]),v.jsx("div",{style:{...Zg(t),pointerEvents:"none"},children:v.jsx("div",{className:"cs-chip",style:{maxWidth:"100%",padding:`${ba(2)} ${ba(6)}`,borderRadius:ba(6),fontSize:ba(10),fontWeight:600,fontFamily:"system-ui, sans-serif",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",pointerEvents:"none"},children:Uqe(a)})})}const e_=new WeakMap;function u6e(e){const t=e_.get(e);if(t)return t;const a=new a6e({fetchCounts:()=>t6e(e.trpcClient),setInterval:(r,c)=>setInterval(r,c),clearInterval:r=>{r!=null&&clearInterval(r)}});return e_.set(e,a),a}function m6e(e,t){const a=u6e(e),r=P.useSyncExternalStore(a.subscribe,a.getSnapshot);return e6e(r,t)}function p6e({system:e,deviceId:t,anchor:a}){const r=m6e(e,t);return r===null||r<1?null:v.jsx("div",{style:{...Zg(a),pointerEvents:"none"},"data-testid":"tile-viewers",children:v.jsxs("span",{role:"img","aria-label":`${r} watching live`,className:"cs-chip",style:{display:"flex",alignItems:"center",gap:ba(4),padding:`${ba(2)} ${ba(6)}`,borderRadius:ba(6),fontSize:ba(11),fontWeight:700,fontFamily:"system-ui, sans-serif",fontVariantNumeric:"tabular-nums",whiteSpace:"nowrap"},children:[v.jsxs("svg",{style:{width:ba(13),height:ba(13)},viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[v.jsx("path",{d:"M2.06 12.35a1 1 0 0 1 0-.7C3.4 8.4 7.3 5 12 5s8.6 3.4 9.94 6.65a1 1 0 0 1 0 .7C20.6 15.6 16.7 19 12 19s-8.6-3.4-9.94-6.65"}),v.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),r]})})}const h6e=1e4,t_=1e3,a_=[0,5e3,15e3,3e4],f6e=4;function g6e(e){const t=Math.max(0,Math.min(e,a_.length-1));return a_[t]??0}function v6e(e){return!e.playing||e.lastFrameAt===null?!1:e.nowMs-e.lastFrameAt>=e.stallMs}function P7(e){const{containerRef:t,playing:a,onRecover:r,stallMs:c=h6e}=e,m=e.now??Date.now,[d,h]=P.useState({recovering:!1,attempts:0}),f=P.useRef(null),k=P.useRef(0),x=P.useRef(0),E=P.useRef(r);E.current=r;const R=P.useRef(m);R.current=m;const T=P.useCallback(()=>{const N=R.current(),j=f.current;f.current=N,k.current>0&&j!==null&&N-j<c&&(k.current=0,h({recovering:!1,attempts:0}))},[c]);return P.useEffect(()=>{if(!a){f.current=null;return}const j=t.current?.querySelector("video");if(!j)return;let q=!1,B=null;if(typeof j.requestVideoFrameCallback=="function"){const H=()=>{q||(T(),B=j.requestVideoFrameCallback?.(H)??null)};return B=j.requestVideoFrameCallback(H),()=>{q=!0,B!==null&&j.cancelVideoFrameCallback?.(B)}}let F=j.currentTime;const U=setInterval(()=>{if(q)return;const H=j.currentTime;H!==F&&(F=H,T())},t_);return()=>{q=!0,clearInterval(U)}},[a,t,T]),P.useEffect(()=>{if(!a)return;const N=setInterval(()=>{const j=R.current();if(j<x.current||!v6e({lastFrameAt:f.current,nowMs:j,stallMs:c,playing:a})||k.current>=f6e)return;const q=k.current;k.current=q+1,f.current=j,x.current=j+g6e(q+1)+c,h({recovering:!0,attempts:q+1}),E.current()},t_);return()=>clearInterval(N)},[a,c]),d}const y6e=300,b6e=130,k6e=["devices","viewOptions"],S6e={inline:k6e,overflow:!1},w6e={inline:[],overflow:!0};function x6e(e,t){return e>=y6e&&t>=b6e?S6e:w6e}const M6e=120,C6e=68;function A6e(e,t,a){return e&&t>=M6e&&a>=C6e}const I6e=16/9,E6e={left:0,top:0,width:0,height:0},n_=.5;function R6e(e,t,a){if(!(e>0)||!(t>0))return E6e;const r={left:0,top:0,width:e,height:t};if(!Number.isFinite(a))return r;const c=Math.min(e,t*a),m=c/a;return e-c<n_&&t-m<n_?r:{left:(e-c)/2,top:(t-m)/2,width:c,height:m}}const T6e=500;function N7(e,t,a){const{motion:r,detection:c}=rDe(e.trpcClient,t),m=P.useRef(0),d=P.useRef(0),h=P.useRef(0),f=P.useRef(!1),[,k]=P.useState(0),x=a?.audio??"off",E=a?.audioDb??-30,R=a?.audioHoldSec??5,T=a?.motionHoldSec??0,N=a?.detectionHoldSec??3,j=a?.detectionClasses??[],q=j.join(",");kr(Ke.MotionOnMotionChanged,U=>{const H=U.data;!H||H.deviceId!==t||!a?.motion||(H.detected===!0?(h.current=Date.now()+Math.max(1,T)*1e3,f.current=!0,k(Q=>Q+1)):H.detected===!1&&f.current&&(h.current=Date.now()+T*1e3,f.current=!1,k(Q=>Q+1)))}),kr(Ke.PipelineAudioInferenceResult,U=>{const H=U.data;if(!H||H.deviceId!==t||x==="off")return;(x==="sensor"?H.frame.detections.length>0:(H.frame.level?.dbfs??Number.NEGATIVE_INFINITY)>=E)&&(m.current=Date.now()+R*1e3,k(te=>te+1))}),P.useEffect(()=>{if(!c)return;c.detections.some(H=>j.length===0||j.includes(H.macroClass))&&(d.current=Date.now()+N*1e3,k(H=>H+1))},[c,N,q]),P.useEffect(()=>{const U=r!==null;(U||f.current)&&(h.current=Date.now()+T*1e3,U||k(H=>H+1)),f.current=U},[r,T]);const B=a?.enabled===!0;if(P.useEffect(()=>{if(!B)return;const U=setInterval(()=>k(H=>H+1),T6e);return()=>clearInterval(U)},[B]),!a?.enabled)return null;const F=Date.now();return a.detection&&F<d.current?"detection":x!=="off"&&F<m.current?"audio":a.motion&&(r!==null||F<h.current)?"motion":null}function Lc(e,t){return ag(t,e)}const _6e=2500;function P6e(e,t=ng()){return ag(t,e)}function Uh(e){return e<0?0:e>1?1:e}function N6e(e){if(e.width<=0||e.height<=0)return[];const t=[];for(const a of e.detections){const{bbox:r}=a,c=Uh(r.x/e.width),m=Uh(r.y/e.height),d=Uh((r.x+r.width)/e.width),h=Uh((r.y+r.height)/e.height);d<=c||h<=m||t.push({label:a.macroClass,score:a.score,x1:c,y1:m,x2:d,y2:h})}return t}function O6e({deviceId:e}){const t=pd(),[a,r]=P.useState([]),c=P.useRef(void 0);return kr(Ke.DetectionResult,m=>{const d=m.data;!d||d.frame.deviceId!==e||(r(N6e(d.frame)),c.current&&clearTimeout(c.current),c.current=setTimeout(()=>r([]),_6e))}),P.useEffect(()=>()=>{c.current&&clearTimeout(c.current),r([])},[e]),a.length===0?null:v.jsx("div",{style:{position:"absolute",inset:0,overflow:"hidden",pointerEvents:"none"},children:a.map((m,d)=>{const h=P6e(m.label,t),f=Math.round(m.score*100);return v.jsx("div",{style:{position:"absolute",left:`${m.x1*100}%`,top:`${m.y1*100}%`,width:`${(m.x2-m.x1)*100}%`,height:`${(m.y2-m.y1)*100}%`,border:`2px solid ${h}`,borderRadius:3},children:v.jsx("span",{style:{position:"absolute",left:-2,bottom:"100%",background:h,color:Yt.dark.onPicture,fontSize:10,fontWeight:700,fontFamily:"system-ui, sans-serif",lineHeight:"14px",padding:"0 4px",borderRadius:3,whiteSpace:"nowrap"},children:`${m.label} ${f}%`})},`${m.label}-${d}`)})})}function D6e(e,t,a,r){const c=Number.isFinite(e)&&e>0?e:0,m=Number.isFinite(t)&&t>0?t:0;if(!Number.isFinite(a)||!Number.isFinite(r)||a<=0||r<=0)return{width:c,height:m};const d=Math.min(c/a,m/r);return{width:a*d,height:r*d}}function j6e(e,t,a){return!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(a)?0:Math.max(0,(a*t-e)/2)}function i_(e,t,a,r){if(!Number.isFinite(e))return 0;const c=j6e(t,a,r);return Math.max(-c,Math.min(c,e))}function z6e(e){"worklet";const{viewportWidth:t,viewportHeight:a,contentAspect:r}=e;if(!Number.isFinite(t)||!Number.isFinite(a)||!Number.isFinite(r)||t<=0||a<=0||r<=0)return 1;const c=t/a/r;return c>=1?c:1/c}const r_=.01;function q6e(e){"worklet";const{minScale:t,maxScale:a,cover:r,fallbackStep:c}=e;if((Number.isFinite(e.current)?e.current:t)>t+r_)return{kind:"fit"};const d=Number.isFinite(r)&&r>t+r_?r:c;return{kind:"zoom",scale:Math.max(t,Math.min(a,d))}}const o_=4,L6e=2,s_=8,B6e=300;function l_(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function c_(e){return e>1?"none":"pan-y"}function F6e({children:e,onTap:t}){const a=P.useRef(null),r=P.useRef(null),c=P.useRef(new Map),m=P.useRef(1),d=P.useRef(0),h=P.useRef(0),f=P.useRef(null),k=P.useRef(null),x=P.useRef(0),E=()=>{const U=r.current;U&&(U.style.transform=`translate(${d.current}px, ${h.current}px) scale(${m.current})`);const H=a.current;H&&(H.style.touchAction=c_(m.current))},R=()=>{const U=r.current?.querySelector("video")??null,H=U?null:r.current?.querySelector("img")??null;return{iw:U?.videoWidth??H?.naturalWidth??0,ih:U?.videoHeight??H?.naturalHeight??0}},T=()=>{const U=a.current?.getBoundingClientRect();if(!U||U.width<=0||U.height<=0)return;const{iw:H,ih:Q}=R(),te=D6e(U.width,U.height,H,Q);d.current=i_(d.current,U.width,te.width,m.current),h.current=i_(h.current,U.height,te.height,m.current)},N=()=>{m.current=1,d.current=0,h.current=0,E()},j=(U,H)=>{const Q=a.current?.getBoundingClientRect();if(!Q||Q.width<=0||Q.height<=0)return;const{iw:te,ih:K}=R(),W=q6e({current:m.current,minScale:1,maxScale:o_,cover:z6e({viewportWidth:Q.width,viewportHeight:Q.height,contentAspect:te>0&&K>0?te/K:Number.NaN}),fallbackStep:L6e});if(W.kind==="fit"){N();return}const oe=W.scale;m.current=oe,d.current=(U-Q.left-Q.width/2)*(1-oe),h.current=(H-Q.top-Q.height/2)*(1-oe),T(),E()},q=U=>{try{U.currentTarget.setPointerCapture(U.pointerId)}catch{}if(c.current.set(U.pointerId,{x:U.clientX,y:U.clientY}),c.current.size===2){const H=[...c.current.values()],Q=H[0],te=H[1];Q&&te&&(f.current={dist:l_(Q,te),scale:m.current,cx:(Q.x+te.x)/2,cy:(Q.y+te.y)/2,tx:d.current,ty:h.current}),k.current=null}else c.current.size===1&&(k.current={x:U.clientX,y:U.clientY,tx:d.current,ty:h.current,moved:!1})},B=U=>{if(!c.current.has(U.pointerId))return;if(c.current.set(U.pointerId,{x:U.clientX,y:U.clientY}),c.current.size>=2&&f.current){const Q=[...c.current.values()],te=Q[0],K=Q[1];if(!te||!K)return;const W=l_(te,K);f.current.dist>0&&(m.current=Math.max(1,Math.min(o_,f.current.scale*(W/f.current.dist))));const oe=(te.x+K.x)/2,he=(te.y+K.y)/2;d.current=f.current.tx+(oe-f.current.cx),h.current=f.current.ty+(he-f.current.cy),T(),E();return}const H=k.current;if(c.current.size===1&&H){const Q=U.clientX-H.x,te=U.clientY-H.y;(Math.abs(Q)>s_||Math.abs(te)>s_)&&(H.moved=!0),m.current>1&&(d.current=H.tx+Q,h.current=H.ty+te,T(),E())}},F=U=>{const H=c.current.size===1,Q=k.current;if(c.current.delete(U.pointerId),c.current.size<2&&(f.current=null),c.current.size===0&&(k.current=null,H&&Q&&!Q.moved)){const te=Date.now();te-x.current<B6e?(x.current=0,j(U.clientX,U.clientY)):(x.current=te,t())}};return v.jsx("div",{ref:a,style:{position:"absolute",inset:0,overflow:"hidden",touchAction:c_(1)},onPointerDown:q,onPointerMove:B,onPointerUp:F,onPointerCancel:F,children:v.jsx("div",{ref:r,style:{width:"100%",height:"100%",transformOrigin:"center center",willChange:"transform"},children:e})})}function $6e(e,t){if(t==null||t.length===0)return null;if(/^https?:\/\//i.test(t))return t;const a=e.replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${a}${r}`}function U6e(e,t){const a=t[0];return a===void 0?null:$6e(e,a.url)}function H6e(e,t){return{handleOffer:(a,r,c)=>e(t,a,r,c),reoffer:(a,r,c,m)=>e(c,r,a,m)}}const Q6e=3500;function V6e(e){return e==="auto"?{kind:"adaptive"}:{kind:"profile",profile:e}}function K6e({system:e,deviceId:t,name:a,online:r,quality:c,muted:m,paused:d,showName:h,audioActive:f,micActive:k,onTogglePause:x,onToggleAudio:E,onToggleMic:R,onOpen:T,ptzSupported:N,onPtz:j,cellW:q,cellH:B,onCellPanel:F,highlight:U,showBoxes:H,overlay:Q,reconnectSignal:te,onStall:K,posterUrl:W,labels:oe=og,editable:he,span:Ae,onRemove:we,onResize:Ee,probeAuthToken:Ie}){const Me=pd(),{handleOffer:Y,getIceServers:de,addIceCandidate:Re,getIceCandidates:Qe,closeSession:re,getSessionState:V,getSessionDebug:ie,applyDownlinkProbe:fe}=IL(e.trpcClient,t),be=N7(e,t,U),ee=P.useRef(null),[Se,_e]=P.useState(0),[Be,Ge]=P.useState("idle"),Ft=P7({containerRef:ee,playing:Be==="playing"&&!d,onRecover:()=>{_e(ct=>ct+1),K?.(t)}}),[Ot,wt]=P.useState(void 0);P.useEffect(()=>{if(W||d)return;let ct=!1;const Ut=q!==void 0&&q>0?Math.round(q):void 0;return e.trpcClient.snapshot.getSnapshotLinks.query({targets:[{deviceId:t,...Ut!==void 0?{width:Ut}:{}}]}).then(La=>{if(ct)return;const Sa=U6e(e.serverUrl,La??[]);Sa!==null&&wt(Sa)}).catch(()=>{}),()=>{ct=!0}},[W,d,e,t,q]);const sa=W??Ot,nt=P.useMemo(()=>V6e(c),[c]),za=`grid:${t}:${c}`,ft=P.useMemo(()=>H6e(Y,nt),[Y,nt]),[lt,Dt]=P.useState(!1),bt=P.useRef(null),ve=()=>{bt.current&&clearTimeout(bt.current),bt.current=setTimeout(()=>Dt(!1),Q6e)},Fe=()=>{Dt(!0),ve()},Le=()=>{Dt(ct=>{const Ut=!ct;return Ut&&ve(),Ut})},ot=x6e(q??0,B??0),He=ct=>{ct.stopPropagation(),Fe()},ea=q!==void 0&&B!==void 0&&q>0&&B>0,$t=R6e(q??0,B??0,I6e),ze=ea?{position:"absolute",left:$t.left,top:$t.top,width:$t.width,height:$t.height}:{position:"absolute",inset:0},st=Math.max(1,Math.round(Ae?.cw??1)),Lt=Math.max(1,Math.round(Ae?.ch??1)),Kt=ea&&q!==void 0?q/st:0,qa=ea&&B!==void 0?B/Lt:0,fn=A6e(he===!0,q??0,B??0);return P.useEffect(()=>()=>{bt.current&&clearTimeout(bt.current)},[]),v.jsxs("div",{ref:ee,"data-stall-recovering":Ft.recovering?"true":void 0,style:{position:"relative",width:"100%",height:"100%",background:Yt.dark.mediaBlack},children:[v.jsxs("div",{style:ze,children:[v.jsx(F6e,{onTap:Le,children:d?v.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:Yt.dark.onMedia},children:v.jsx(u_,{size:28})}):v.jsx(AL,{applyDownlinkProbe:fe,serverUrl:e.serverUrl,streamKey:za,autoPlay:!0,muted:m,showControls:!1,className:"w-full h-full",handleOffer:ft.handleOffer,reoffer:ft.reoffer,getSessionState:V,getSessionDebug:ie,getIceServers:de,addIceCandidate:Re,getIceCandidates:Qe,closeSession:re,reconnectSignal:(te??0)+Se,onStateChange:Ge,posterUrl:sa,probeAuthToken:Ie,onClientNetworkSample:c==="auto"?ct=>{e.trpcClient.networkQuality.reportClientStats.mutate({deviceId:t,...ct}).catch(()=>{})}:void 0},za)}),H&&!d?v.jsx(O6e,{deviceId:t}):null,Q?.motionBoxes===!0&&!d?v.jsx(r6e,{deviceId:t}):null]}),v.jsxs("div",{style:{...ze,pointerEvents:"none",...Zqe(Wqe(ea?$t.width:q??0,Q?.size??Hqe))},children:[sk(Q?.audioMeter)&&!d?v.jsx(o6e,{deviceId:t,anchor:Q.audioMeter}):null,sk(Q?.occupancy)&&!d?v.jsx(l6e,{system:e,deviceId:t,anchor:Q.occupancy}):null,Q?.stats===!0&&!d?v.jsx(d6e,{containerRef:ee,anchor:Q.statsAt??c6e}):null,sk(Q?.viewers)&&!d?v.jsx(p6e,{system:e,deviceId:t,anchor:Q.viewers}):null]}),be&&(()=>{const ct=U?.appearance,Ut=be==="motion"?ct?.motionColor??Lc("motion",Me):be==="audio"?ct?.audioColor??Lc("audio",Me):ct?.detectionColor??Lc("detection",Me),La=ct?.thickness??3;return v.jsx("div",{style:{position:"absolute",inset:0,border:`${La}px solid ${Ut}`,boxShadow:`inset 0 0 12px ${Ut}`,pointerEvents:"none"}})})(),(h||lt)&&v.jsxs("div",{className:"cs-glass cs-fade","data-on":h||lt,style:{position:"absolute",left:0,right:0,top:0,display:"flex",alignItems:"center",gap:6,padding:"4px 8px",fontSize:12,fontWeight:600,fontFamily:"system-ui, sans-serif",pointerEvents:"none",opacity:h||lt?1:0},children:[v.jsx("span",{style:{width:8,height:8,borderRadius:4,background:r?Yt.dark.presence:Yt.dark.presenceOff}}),v.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a})]}),v.jsxs("div",{className:"cs-fade","data-on":lt,style:{position:"absolute",inset:0,opacity:lt?1:0,pointerEvents:"none"},children:[v.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"},children:v.jsx(Xo,{label:d?oe.play:oe.pause,big:!0,enabled:lt,onClick:ct=>{He(ct),x(t)},children:d?v.jsx(u_,{size:22}):v.jsx(G6e,{size:22})})}),v.jsxs("div",{style:{position:"absolute",left:8,bottom:8,display:"flex",gap:8,pointerEvents:"none"},children:[v.jsx(Xo,{label:f?oe.mute:oe.listen,active:f,enabled:lt,onClick:ct=>{He(ct),E(t)},children:f?v.jsx(W6e,{size:18}):v.jsx(Z6e,{size:18})}),v.jsx(Xo,{label:k?oe.stopTalk:oe.talk,active:k,enabled:lt,onClick:ct=>{He(ct),R(t)},children:v.jsx(Y6e,{size:18,muted:!k})}),N&&j&&(!F||!ot.overflow)?v.jsx(Xo,{label:oe.ptz,enabled:lt,onClick:ct=>{He(ct),j(t)},children:v.jsx(nLe,{size:18})}):null,F?ot.inline.map(ct=>v.jsx(Xo,{label:ct==="devices"?oe.linkedDevices:oe.viewOptions,enabled:lt,onClick:Ut=>{He(Ut),F(t,ct)},children:ct==="devices"?v.jsx(J6e,{size:18}):v.jsx(eLe,{size:18})},ct)):null,F&&ot.overflow?v.jsx(Xo,{label:oe.moreActions,enabled:lt,onClick:ct=>{He(ct),F(t,"actions")},children:v.jsx(tLe,{size:18})}):null]}),v.jsx("div",{style:{position:"absolute",right:8,bottom:8,pointerEvents:"none"},children:v.jsx(Xo,{label:oe.open,enabled:lt,onClick:ct=>{He(ct),T(t)},children:v.jsx(X6e,{size:18})})}),fn&&we?v.jsx("div",{style:{position:"absolute",right:8,top:8,pointerEvents:"none"},children:v.jsx(Xo,{label:oe.removeFromView,enabled:lt,onClick:ct=>{He(ct),we(t)},children:v.jsx(aLe,{size:18})})}):null,fn&&Ee?v.jsxs(v.Fragment,{children:[v.jsx(d_,{axis:"x",label:oe.resizeWidth,enabled:lt,track:Kt,span:st,onSpan:ct=>{Fe(),Ee(t,ct,Lt)}}),v.jsx(d_,{axis:"y",label:oe.resizeHeight,enabled:lt,track:qa,span:Lt,onSpan:ct=>{Fe(),Ee(t,st,ct)}})]}):null]})]})}function d_({axis:e,label:t,enabled:a,track:r,span:c,onSpan:m}){const d=P.useRef(null),h=f=>e==="x"?f.clientX:f.clientY;return v.jsx("div",{className:"cs-glass cs-grip",role:"separator","aria-label":t,"aria-orientation":e==="x"?"vertical":"horizontal",onPointerDown:f=>{f.stopPropagation(),f.currentTarget.setPointerCapture(f.pointerId),d.current={origin:h(f),base:c}},onPointerMove:f=>{if(d.current===null||!(r>0))return;f.stopPropagation();const k=Math.round((h(f)-d.current.origin)/r),x=Math.max(1,d.current.base+k);x!==c&&m(x)},onPointerUp:f=>{d.current=null,f.currentTarget.hasPointerCapture(f.pointerId)&&f.currentTarget.releasePointerCapture(f.pointerId)},onPointerCancel:()=>{d.current=null},style:{position:"absolute",...e==="x"?{right:0,top:"50%",width:14,height:48,transform:"translateY(-50%)"}:{bottom:0,left:"50%",width:48,height:14,transform:"translateX(-50%)"},borderRadius:7,cursor:e==="x"?"ew-resize":"ns-resize",touchAction:"none",pointerEvents:a?"auto":"none"}})}function Xo({children:e,label:t,onClick:a,big:r=!1,active:c=!1,enabled:m=!0}){const d=r?52:40;return v.jsx("button",{type:"button","aria-label":t,onClick:a,className:"cs-glass cs-glass-btn","data-active":c,style:{width:d,height:d,borderRadius:d/2,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,WebkitTapHighlightColor:"transparent",pointerEvents:m?"auto":"none"},children:e})}const Ss={fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};function u_({size:e}){return v.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",children:v.jsx("polygon",{points:"6 4 20 12 6 20 6 4",fill:"currentColor"})})}function G6e({size:e}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",children:[v.jsx("rect",{x:"6",y:"4",width:"4",height:"16",fill:"currentColor"}),v.jsx("rect",{x:"14",y:"4",width:"4",height:"16",fill:"currentColor"})]})}function W6e({size:e}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",...Ss,children:[v.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),v.jsx("path",{d:"M19.07 4.93a10 10 0 010 14.14M15.54 8.46a5 5 0 010 7.07"})]})}function Z6e({size:e}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",...Ss,children:[v.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),v.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),v.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})}function Y6e({size:e,muted:t}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",...Ss,children:[v.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),v.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2M12 19v4"}),t&&v.jsx("line",{x1:"3",y1:"3",x2:"21",y2:"21"})]})}function X6e({size:e}){return v.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",...Ss,children:v.jsx("path",{d:"M15 3h6v6M21 3l-9 9M21 14v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5"})})}function J6e({size:e}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",...Ss,children:[v.jsx("path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5A5.5 5.5 0 1 0 7.5 11.5c.8.8 1.3 1.5 1.5 2.5"}),v.jsx("path",{d:"M9 18h6M10 22h4"})]})}function eLe({size:e}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",...Ss,children:[v.jsx("path",{d:"M3 6h18M3 12h18M3 18h18"}),v.jsx("circle",{cx:"8",cy:"6",r:"2"}),v.jsx("circle",{cx:"16",cy:"12",r:"2"}),v.jsx("circle",{cx:"10",cy:"18",r:"2"})]})}function tLe({size:e}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",children:[v.jsx("circle",{cx:"5",cy:"12",r:"2",fill:"currentColor"}),v.jsx("circle",{cx:"12",cy:"12",r:"2",fill:"currentColor"}),v.jsx("circle",{cx:"19",cy:"12",r:"2",fill:"currentColor"})]})}function aLe({size:e}){return v.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",...Ss,children:v.jsx("path",{d:"M18 6L6 18M6 6l12 12"})})}function nLe({size:e}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",...Ss,children:[v.jsx("path",{d:"M12 2v20M2 12h20"}),v.jsx("path",{d:"M12 2l-3 3M12 2l3 3M12 22l-3-3M12 22l3-3M2 12l3-3M2 12l3 3M22 12l-3-3M22 12l-3 3"})]})}function iLe({wall:e,renderTile:t}){return v.jsx("div",{style:{position:"relative",width:e.wallW,height:e.wallH},children:e.placements.map(a=>v.jsx("div",{"data-device-id":a.deviceId,style:{position:"absolute",left:a.x,top:a.y,width:a.w,height:a.h},children:t(a.deviceId,a.w,a.h)},a.deviceId))})}function rLe(e){return{box:e,hostOwned:!1}}function oLe(e,t){return{box:t,hostOwned:!0}}function sLe(e,t){return e.hostOwned||!(t.w>0&&t.h>0)||t.w===e.box.w&&t.h===e.box.h?e:{box:t,hostOwned:!1}}function m_(){return{w:window.innerWidth,h:window.innerHeight}}function Ux(){const[e,t]=P.useState(()=>rLe(m_()));P.useEffect(()=>{const r=()=>t(c=>sLe(c,m_()));return window.addEventListener("resize",r),r(),()=>window.removeEventListener("resize",r)},[]);const a=P.useCallback((r,c)=>{t(m=>oLe(m,{w:r,h:c}))},[]);return{box:e.box,fit:a}}function p_({message:e}){return P.useEffect(()=>vr(R7("error",e)),[e]),v.jsxs("div",{style:{position:"fixed",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:Yt.dark.mediaBlack,color:Yt.dark.danger,fontFamily:"system-ui, sans-serif",fontSize:13,padding:16,textAlign:"center"},children:["Grid embed config error: ",e]})}const lLe=["setDevices","setSpans"];function cLe(e,t){return e.length===t.length&&e.every((a,r)=>a===t[r])}function dLe({system:e,config:t}){const[a,r]=P.useState(t.devices),[c,m]=P.useState(()=>new Set(t.audioOnIds??[])),d=E7(),h=P.useRef(d.setActiveMic);h.current=d.setActiveMic;const[f,k]=P.useState(()=>new Set(t.pausedIds??[])),[x,E]=P.useState(t.highlight),[R,T]=P.useState(t.activeOnly??!1),[N,j]=P.useState(t.showBoxes??!1),[q,B]=P.useState(()=>t.overlays??{}),[F,U]=P.useState(()=>t.spans??{}),H=xqe(a,x),Q=P.useMemo(()=>R?a.filter(ee=>H.has(ee)):a,[R,a,H]),[te,K]=P.useState(t.quality),[W,oe]=P.useState(t.layout),[he,Ae]=P.useState(t.showName),[we,Ee]=P.useState(0),Ie=P.useMemo(()=>Xze(t.labels),[t.labels]),[Me,Y]=P.useState(()=>t.snapshots??{}),de=P.useMemo(()=>new Set(t.ptzIds??[]),[t.ptzIds]),{box:Re,fit:Qe}=Ux(),re=Ie.camera,[V,ie]=P.useState({});P.useEffect(()=>{let ee=!1;return e.trpcClient.deviceManager.listAll.query({deviceIds:[...a],projection:"slim"}).then(Se=>{if(ee)return;const _e={};for(const Be of Se)_e[Be.id]={name:Be.name??`${re} ${Be.id}`,online:Be.online??!1};ie(_e)}).catch(()=>{}),()=>{ee=!0}},[e,a,re]),P.useEffect(()=>(window.__camstackGrid={setAudioOn:ee=>m(new Set(ee)),setMutedAll:ee=>{ee&&m(new Set)},setActiveMic:ee=>h.current(ee),setHighlight:ee=>E(ee),setActiveOnly:ee=>T(ee),setShowBoxes:ee=>j(ee),setOverlays:ee=>B(ee),setPaused:ee=>k(new Set(ee)),setDevices:ee=>r(Se=>cLe(Se,ee)?Se:[...ee]),setSpans:ee=>U(ee),setQuality:ee=>K(ee),setLayout:ee=>oe(ee),setShowName:Ae,setShowBadges:()=>{},setSnapshots:ee=>Y(ee),fit:Qe,reconnect:()=>Ee(ee=>ee+1)},vr(R7("ready",void 0,lLe)),()=>{window.__camstackGrid&&delete window.__camstackGrid}),[Qe]),P.useEffect(()=>Gm(ee=>{const Se=window.__camstackGrid;if(!Se)return;switch(ee.kind){case"setAudioOn":Se.setAudioOn(ee.value);break;case"setMutedAll":Se.setMutedAll(ee.value);break;case"setActiveMic":Se.setActiveMic(ee.value);break;case"setHighlight":Se.setHighlight(ee.value);break;case"setActiveOnly":Se.setActiveOnly(ee.value);break;case"setShowBoxes":Se.setShowBoxes(ee.value===!0);break;case"setOverlays":Se.setOverlays(ee.value);break;case"setPaused":Se.setPaused(ee.value);break;case"setDevices":Se.setDevices(ee.value);break;case"setSpans":Se.setSpans(ee.value);break;case"setQuality":Se.setQuality(w7.parse(ee.value));break;case"setLayout":Se.setLayout(ee.value);break;case"setShowName":Se.setShowName(ee.value);break;case"setShowBadges":Se.setShowBadges(ee.value);break;case"setSnapshots":Se.setSnapshots(ee.value);break;case"fit":Se.fit(ee.w,ee.h);break;case"reconnect":Se.reconnect();break}}),[]);const fe=P.useMemo(()=>kqe(Q,Re.w,Re.h,W,F),[Q,Re.w,Re.h,W,F]),be=P.useRef(null);return P.useEffect(()=>{const ee=be.current;if(!ee)return;const Se=[];ee.querySelectorAll("[data-device-id]").forEach(_e=>{const Be=Number(_e.dataset.deviceId),Ge=_e.getBoundingClientRect();Se.push({deviceId:Be,rect:{x:Ge.x,y:Ge.y,w:Ge.width,h:Ge.height}})}),Se.length&&vr(_qe(Se))},[fe,Q]),v.jsxs("div",{ref:be,style:{position:"fixed",inset:0,background:Yt.dark.mediaBlack,display:"flex",alignItems:"center",justifyContent:"center"},children:[R&&Q.length===0&&v.jsx("div",{style:{color:Yt.dark.eventsMuted,fontFamily:"system-ui, sans-serif",fontSize:14,padding:24,textAlign:"center"},children:Ie.noActiveCameras}),v.jsx(iLe,{wall:fe,renderTile:(ee,Se,_e)=>v.jsx(K6e,{system:e,probeAuthToken:t.token,deviceId:ee,name:V[ee]?.name??`${Ie.camera} ${ee}`,online:V[ee]?.online??!1,quality:te,muted:!c.has(ee),paused:f.has(ee),showName:he,audioActive:c.has(ee),micActive:d.activeMicId===ee,onTogglePause:Be=>vr(Aqe(Be)),onToggleAudio:Be=>vr(Cqe(Be)),onToggleMic:d.toggleMic,onOpen:Be=>vr(Mqe(Be)),ptzSupported:de.has(ee),onPtz:Be=>vr(Iqe(Be)),cellW:Se,cellH:_e,onCellPanel:t.cellPanels===!1?void 0:(Be,Ge)=>vr(Eqe(Be,Ge)),highlight:x,showBoxes:N,overlay:q[String(ee)],reconnectSignal:we,posterUrl:Me[String(ee)],editable:t.editable===!0,span:F[String(ee)],onRemove:Be=>vr(Rqe(Be)),onResize:(Be,Ge,Ft)=>vr(Tqe(Be,Ge,Ft)),labels:Ie})})]})}function uLe(){const e=Wm("grid",()=>window.__CAMSTACK_GRID__,M7,mqe),t=P.useMemo(()=>{if(e===null||!e.ok)return null;const a=xm({serverUrl:e.config.serverUrl,token:e.config.token}),r=new uq({defaultOptions:{queries:{retry:!1,refetchOnWindowFocus:!1}}});return{system:a,queryClient:r}},[e]);return P.useEffect(()=>{if(t)return()=>t.system.close()},[t]),e===null?null:e.ok?t?v.jsx(Zq,{system:t.system,children:v.jsx(pq,{client:t.queryClient,children:v.jsxs(S.Provider,{client:t.system.trpcClient,queryClient:t.queryClient,children:[v.jsx(Wg,{system:t.system}),v.jsx(dLe,{system:t.system,config:e.config})]})})}):v.jsx(p_,{message:"Failed to initialise the grid embed"}):v.jsx(p_,{message:e.error})}const Hx=qe([o({kind:_("adaptive")}),o({kind:_("profile"),profile:wn})]),mLe=o({deviceId:i().int().nonnegative(),target:Hx.optional(),muted:w().optional(),stats:w().optional(),snapshot:n().optional(),atMs:i().int().positive().optional()});function pLe(e){const t=mLe.safeParse(e);return t.success?t.data:null}const hLe=["live","loading","playing","paused","gap","ended","error"];function fLe(e){return typeof e=="string"&&hLe.includes(e)}const gLe=["not-negotiated","not-offered","no-audio-track","unsupported-codec","codec-mismatch","stream-failed","rate"],vLe=["stream-short","stream-empty"],Zs="low",h_=5e3;class yLe{constructor(t){this.deps=t,this.deps.channel.addEventListener("message",this.onMessage)}deps;begun=!1;disposed=!1;lastSentProfile=null;degradedRequest=null;positionsSeen=0;firstFrameAnnounced=!1;rvfcHandle=null;lastPushSeq=null;retargets=0;renders=0;acks=0;lastCursorMs=null;lastState=null;playIntentAt=null;playIntentKind=null;playIntentDragId=void 0;pendingUpgrade=null;upgradeTimer=null;upgradeWarmTimer=null;clipId=null;onMessage=t=>{if(this.disposed||typeof t.data!="string")return;let a;try{a=JSON.parse(t.data)}catch{return}if(typeof a!="object"||a===null)return;const r=a;if(r.t==="liveProfile"&&(r.profile==="high"||r.profile==="mid"||r.profile==="low")){this.deps.onLiveProfile?.(r.profile);return}if(r.t==="servedProfile"&&(r.profile==="high"||r.profile==="mid"||r.profile==="low")&&typeof r.requested=="string"){const c=r.requested;this.lastSentProfile=r.profile,this.degradedRequest=r.profile===c?null:c,this.degradedRequest!==null&&this.pendingUpgrade?.desiredProfile===this.degradedRequest&&(this.deps.onLog?.("scrub:playback-upgrade-vetoed",{to:this.degradedRequest}),this.cancelPlaybackUpgrade()),this.deps.onServedProfile?.({profile:r.profile,requested:c});return}if(r.t==="clipDuration"){const c=r;typeof c.clipId=="string"&&typeof c.durationMs=="number"&&Number.isFinite(c.durationMs)&&c.durationMs>0&&this.deps.onClipDuration?.({clipId:c.clipId,durationMs:c.durationMs});return}if(r.t==="clipAudio"){const c=r;if(typeof c.clipId!="string"||c.clipId.length===0||typeof c.carried!="boolean")return;const m=c.codec==="opus"||c.codec==="pcmu"?c.codec:void 0,d=gLe.find(k=>k===c.reason),h=typeof c.rate=="number"&&Number.isFinite(c.rate)&&c.rate>0?c.rate:void 0,f=d==="rate"&&h===void 0?void 0:d;this.deps.onClipAudio?.({clipId:c.clipId,carried:c.carried,...m===void 0?{}:{codec:m},...f===void 0?{}:{reason:f},...f==="rate"&&h!==void 0?{rate:h}:{}});return}if(r.t==="clipIncomplete"){const c=r;if(typeof c.clipId!="string"||c.clipId.length===0)return;const m=vLe.find(d=>d===c.code);if(m===void 0||typeof c.reason!="string"||c.reason.trim().length===0)return;this.deps.onClipIncomplete?.({clipId:c.clipId,code:m,reason:c.reason});return}if(r.t==="state"&&fLe(r.state)){this.lastState=r.state,r.state==="playing"||r.state==="paused"?(this.maybeArmPlaybackUpgrade(),this.playIntentAt!==null&&(this.deps.onLog?.("playback:ready",{kind:this.playIntentKind,state:r.state,waitMs:Math.round(performance.now()-this.playIntentAt),dragId:this.playIntentDragId}),this.playIntentAt=null,this.playIntentKind=null,this.playIntentDragId=void 0)):(r.state==="live"||r.state==="gap"||r.state==="ended"||r.state==="error")&&this.cancelPlaybackUpgrade(),this.deps.onState?.(r.state);return}r.t!=="position"||typeof r.epochMs!="number"||(this.lastCursorMs=r.epochMs,this.deps.onPosition?.(r.epochMs),typeof r.seq=="number"&&(this.lastPushSeq=r.seq),this.begun&&(this.positionsSeen+=1,this.rvfcCapable()||(this.acks+=1,this.sendAck())))};sendAck(){this.send(this.lastPushSeq===null?{t:"scrubAck"}:{t:"scrubAck",seq:this.lastPushSeq})}rvfcCapable(){return typeof this.deps.video()?.requestVideoFrameCallback=="function"}send(t){return this.disposed||this.deps.channel.readyState!=="open"?!1:(this.deps.channel.send(JSON.stringify(t)),!0)}sendPlayRecorded(t,a,r,c,m){const d=this.send({t:"playRecorded",deviceId:t,epoch:a,profile:r});return d&&(this.lastSentProfile=r,this.playIntentAt=performance.now(),this.playIntentKind=c,this.playIntentDragId=m,this.deps.onLog?.("playback:intent",{kind:c,deviceId:t,epochMs:a,profile:r,dragId:m})),d}maybeArmPlaybackUpgrade(){if(this.pendingUpgrade===null||this.upgradeTimer!==null||this.disposed)return;this.upgradeTimer=setTimeout(()=>this.firePlaybackUpgrade(),h_);const t=this.pendingUpgrade;this.upgradeWarmTimer=setTimeout(()=>{if(this.upgradeWarmTimer=null,this.pendingUpgrade===null||this.disposed)return;const a=this.lastCursorMs??t.landEpochMs;this.warm(a,t.desiredProfile)},Math.max(0,h_-1500))}firePlaybackUpgrade(){this.upgradeTimer=null;const t=this.pendingUpgrade;if(this.pendingUpgrade=null,!t||this.disposed)return;const a=this.lastCursorMs??t.landEpochMs;this.sendPlayRecorded(t.deviceId,a,t.desiredProfile,"upgrade"),this.deps.onLog?.("scrub:playback-upgrade",{from:Zs,to:t.desiredProfile,epochMs:a})}cancelPlaybackUpgrade(){this.upgradeTimer!==null&&(clearTimeout(this.upgradeTimer),this.upgradeTimer=null),this.upgradeWarmTimer!==null&&(clearTimeout(this.upgradeWarmTimer),this.upgradeWarmTimer=null),this.pendingUpgrade=null}playRecorded(t,a,r){return this.cancelPlaybackUpgrade(),this.clipId=null,this.sendPlayRecorded(t,a,r,"play")}holdsClip(){return this.clipId!==null}playClip(t,a,r,c,m){this.cancelPlaybackUpgrade();const d=this.send({t:"playClip",deviceId:t,clipId:a,provider:r,offsetMs:Math.max(0,Math.round(c)),...m===void 0?{}:{profile:m}});return d&&(this.clipId=a),d}upgradePlayback(t,a,r){return r===this.lastSentProfile?!0:this.clipId!==null?(this.deps.onLog?.("clip:playback-upgrade-refused",{clipId:this.clipId,to:r}),!0):(this.cancelPlaybackUpgrade(),this.warm(a,r),this.sendPlayRecorded(t,a,r,"upgrade"))}landFromScrub(t,a,r,c){if(this.end(),this.cancelPlaybackUpgrade(),this.clipId!==null){const d=this.commit(a,c);return d&&(this.lastCursorMs=a,this.deps.onLog?.("playback:intent",{kind:"clip-commit",deviceId:t,epochMs:a,dragId:c})),d}return this.sendPlayRecorded(t,a,Zs,"land",c)?(this.lastCursorMs=a,r===this.degradedRequest?this.deps.onLog?.("scrub:playback-upgrade-vetoed",{to:r,epochMs:a}):r!==Zs&&(this.pendingUpgrade={deviceId:t,desiredProfile:r,landEpochMs:a},this.warm(a,r),(this.lastState==="playing"||this.lastState==="paused")&&this.maybeArmPlaybackUpgrade()),!0):!1}seek(t){this.cancelPlaybackUpgrade();const a=this.send({t:"seek",epoch:t});return a&&(this.playIntentAt=performance.now(),this.playIntentKind="seek",this.playIntentDragId=void 0,this.deps.onLog?.("playback:intent",{kind:"seek",epochMs:t})),a}warm(t,a=Zs){return this.send({t:"warm",epoch:t,profile:a})}setRate(t){return this.send({t:"setRate",rate:t})}stepFrame(t){return this.send({t:"stepFrame",dir:t})}commit(t,a){return this.end(),this.send(a!==void 0?{t:"scrubCommit",epoch:t,dragId:a}:{t:"scrubCommit",epoch:t})}goLive(){this.cancelPlaybackUpgrade();const t=this.send({t:"goLive"});return t&&(this.deps.onLog?.("scrub:push-golive",{clipId:this.clipId}),this.clipId=null),this.end(),t}isActive(){return this.begun&&!this.disposed&&this.deps.channel.readyState==="open"}isOpen(){return!this.disposed&&this.deps.channel.readyState==="open"}begin(t){return this.disposed||this.deps.channel.readyState!=="open"?!1:(this.begun||(this.begun=!0,this.positionsSeen=0,this.firstFrameAnnounced=!1,this.retargets=0,this.renders=0,this.acks=0,this.cancelPlaybackUpgrade(),this.lastSentProfile!==Zs&&(this.lastSentProfile=Zs,this.send({t:"setProfile",profile:Zs})),this.send(t!==void 0?{t:"scrubStart",dragId:t}:{t:"scrubStart"}),this.armRenderAck(),this.deps.onLog?.("scrub:push-begin",{rvfc:this.rvfcCapable(),dragId:t})),!0)}retarget(t,a){this.isActive()&&(this.retargets+=1,this.send(a?{t:"scrubTo",epoch:t,m:a.mode,v:Math.round(a.velocityPxPerS)}:{t:"scrubTo",epoch:t}))}end(){this.begun&&this.deps.onLog?.("scrub:push-drag-end",{retargets:this.retargets,positions:this.positionsSeen,renders:this.renders,acks:this.acks}),this.begun=!1,this.cancelRenderAck()}dispose(){this.cancelPlaybackUpgrade(),this.end(),this.disposed=!0,this.deps.channel.removeEventListener("message",this.onMessage)}armRenderAck(){const t=this.deps.video();t?.requestVideoFrameCallback&&(this.rvfcHandle=t.requestVideoFrameCallback(()=>{this.rvfcHandle=null,!(!this.begun||this.disposed)&&(this.positionsSeen>0&&(this.renders+=1,this.acks+=1,this.sendAck(),this.firstFrameAnnounced||(this.firstFrameAnnounced=!0,this.deps.onFirstFrame?.()),this.deps.onLog?.("scrub:drawn",{depth:"push"})),this.armRenderAck())}))}cancelRenderAck(){this.rvfcHandle!==null&&(this.deps.video()?.cancelVideoFrameCallback?.(this.rvfcHandle),this.rvfcHandle=null)}}function bLe(e,t,a,r){return e?.isOpen()?(e.warm(a),e.playRecorded(t,a,r)):!1}const kLe=24e4;function SLe(e,t=kLe){if(t<=0)return[e];const a=[];for(let r=0;r<e.length;r+=t)a.push(e.slice(r,r+t));return a.length===0?[""]:a}const wLe=["video/mp4;codecs=avc1.42E01E,mp4a.40.2","video/webm;codecs=vp8,opus","video/webm;codecs=vp9,opus"],f_=["video/mp4;codecs=avc1.42E01E","video/mp4","video/webm;codecs=vp8","video/webm"];function xLe(e=a=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(a),t){const a=t?.audio?[...wLe,...f_]:f_;for(const r of a)try{if(e(r))return r}catch{}return""}function MLe(e,t){const a=[...e.getVideoTracks()],r=t?.getAudioTracks()??[],c=r.length>0?r.map(m=>{const d=m.clone();return"enabled"in d&&(d.enabled=!0),d}):[...e.getAudioTracks()];return[...a,...c]}function CLe(e,t=30){const a=e;try{if(typeof a.captureStream=="function"){const r=a.captureStream(t);if(r.getVideoTracks().length>0)return r}}catch{}try{if(typeof a.mozCaptureStream=="function"){const r=a.mozCaptureStream(t);if(r.getVideoTracks().length>0)return r}}catch{}return ALe(e,t)}function ALe(e,t){if(e.videoWidth<2||e.videoHeight<2||typeof document>"u")return null;const a=document.createElement("canvas");a.width=e.videoWidth,a.height=e.videoHeight;const r=a.getContext("2d");if(!r||typeof a.captureStream!="function")return null;let c=!0;const m=()=>{if(c){try{r.drawImage(e,0,0,a.width,a.height)}catch{}requestAnimationFrame(m)}};m();const d=a.captureStream(t),h=d.getVideoTracks()[0];if(h){const f=h.stop.bind(h);h.stop=()=>{c=!1,f()}}return d}function ILe(e){return new Promise((t,a)=>{const r=new FileReader;r.onload=()=>{const c=String(r.result??""),m=c.indexOf(",");t(m>=0?c.slice(m+1):c)},r.onerror=()=>a(r.error??new Error("read failed")),r.readAsDataURL(e)})}function ELe(){return`c${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}function RLe(e){let t=null,a=[],r=null,c="",m=!1;const d=()=>{if(t=null,a=[],m=!1,r){for(const f of r.getTracks())try{f.stop()}catch{}r=null}},h=f=>{d(),e.emit({type:"liveCaptureError",message:f})};return{start(){if(t)return;const f=e.getVideo();if(!f){h("no video");return}if(typeof MediaRecorder>"u"){h("MediaRecorder missing");return}const k=CLe(f);if(!k){h("no video");return}const x=f.srcObject instanceof MediaStream?f.srcObject:null,E=MLe(k,x);if(x&&x.getAudioTracks().length>0)for(const j of k.getAudioTracks())try{j.stop()}catch{}const R=new MediaStream(E);r=R;const T=E.some(j=>j.kind==="audio"),N=xLe(void 0,{audio:T});try{t=N?new MediaRecorder(R,{mimeType:N,videoBitsPerSecond:25e5,...T?{audioBitsPerSecond:128e3}:{}}):new MediaRecorder(R)}catch(j){h(j instanceof Error?j.message:"MediaRecorder missing");return}a=[],c=ELe(),m=!1,t.ondataavailable=j=>{j.data&&j.data.size>0&&a.push(j.data)},t.onerror=()=>h("MediaRecorder missing");try{t.start(1e3)}catch(j){h(j instanceof Error?j.message:"MediaRecorder missing")}},stop(){const f=t;if(!f||m){f||h("no video");return}m=!0;const k=c,x=f.mimeType||"video/mp4";f.onstop=()=>{const E=new Blob(a,{type:x});if(d(),E.size===0){e.emit({type:"liveCaptureError",message:"empty capture"});return}ILe(E).then(R=>{e.emit({type:"liveCaptureStart",id:k,mime:x});const T=SLe(R),N=T.length;T.forEach((j,q)=>{e.emit({type:"liveCaptureChunk",id:k,index:q,total:N,data:j})}),e.emit({type:"liveCaptureDone",id:k})}).catch(R=>{e.emit({type:"liveCaptureError",message:R instanceof Error?R.message:"encode failed"})})};try{typeof f.requestData=="function"&&f.requestData(),f.stop()}catch(E){h(E instanceof Error?E.message:"stop failed")}},abort(){if(t&&t.state!=="inactive")try{t.stop()}catch{}d()}}}const g_=2560,TLe=.9;function _Le(e,t){const a=Math.max(e,t);if(a<=g_)return{width:e,height:t};const r=g_/a;return{width:Math.round(e*r),height:Math.round(t*r)}}function PLe(e){const t=e.indexOf(",");return e.startsWith("data:")&&t>=0?e.slice(t+1):null}function NLe(e){if(e.videoWidth<2||e.videoHeight<2||typeof document>"u")return null;const{width:t,height:a}=_Le(e.videoWidth,e.videoHeight),r=document.createElement("canvas");r.width=t,r.height=a;const c=r.getContext("2d");if(!c)return null;try{c.drawImage(e,0,0,t,a);const m=PLe(r.toDataURL("image/jpeg",TLe));return m===null||m.length===0?null:{base64:m,width:t,height:a}}catch{return null}}function OLe(e,t){const a=e.getVideo(),r=a===null?null:NLe(a);if(r===null){e.emit({type:"snapshotError",id:t,message:"no frame"});return}e.emit({type:"snapshot",id:t,base64:r.base64,width:r.width,height:r.height})}const DLe=8,jLe=2.5;function zLe(e){return e>=DLe?"high":e>=jLe?"mid":"low"}function qLe(e,t){return e.kind==="profile"?e.profile:"low"}function LLe(e,t){return e.kind==="profile"?e.profile:zLe(t)}const BLe=o({serverUrl:n().min(1),token:n().min(1),deviceId:i().int().nonnegative(),target:Hx,muted:w(),stats:w().optional(),highlight:x7.optional(),snapshot:n().optional(),initialSeekMs:i().positive().optional(),initialClipId:n().min(1).optional(),initialClipProvider:n().min(1).optional(),initialClipProfile:n().min(1).optional()}),v_=["setDevice","setDevice.atMs","setToken"];function bw(e,t){qt(t!==void 0?{type:"state",state:e,message:t,caps:v_}:{type:"state",state:e,caps:v_})}function FLe(e){switch(e){case"playing":return"playing";case"error":return"error";case"connecting":case"disconnected":case"idle":return"connecting"}}function y_(e,t){return qLe(e)}async function $Le(){if(typeof window>"u")return null;const e=window.location.origin.replace(/\/+$/,""),t=new AbortController,a=window.setTimeout(()=>t.abort(),2500),r=performance.now();try{const c=await fetch(`${e}/adaptive-probe`,{signal:t.signal});if(!c.ok)return null;const m=await c.arrayBuffer(),d=Math.max(1,performance.now()-r);return m.byteLength<1024?null:m.byteLength*8/d/1e3}catch{return null}finally{window.clearTimeout(a)}}function b_(e,t,a,r){r.kind==="adaptive"&&$Le().then(c=>{if(c===null)return;const m=LLe(r,c);e.upgradePlayback(t,a,m)})}function ULe(e){return e.kind==="adaptive"?{kind:"adaptive"}:{kind:"profile",profile:e.profile}}function HLe(e){return e.kind==="adaptive"?"embed:adaptive":`embed:profile:${e.profile}`}function QLe(e){const t=BLe.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(a=>`${a.path.join(".")||"(root)"}: ${a.message}`).join("; ")}}function k_({message:e}){return P.useEffect(()=>{bw("error",e)},[e]),v.jsxs("div",{style:{position:"fixed",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:Yt.dark.mediaBlack,color:Yt.dark.danger,fontFamily:"system-ui, sans-serif",fontSize:13,padding:16,textAlign:"center"},children:["Embed config error: ",e]})}function VLe({system:e,deviceId:t,initialTarget:a,initialMuted:r,initialStats:c,initialHighlight:m,initialSnapshot:d,initialSeekMs:h,initialClipId:f,initialClipProvider:k,initialClipProfile:x,probeAuthToken:E}){const[R,T]=P.useState(a),N=pd();P.useEffect(()=>d7(t),[t]);const j=P.useRef(R);j.current=R;const[q,B]=P.useState(r),[F,U]=P.useState(c),[H,Q]=P.useState(m),[te,K]=P.useState(d),[W,oe]=P.useState(0),[he,Ae]=P.useState("idle"),{box:we,fit:Ee}=Ux(),Ie=N7(e,t,H),Me=E7(),Y=P.useRef(Me.setActiveMic);Y.current=Me.setActiveMic;const{handleOffer:de,getIceServers:Re,addIceCandidate:Qe,getIceCandidates:re,closeSession:V,getSessionState:ie,getSessionDebug:fe,applyDownlinkProbe:be}=IL(e.trpcClient,t),ee=P.useMemo(()=>ULe(R),[R]),Se=P.useMemo(()=>(ve,Fe,Le)=>de(ee,ve,Fe,Le),[de,ee]),_e=P.useMemo(()=>(ve,Fe,Le,ot)=>de(Le,Fe,ve,ot),[de]),Be=P.useRef(null),Ge=P.useRef(null),Ft=P.useRef(null);P7({containerRef:Ft,playing:he==="playing",onRecover:()=>{oe(ve=>ve+1),qt({type:"log",scope:"stream-debug",msg:"stall-recovery",data:{reason:"no presented frame while playing"}})}});const Ot=P.useRef("low"),wt=P.useRef(!1),sa=P.useRef(null),nt=P.useRef(null),za=P.useRef(null),ft=()=>{const ve=nt.current;if(ve===null)return;const Fe=Ot.current,Le=`${ve.phase}|${ve.viewportWidth??"-"}x${ve.viewportHeight??"-"}|${ve.devicePixelRatio??"-"}|${ve.downlinkMbps??"-"}|${ve.prefersTier??"-"}|${ve.probeOrigin??"unreachable"}|${Fe}`;Le!==za.current&&(za.current=Le,qt({type:"log",scope:"adaptive",msg:"tier decision",data:{deviceId:t,requested:R.kind==="adaptive"?"adaptive":`pinned:${R.kind}`,phase:ve.phase,viewportWidth:ve.viewportWidth??null,viewportHeight:ve.viewportHeight??null,devicePixelRatio:ve.devicePixelRatio??null,downlinkMbps:ve.downlinkMbps??null,prefersTier:ve.prefersTier??null,probeOrigin:ve.probeOrigin,liveProfile:Fe}}))},lt=P.useRef(h??null),Dt=P.useRef(f===void 0||k===void 0?null:{clipId:f,provider:k,...x===void 0?{}:{profile:x}});P.useEffect(()=>{if(!q){let Fe=0;for(const Le of Array.from(document.querySelectorAll("video"))){const ot=Le.srcObject;if(ot instanceof MediaStream)for(const He of ot.getAudioTracks())He.enabled||(He.enabled=!0,Fe++)}Fe>0&&qt({type:"log",scope:"live-audio",msg:"un-muted",data:{restored:Fe}});return}const ve=setInterval(()=>{let Fe=0;for(const Le of Array.from(document.querySelectorAll("video"))){Le.muted||(Le.muted=!0,Fe++);const ot=Le.srcObject;if(ot instanceof MediaStream)for(const He of ot.getAudioTracks())He.enabled&&(He.enabled=!1,Fe++)}Fe>0&&qt({type:"log",scope:"live-audio",msg:"re-muted",data:{corrected:Fe}})},1e3);return()=>clearInterval(ve)},[q]),P.useEffect(()=>()=>Be.current?.dispose(),[]),P.useEffect(()=>{const ve=()=>{const ze=Be.current;return ze?.isOpen()?ze:null},Fe=()=>y_(j.current,Ot.current),Le=(ze,st)=>{b_(ze,t,st,j.current)},ot=ze=>{wt.current||(wt.current=!0,qt({type:"log",scope:"recorded:session",msg:"pointer move with no open session",data:{what:ze}}),qt({type:"recState",state:"error"}))},He=(ze,st)=>{const Lt=ve();return!Lt||!st(Lt)?(ot(ze),!1):(wt.current=!1,!0)},ea=(ze,st)=>{He("scrubCommit",Lt=>{const Kt=Lt.landFromScrub(t,ze,Fe(),st);return Kt&&Le(Lt,ze),Kt})},$t=RLe({emit:qt,getVideo:()=>Ge.current});return window.__camstackEmbed={setMuted:ze=>B(ze),setTarget:ze=>{const st=Hx.safeParse(ze);st.success&&T(st.data)},setStats:ze=>U(ze),setHighlight:ze=>Q(ze),setSnapshot:ze=>K(ze),setMic:ze=>Y.current(ze?t:null),fit:Ee,reconnect:()=>oe(ze=>ze+1),playRecorded:(ze,st,Lt)=>{Number.isFinite(st)&&He("playRecorded",Kt=>Kt.playRecorded(ze,st,Lt))},playClip:(ze,st,Lt,Kt,qa)=>{if(!Number.isFinite(Kt)||typeof st!="string"||st.length===0||typeof Lt!="string"||Lt.length===0){qt({type:"log",scope:"clip:play",msg:"playClip REFUSED — the command is malformed",data:{deviceId:ze,clipId:String(st).slice(0,120),provider:Lt,offsetMs:Kt}});return}qt({type:"log",scope:"clip:play",msg:"playClip arrived",data:{deviceId:ze,clipId:st.slice(0,120),provider:Lt,offsetMs:Kt,profile:qa??null}});const fn=He("playClip",ct=>ct.playClip(ze,st,Lt,Kt,qa));sa.current=fn?null:{deviceId:ze,clipId:st,provider:Lt,offsetMs:Kt,...qa!==void 0?{profile:qa}:{}},qt({type:"log",scope:"clip:play",msg:fn?"playClip sent to the broker":"playClip HELD — no open session yet",data:{deviceId:ze,sent:fn}})},seek:ze=>{Number.isFinite(ze)&&He("seek",st=>{if(st.holdsClip())return st.seek(ze);const Lt=st.playRecorded(t,ze,Fe());return Lt&&Le(st,ze),Lt})},scrubCommit:(ze,st)=>{Number.isFinite(ze)&&ea(ze,st)},scrubStart:ze=>{qt({type:"log",scope:"recorded:scrub",msg:"scrubStart",data:{dragId:ze}}),He("scrubStart",st=>st.begin(ze))},scrubTo:(ze,st,Lt)=>{if(!Number.isFinite(ze))return;const Kt=(st==="fine"||st==="coarse")&&Number.isFinite(Lt)?{mode:st,velocityPxPerS:Lt}:void 0;He("scrubTo",qa=>qa.isActive()?(qa.retarget(ze,Kt),!0):!1)},timelineWarm:ze=>{Number.isFinite(ze)&&ve()?.warm(ze)},scrubEnd:ze=>{Number.isFinite(ze)&&ea(ze)},setRate:ze=>{Number.isFinite(ze)&&He("setRate",st=>st.setRate(ze))},stepFrame:ze=>{ze!==1&&ze!==-1||He("stepFrame",st=>st.stepFrame(ze))},goLive:()=>{sa.current=null,He("goLive",ze=>ze.goLive())&&qt({type:"recState",state:"live"})},startLiveCapture:()=>$t.start(),stopLiveCapture:()=>$t.stop(),snapshot:ze=>OLe({emit:qt,getVideo:()=>Ge.current},ze)},()=>{$t.abort(),window.__camstackEmbed&&delete window.__camstackEmbed}},[t,Ee]),P.useEffect(()=>{qt({type:"micState",state:Me.micState})},[Me.micState]),P.useEffect(()=>Gm(ve=>{const Fe=window.__camstackEmbed;if(!Fe)return;switch(ve.kind){case"setMuted":Fe.setMuted(ve.value);break;case"setTarget":Fe.setTarget(ve.value);break;case"setStats":Fe.setStats(ve.value);break;case"setHighlight":Fe.setHighlight(ve.value);break;case"setSnapshot":Fe.setSnapshot(ve.value);break;case"setMic":Fe.setMic(ve.value);break;case"fit":Fe.fit(ve.w,ve.h);break;case"reconnect":Fe.reconnect();break;case"playRecorded":Fe.playRecorded(ve.deviceId,ve.epochMs,ve.profile);break;case"seek":Fe.seek(ve.epochMs??ve.value);break;case"scrubCommit":Fe.scrubCommit(ve.epochMs??ve.value,ve.dragId);break;case"scrubStart":Fe.scrubStart(ve.dragId);break;case"scrubTo":Fe.scrubTo(ve.epochMs??ve.value,ve.m,ve.v);break;case"scrubEnd":Fe.scrubEnd(ve.epochMs??ve.value);break;case"timelineWarm":Fe.timelineWarm(ve.epochMs??ve.value);break;case"setRate":Fe.setRate(ve.rate??ve.value);break;case"stepFrame":{const ot=ve.dir;(ot===1||ot===-1)&&Fe.stepFrame(ot);break}case"goLive":Fe.goLive();break;case"startLiveCapture":Fe.startLiveCapture();break;case"stopLiveCapture":Fe.stopLiveCapture();break;case"snapshot":typeof ve.id=="string"&&Fe.snapshot(ve.id);break}}),[]);const bt=HLe(R);return v.jsxs("div",{ref:Ft,style:{position:"fixed",left:0,top:0,width:we.w,height:we.h,background:Yt.dark.mediaBlack},children:[v.jsx(AL,{serverUrl:e.serverUrl,applyDownlinkProbe:be,streamKey:bt,autoPlay:!0,muted:q,showControls:!1,showStats:F,onDebugStats:ve=>qt({type:"log",scope:"stream-debug",msg:"sample",data:ve}),onPlaybackStats:ve=>qt({type:"log",scope:"playback",msg:"stats",data:ve}),onConnectTiming:ve=>qt({type:"log",scope:"webrtc-timing",msg:"connect",data:ve}),onClientNetworkSample:R.kind==="adaptive"?ve=>{e.trpcClient.networkQuality.reportClientStats.mutate({deviceId:t,...ve}).catch(()=>{})}:void 0,probeAuthToken:E,className:"w-full h-full",onAdaptiveHints:ve=>{nt.current=ve,ft()},handleOffer:Se,reoffer:_e,getSessionState:ie,getSessionDebug:fe,getIceServers:Re,addIceCandidate:Qe,getIceCandidates:re,closeSession:V,reconnectSignal:W,posterUrl:te,onStateChange:ve=>{Ae(ve),bw(FLe(ve))},onError:ve=>bw("error",ve),onReconnectAttempt:ve=>qt({type:"log",scope:"live:retry",msg:ve.kind==="retry"?"auto-retry scheduled":"auto-retry exhausted",data:ve}),onControlChannel:ve=>{Be.current?.dispose(),wt.current=!1,Be.current=new yLe({channel:ve,video:()=>Ge.current,onState:Le=>qt({type:"recState",state:Le}),onPosition:Le=>qt({type:"position",positionMs:Le}),onServedProfile:Le=>qt({type:"servedProfile",profile:Le.profile,requested:Le.requested}),onClipDuration:Le=>qt({type:"clipDuration",clipId:Le.clipId,durationMs:Le.durationMs}),onClipAudio:Le=>qt({type:"clipAudio",...Le}),onClipIncomplete:Le=>qt({type:"clipIncomplete",...Le}),onLiveProfile:Le=>{Ot.current=Le,ft()},onFirstFrame:()=>qt({type:"scrubDrawn"}),onLog:(Le,ot)=>qt({type:"log",scope:Le.startsWith("playback:")?"playback":"scrub",msg:Le,data:ot})});const Fe=()=>{const Le=Be.current;if(Le===null)return;const ot=Dt.current;if(ot!==null){const $t=Le.playClip(t,ot.clipId,ot.provider,0,ot.profile);qt({type:"log",scope:"clip:play",msg:$t?"initial clip opened":"initial clip still waiting for the channel",data:{deviceId:t,clipId:ot.clipId.slice(0,120),sent:$t}}),$t&&(Dt.current=null);return}const He=sa.current;if(He===null)return;const ea=Le.playClip(He.deviceId,He.clipId,He.provider,He.offsetMs,He.profile);qt({type:"log",scope:"clip:play",msg:ea?"held clip asserted on the open channel":"held clip still waiting",data:{deviceId:He.deviceId,clipId:He.clipId.slice(0,120),sent:ea}}),ea&&(sa.current=null)};if(ve.addEventListener("open",Fe),Fe(),lt.current!==null){const Le=()=>{const ot=lt.current;if(ot===null)return;const He=y_(j.current,Ot.current);bLe(Be.current,t,ot,He)&&(lt.current=null,Be.current&&b_(Be.current,t,ot,j.current),qt({type:"log",scope:"recorded:initial-seek",msg:"config-carried seek fired",data:{epochMs:ot,profile:He}}))};ve.readyState==="open"?Le():ve.addEventListener("open",Le,{once:!0})}},onVideoElement:ve=>{Ge.current=ve}}),Ie&&(()=>{const ve=H?.appearance,Fe=Ie==="motion"?ve?.motionColor??Lc("motion",N):Ie==="audio"?ve?.audioColor??Lc("audio",N):ve?.detectionColor??Lc("detection",N),Le=ve?.thickness??3;return v.jsx("div",{style:{position:"absolute",inset:0,border:`${Le}px solid ${Fe}`,boxShadow:`inset 0 0 12px ${Fe}`,pointerEvents:"none",transform:"translateZ(0)"}})})()]})}function KLe(){const e=Wm("player",()=>window.__CAMSTACK_EMBED__,QLe),[t,a]=P.useState(null),[r,c]=P.useState(null),m=P.useRef(null),d=P.useRef(null);d.current=r;const h=j=>{if(typeof j!="string"||j.length===0||d.current===j)return;const q=m.current;q!==null&&(q.setToken(j),q.reconnect(),c(j))};P.useEffect(()=>{const j=B=>{const F=pLe(B);F&&a(F)};window.__camstackEmbedPage={setDevice:j,setToken:h};const q=Gm(B=>{if(B.kind==="setDevice"){j(B.value);return}B.kind==="setToken"&&h(B.value)});return()=>{window.__camstackEmbedPage&&delete window.__camstackEmbedPage,q()}},[]);const f=P.useMemo(()=>{if(e===null||!e.ok)return null;const j=xm({serverUrl:e.config.serverUrl,token:e.config.token}),q=new uq({defaultOptions:{queries:{retry:!1,refetchOnWindowFocus:!1}}});return{system:j,queryClient:q}},[e]);if(P.useEffect(()=>{if(!f){m.current=null;return}return m.current=f.system,e!==null&&e.ok&&c(e.config.token),()=>{f.system.close(),m.current=null}},[f,e]),e===null)return null;if(!e.ok)return v.jsx(k_,{message:e.error});if(!f)return v.jsx(k_,{message:"Failed to initialise the embed player"});const k=t?.deviceId??e.config.deviceId,x=t?.target??e.config.target,E=t?.muted??e.config.muted,R=t?.stats??e.config.stats??!1,T=t!==null?t.snapshot:e.config.snapshot,N=r??e.config.token;return v.jsx(Zq,{system:f.system,children:v.jsx(pq,{client:f.queryClient,children:v.jsxs(S.Provider,{client:f.system.trpcClient,queryClient:f.queryClient,children:[v.jsx(Wg,{system:f.system}),v.jsx(VLe,{system:f.system,probeAuthToken:N,deviceId:k,initialTarget:x,initialMuted:E,initialStats:R,initialHighlight:e.config.highlight,initialSnapshot:T,initialSeekMs:t===null?e.config.initialSeekMs:t.atMs},k)]})})})}const GLe="recorder",WLe=o({serverUrl:n().min(1),token:n().min(1),deviceId:i().int().nonnegative(),startMs:i().int().nonnegative().optional(),provider:n().min(1).optional()});function ZLe(e){if(e==null)return{ok:!1,error:"config is required"};const t=WLe.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(a=>`${a.path.join(".")||"(root)"}: ${a.message}`).join("; ")}}function YLe(e,t){const a=(e-t)/1e3;return Number.isFinite(a)&&a>0?a:0}const S_=360*60*1e3,XLe="scrub unavailable: no open RecordedTrackSession";function Ri(e){qt(e)}function Pa(e,t,a){try{qt({type:"log",scope:e,msg:t,data:a})}catch{}try{console.debug(`[rec-embed:${e}] ${t}`,a??"")}catch{}}function JLe({system:e,config:t}){P.useEffect(()=>d7(t.deviceId),[t.deviceId]);const a=P.useRef(null),r=P.useRef(0),c=P.useRef(0),m=P.useRef(0),{box:d,fit:h}=Ux(),f=P.useMemo(()=>async k=>{const x=a.current;if(!x)return;const E=++m.current;c.current=performance.now(),Pa("loadAt","start",{epochMs:k,window:S_}),Ri({type:"state",state:"loading"});try{const R=await e.trpcClient.recording.getPlayback.query({deviceId:t.deviceId,provider:t.provider??GLe,fromMs:k,toMs:k+S_});if(E!==m.current){Pa("loadAt","superseded",{epochMs:k});return}if(R?.kind!=="hls"){const j=R?.kind==="clip"?"this source serves clips, not a playable HLS window":R?.reason??"no footage";Pa("loadAt","not-playable-here",{kind:R?.kind??null,why:j}),Ri({type:"state",state:"error",message:j});return}const T=R.manifest;if(Pa("loadAt","manifest",{playbackUrl:T?.playbackUrl??null,endpoints:T?.playbackEndpoints?.length??0,localMaster:!!T?.localMasterPath}),!T?.playbackUrl){Ri({type:"state",state:"error",message:"no footage"});return}x.src=T.playbackUrl;const N=()=>{if(E!==m.current)return;const j=typeof x.getStartDate=="function"?x.getStartDate():null,q=j instanceof Date&&!Number.isNaN(j.getTime())?j.getTime():k;r.current=q;const B=YLe(k,q);if(B>0)try{x.currentTime=B}catch(F){Pa("loadAt","seek-failed",{msg:String(F)})}x.play().catch(F=>{Pa("loadAt","play-rejected",{msg:String(F)})}),Pa("loadAt","seek",{epochMs:k,media0Ms:q,offsetSec:B})};x.readyState>=HTMLMediaElement.HAVE_METADATA?N():x.addEventListener("loadedmetadata",N,{once:!0}),Pa("loadAt","src-set",{src:T.playbackUrl})}catch(R){Pa("loadAt","error",{msg:R instanceof Error?R.message:String(R)}),Ri({type:"state",state:"error",message:R instanceof Error?R.message:String(R)})}},[e,t.deviceId]);return P.useEffect(()=>{Pa("init","mounted",{deviceId:t.deviceId,startMs:t.startMs??null,ua:navigator.userAgent});const k=(x,E)=>{Pa("scrub","unavailable",{command:x,...E===void 0?{}:{epochMs:E}}),Ri({type:"state",state:"error",message:XLe})};return window.__camstackRecording={seekTo:x=>{Pa("cmd","seekTo",{epochMs:x}),f(x)},play:()=>{Pa("cmd","play"),a.current?.play().catch(()=>{})},pause:()=>{Pa("cmd","pause"),a.current?.pause()},setRate:x=>{Pa("cmd","setRate",{rate:x}),a.current&&(a.current.playbackRate=x)},fit:(x,E)=>{Pa("cmd","fit",{w:x,h:E}),h(x,E)},scrubStart:()=>{Pa("cmd","scrubStart"),k("scrubStart")},scrubTo:x=>{Pa("cmd","scrubTo",{epochMs:x}),k("scrubTo",x)},scrubEnd:x=>{Pa("cmd","scrubEnd",{epochMs:x}),k("scrubEnd",x)}},t.startMs&&t.startMs>0&&f(t.startMs),()=>{window.__camstackRecording&&delete window.__camstackRecording}},[f,t.startMs,t.deviceId,h]),P.useEffect(()=>Gm(k=>{const x=window.__camstackRecording;if(!x)return;switch(k.kind){case"seekTo":x.seekTo(k.value);break;case"play":x.play();break;case"pause":x.pause();break;case"setRate":x.setRate(k.value);break;case"scrubStart":x.scrubStart();break;case"scrubTo":x.scrubTo(k.value);break;case"scrubEnd":x.scrubEnd(k.value);break;case"fit":x.fit(k.w,k.h);break}}),[]),v.jsx("div",{style:{position:"fixed",left:0,top:0,width:d.w,height:d.h,background:"#000"},children:v.jsx("video",{ref:a,playsInline:!0,controls:!1,style:{width:"100%",height:"100%",objectFit:"contain",background:"#000"},onLoadedMetadata:k=>Pa("video","loadedmetadata",{w:k.currentTarget.videoWidth,h:k.currentTarget.videoHeight,dur:k.currentTarget.duration}),onPlaying:()=>{Pa("video","playing",{vodStartMs:Math.round(performance.now()-c.current)}),Ri({type:"state",state:"playing"})},onPause:()=>Ri({type:"state",state:"paused"}),onEnded:()=>Ri({type:"state",state:"ended"}),onError:k=>{const x=k.currentTarget.error;Pa("video","error",{code:x?.code??null,message:x?.message??null}),Ri({type:"state",state:"error",message:x?.message||"video error"})},onTimeUpdate:k=>Ri({type:"position",positionMs:r.current+k.currentTarget.currentTime*1e3})})})}function e8e(){const e=Wm("recording",()=>window.__CAMSTACK_RECORDING__,ZLe),t=P.useMemo(()=>e===null||!e.ok?null:(document.cookie=`camstack_session=${e.config.token}; path=/; SameSite=Lax`,xm({serverUrl:e.config.serverUrl,token:e.config.token})),[e]);return P.useEffect(()=>()=>t?.close(),[t]),e===null?null:e.ok?t?v.jsx(JLe,{system:t,config:e.config}):(Ri({type:"state",state:"error",message:"init failed"}),null):(Ri({type:"state",state:"error",message:e.error}),null)}function t8e(e){return e.replace(/\/+$/,"")}function a8e(e,t){const a=e.includes("?")?"&":"?",r=`&size=${Math.round(t)}`;return`${e}${a}variant=thumb${r}`}function n8e(e,t){if(t===void 0||t.length===0)return null;if(t.startsWith("data:")||/^https?:\/\//i.test(t))return t;if(e===null||e.length===0)return null;const a=t8e(e);return t.startsWith("/")?`${a}${t}`:`${a}/${t}`}function i8e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function r8e(e){if(!Array.isArray(e))return[];const t=[];for(const a of e){if(!i8e(a))continue;const r=typeof a.mediaId=="number"?a.mediaId:null,c=typeof a.kind=="string"&&a.kind.length>0?a.kind:null;r===null||c===null||t.push({mediaId:r,kind:c,timestamp:typeof a.timestamp=="number"?a.timestamp:0,...typeof a.url=="string"&&a.url.length>0?{url:a.url}:{},...typeof a.sizeBytes=="number"?{sizeBytes:a.sizeBytes}:{}})}return t}function o8e(e){const t=new URLSearchParams(e),a=t.get("id")?.trim()??"";if(a.length===0)return null;const r=t.get("device")??t.get("deviceId"),c=r!==null&&/^\d+$/.test(r)?Number(r):null,m=t.get("best")??t.get("bestEventId");return{trackId:a,deviceId:c,bestEventId:m!==null&&m.length>0?m:null}}function s8e(e){return/clip|video/i.test(e)}const l8e=240;function c8e(e,t){const a=r8e(e),r=[];let c=null;for(const m of a){const d=n8e(t,m.url);if(d===null)continue;const h=`${m.kind}:${m.mediaId??r.length}`;if(s8e(m.kind)){c===null&&(c={key:h,kind:m.kind,url:d});continue}r.push({key:h,kind:m.kind,url:a8e(d,l8e)})}return{stills:r,clip:c}}function d8e(e,t){const a=Math.max(0,Math.round((t-e)/1e3));if(a<60)return`${a} s`;const r=Math.floor(a/60),c=a%60;return c===0?`${r} min`:`${r} min ${c} s`}const u8e={camera:"Camera",zone:"Zone",time:"Time",loading:"Loading",noCamera:"The track link names no camera (device=)",notFound:"Track not found",loadFailed:"Failed to load the track",noTrack:"The track link names no track (id=)",configError:"Track embed config error"},m8e={camera:"Camera",zone:"Zona",time:"Ora",loading:"Caricamento",noCamera:"Il link della traccia non indica la camera (device=)",notFound:"Traccia non trovata",loadFailed:"Impossibile caricare la traccia",noTrack:"Il link non indica nessuna traccia (id=)",configError:"Errore di configurazione dell’embed traccia"};function Qx(e){return e==="it"?m8e:u8e}const w_=320;async function p8e(e,t,a,r,c){if(t.deviceId===null)return{status:"error",message:c.noCamera};const m=new Map(a!==void 0?[[t.deviceId,a]]:[]),[d,h]=await Promise.all([e.trpcClient.pipelineAnalytics.getTrack.query({deviceId:t.deviceId,trackId:t.trackId}),e.trpcClient.pipelineAnalytics.listTrackMedia.query({deviceId:t.deviceId,trackId:t.trackId}).catch(()=>[])]),f=W8(d,m);return f===null?{status:"error",message:c.notFound}:{status:"ready",row:f,media:c8e(h,r)}}function x_({url:e,token:t,palette:a,style:r,alt:c}){const m=p7(e,t),d={background:a.skeleton,border:`1px solid ${a.border}`,borderRadius:10,overflow:"hidden",boxSizing:"border-box",...r};return m.status!=="ready"?v.jsx("div",{style:d,role:"img","aria-label":c}):v.jsx("div",{style:d,children:v.jsx("img",{src:m.src,alt:c,style:{width:"100%",height:"100%",objectFit:"contain",display:"block"}})})}function O7(e){return Bx(e.locale,typeof navigator>"u"?void 0:navigator.language)}function h8e({row:e,media:t,config:a,palette:r}){const c=pd(),m=O7(a),d=Qx(m),h=P.useMemo(()=>B8(a.labels,m),[a.labels,m]),f=P.useMemo(()=>Object.keys(a.kindLabels).length>0?H8(a.kindLabels):Kg,[a.kindLabels]),k=Z8(e,f),x=sw(e.className,ig(e),c),E=jS(U8(e.className,new Map,ig(e))),[R,T]=P.useState(null),N=t.stills.find(F=>F.key===R)?.url.replace(/&size=\d+/,`&size=${w_}`)??Nx(a.serverUrl,e.trackId,w_),j=e.zoneNames.length>0?e.zoneNames:[],q=[];e.active&&q.push(h.active),e.favourited===!0&&q.push(h.favourite),e.debug===!0&&q.push(h.debug),e.markForTrain===!0&&q.push(h.train);const B={background:r.chip,color:r.text,borderRadius:999,padding:"2px 10px",fontSize:12,lineHeight:"18px"};return v.jsxs("main",{"data-testid":"track-detail",style:{minHeight:"100%",boxSizing:"border-box",background:r.background,color:r.text,fontFamily:"system-ui, sans-serif",padding:12,display:"flex",flexDirection:"column",gap:12,maxWidth:720,margin:"0 auto"},children:[v.jsx(x_,{url:N,token:a.token,palette:r,alt:k.text,style:{width:"100%",aspectRatio:"4 / 3"}}),t.clip!==null&&a.token===void 0&&v.jsx("video",{"data-testid":"track-clip",src:t.clip.url,controls:!0,preload:"none",style:{width:"100%",borderRadius:10,background:r.skeleton}}),t.stills.length>1&&v.jsx("div",{"data-testid":"track-strip",style:{display:"flex",gap:8,overflowX:"auto",paddingBottom:2},children:t.stills.map(F=>v.jsx("button",{type:"button",onClick:()=>T(F.key),"aria-label":F.kind,style:{all:"unset",cursor:"pointer",flex:"0 0 auto",outline:F.key===R?`2px solid ${x}`:"none",borderRadius:10},children:v.jsx(x_,{url:F.url,token:a.token,palette:r,alt:F.kind,style:{width:84,height:84}})},F.key))}),v.jsxs("section",{style:{display:"flex",flexDirection:"column",gap:8},children:[v.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[v.jsx(E,{size:20,color:x,"aria-hidden":!0}),v.jsx("h1",{style:{fontSize:18,lineHeight:"24px",margin:0,fontWeight:600},children:k.fullText??k.text})]}),q.length>0&&v.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:q.map(F=>v.jsx("span",{style:B,children:F},F))}),v.jsxs("dl",{style:{margin:0,display:"grid",gridTemplateColumns:"auto 1fr",gap:"4px 12px",fontSize:13},children:[v.jsx("dt",{style:{color:r.textMuted},children:d.camera}),v.jsx("dd",{style:{margin:0},children:e.cameraName}),j.length>0&&v.jsxs(v.Fragment,{children:[v.jsx("dt",{style:{color:r.textMuted},children:d.zone}),v.jsx("dd",{style:{margin:0},children:j.join(", ")})]}),v.jsx("dt",{style:{color:r.textMuted},children:d.time}),v.jsxs("dd",{style:{margin:0},children:[cDe(e.lastSeen,Date.now(),m)," · ",d8e(e.firstSeen,e.lastSeen)]})]})]})]})}function lg({message:e,palette:t}){return v.jsx("div",{role:"status",style:{position:"fixed",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:t.background,color:t.textMuted,fontFamily:"system-ui, sans-serif",fontSize:13,padding:16,textAlign:"center"},children:e})}function f8e({config:e,query:t,palette:a}){const r=P.useMemo(()=>xm({serverUrl:e.serverUrl,token:e.token}),[e.serverUrl,e.token]);P.useEffect(()=>()=>r.close(),[r]);const[c,m]=P.useState({status:"loading"}),d=Qx(O7(e));return P.useEffect(()=>{let h=!0;return p8e(r,t,e.deviceNames[String(t.deviceId)],e.serverUrl,d).then(f=>h&&m(f)).catch(f=>h&&m({status:"error",message:f instanceof Error?f.message:d.loadFailed})),()=>{h=!1}},[r,t,e.deviceNames,e.serverUrl,d]),v.jsxs(v.Fragment,{children:[v.jsx(Wg,{system:r}),c.status==="loading"&&v.jsx(lg,{message:d.loading,palette:a}),c.status==="error"&&v.jsx(lg,{message:c.message,palette:a}),c.status==="ready"&&v.jsx(h8e,{row:c.row,media:c.media,config:e,palette:a})]})}function g8e(){const e=Wm("events",()=>window.__CAMSTACK_EVENTS__,Fx,y7,{urlFirst:!0}),t=P.useMemo(()=>o8e(location.search),[]),a=Ox(e!==null&&e.ok?e.config.theme:"auto",window.matchMedia?.("(prefers-color-scheme: dark)").matches??!0);if(e===null)return null;const r=Qx(Bx(e.ok?e.config.locale:void 0,typeof navigator>"u"?void 0:navigator.language));return e.ok?t===null?v.jsx(lg,{message:r.noTrack,palette:a}):v.jsx(f8e,{config:e.config,query:t,palette:a}):v.jsx(lg,{message:`${r.configError}: ${e.error}`,palette:a})}function v8e(){const e=window.__CAMSTACK_EMBED_MODE__??new URLSearchParams(location.search).get("mode")??new URLSearchParams(location.hash.replace(/^#/,"")).get("mode")??"grid";return e==="player"?v.jsx(KLe,{}):e==="recording"?v.jsx(e8e,{}):e==="events"?v.jsx(Wze,{}):e==="track"?v.jsx(g8e,{}):v.jsx(uLe,{})}const M_=document.getElementById("root");M_&&KB.createRoot(M_).render(v.jsx(v8e,{}));export{U3e as C,Nq as E,C8e as G,Dq as I,A8e as M,SIe as R,Hm as S,N8e as T,E8e as W,GIe as a,q8e as b,X as c,zIe as d,cs as e,R8e as f,z8e as g,j8e as h,T8e as i,v as j,O8e as k,R1 as l,I8e as m,kw as n,$B as o,qB as p,Xa as q,P as r,D8e as s,Vm as u,ff as v};
117
+ `;function b8({trpc:e,deviceId:t,layout:a,optimistic:r}){const{cap:c,slice:m,available:d}=Nt({trpc:e,deviceId:t,cap:F=>F.climateControl,slice:F=>F.state.climateControl}),{display:h,applyOptimistic:f}=ra(m,{enabled:r??!0});if(c===void 0||h===void 0)return null;const k=!d;if(a==="compact")return v.jsxs("div",{"data-mode":h.mode,className:"inline-flex items-center gap-1",children:[v.jsx("span",{className:ne("text-xs tabular-nums font-medium",QL[h.mode]),children:h.target!==null?v.jsxs(v.Fragment,{children:[h.target,"°",h.currentTemp!==null&&v.jsxs("span",{className:"text-foreground-subtle font-normal",children:[" ","(",h.currentTemp,"°)"]})]}):h.currentTemp!==null?v.jsxs("span",{className:"text-foreground-subtle",children:[h.currentTemp,"°"]}):null}),h.target!==null&&v.jsxs(v.Fragment,{children:[v.jsx("button",{type:"button","aria-label":"Decrease target",disabled:k,onClick:F=>{if(F.stopPropagation(),!k&&h.target!==null){const U=h.target-1;f({target:U}),c.setTarget({target:U})}},className:ne("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs",k&&"opacity-40 cursor-not-allowed"),children:"−"}),v.jsx("button",{type:"button","aria-label":"Increase target",disabled:k,onClick:F=>{if(F.stopPropagation(),!k&&h.target!==null){const U=h.target+1;f({target:U}),c.setTarget({target:U})}},className:ne("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs",k&&"opacity-40 cursor-not-allowed"),children:"+"})]}),v.jsx("select",{"aria-label":"Mode",value:h.mode,disabled:k,onChange:F=>{F.stopPropagation();const U=h.availableModes.find(H=>H===F.target.value);!k&&U&&(f({mode:U}),c.setMode({mode:U}))},className:ne("bg-transparent px-0.5 text-xs text-foreground-subtle hover:text-foreground cursor-pointer",k&&"opacity-40 cursor-not-allowed"),children:h.availableModes.map(F=>v.jsx("option",{value:F,children:U1[F]},F))})]});const x=LNe[h.mode],E=h.mode!=="off",R=$Ne(h.preset),T=h.preset==="turbo",N=Math.max(.55,UNe(h.fanMode)*(T?.6:1)),j=h.swingVertical!==null,q=h.swingHorizontal!==null,B=E&&(h.swingVertical===!0||h.swingHorizontal===!0);return v.jsxs("div",{"data-mode":h.mode,className:ne("relative flex flex-col items-stretch gap-2.5 overflow-hidden rounded-lg border p-3 transition-colors",Ix[h.mode]),children:[v.jsx("style",{children:HNe}),v.jsxs("div",{className:"relative z-10 flex flex-col items-center justify-center gap-1 overflow-hidden rounded-lg border border-border/50 bg-surface/30 px-3 py-3",children:[v.jsx("div",{className:"pointer-events-none absolute inset-0 opacity-60",children:v.jsx(KNe,{mode:h.mode,accent:x,periodSec:N,swaying:B})}),v.jsx("div",{className:"pointer-events-none absolute inset-0 bg-gradient-to-b from-surface/50 via-transparent to-surface/50"}),E&&v.jsx("span",{"aria-hidden":!0,className:"acv-glow pointer-events-none absolute left-1/2 top-1/2 h-16 w-16 -translate-x-1/2 -translate-y-1/2 rounded-full blur-2xl",style:{background:x,animation:"acv-glow 3.2s ease-in-out infinite"}}),v.jsxs("div",{className:"relative z-10 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide",style:{color:x},children:[v.jsx(K4,{mode:h.mode,className:"h-3.5 w-3.5"}),U1[h.mode],h.currentTemp!==null&&v.jsxs("span",{className:"normal-case text-foreground-subtle",children:["· ",h.currentTemp,"° now"]}),h.currentHumidity!==null&&v.jsxs("span",{className:"inline-flex items-center gap-0.5 normal-case text-foreground-subtle",children:[v.jsx(md,{className:"h-3 w-3"}),h.currentHumidity,"%"]})]}),h.target!==null?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"relative z-10 flex items-center gap-3",children:[v.jsx(G4,{label:"Decrease target",symbol:"−",disabled:k,onClick:()=>{if(k||h.target===null)return;const F=h.target-1;f({target:F}),c.setTarget({target:F})}}),v.jsxs("div",{className:"flex items-baseline gap-0.5",children:[v.jsx("span",{className:"text-4xl font-bold leading-none tabular-nums",style:{color:x},children:h.target}),v.jsx("span",{className:"text-lg text-foreground-subtle",children:"°"})]}),v.jsx(G4,{label:"Increase target",symbol:"+",disabled:k,onClick:()=>{if(k||h.target===null)return;const F=h.target+1;f({target:F}),c.setTarget({target:F})}})]}),v.jsx("div",{className:"relative z-10 w-36",children:v.jsx(VNe,{value:h.target,min:BNe,max:FNe,accent:x})})]}):v.jsxs("div",{className:"relative z-10 flex items-baseline gap-0.5",children:[v.jsx("span",{className:"text-4xl font-bold leading-none tabular-nums text-foreground",children:h.currentTemp??"—"}),v.jsx("span",{className:"text-lg text-foreground-subtle",children:"°"})]})]}),v.jsxs("div",{className:"relative z-10 grid grid-cols-3 gap-2",children:[v.jsx(H1,{label:"Mode",icon:v.jsx("span",{style:{color:x},className:"flex",children:v.jsx(K4,{mode:h.mode,className:"h-4 w-4"})}),value:h.mode,options:h.availableModes.map(F=>({value:F,label:U1[F]})),disabled:k,onChange:F=>{const U=h.availableModes.find(H=>H===F);U&&(f({mode:U}),c.setMode({mode:U}))}}),h.availableFanModes.length>0&&v.jsx(H1,{label:"Fan",icon:v.jsx(co,{className:"h-4 w-4 text-sky-500"}),value:h.fanMode,options:h.availableFanModes.map(F=>({value:F,label:V4(F)})),disabled:k,onChange:F=>{f({fanMode:F}),c.setFanMode({fanMode:F})}}),h.availablePresets.length>0&&v.jsx(H1,{label:"Preset",icon:v.jsx(R,{className:"h-4 w-4 text-emerald-500"}),value:h.preset,options:h.availablePresets.map(F=>({value:F,label:V4(F)})),disabled:k,onChange:F=>{f({preset:F}),c.setPreset({preset:F})}})]}),(j||q)&&v.jsx(QNe,{label:"Swing",children:v.jsxs("div",{className:"grid grid-cols-2 gap-1",children:[j&&v.jsx(W4,{axis:"vertical",on:h.swingVertical??!1,busy:k,onToggle:F=>{f({swingVertical:F}),c.setSwingVertical({on:F})}}),q&&v.jsx(W4,{axis:"horizontal",on:h.swingHorizontal??!1,busy:k,onToggle:F=>{f({swingHorizontal:F}),c.setSwingHorizontal({on:F})}})]})})]})}function QNe({label:e,children:t}){return v.jsxs("div",{className:"relative z-10 flex flex-col gap-1",children:[v.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle",children:e}),t]})}function K4({mode:e,className:t}){const a=qNe[e];return v.jsx(a,{className:t,"aria-hidden":!0})}function H1({label:e,icon:t,value:a,options:r,disabled:c,onChange:m}){return v.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[v.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle",children:e}),v.jsxs("div",{className:ne("flex items-center gap-1 overflow-hidden rounded-lg border border-border/60 bg-surface-subtle px-1.5 py-1.5",c&&"opacity-40"),children:[v.jsx("span",{className:"flex shrink-0",children:t}),v.jsx("select",{"aria-label":e,value:a,disabled:c,onChange:d=>{d.stopPropagation(),c||m(d.target.value)},className:"min-w-0 flex-1 cursor-pointer appearance-none truncate bg-transparent text-xs font-medium text-foreground outline-none",children:r.map(d=>v.jsx("option",{value:d.value,children:d.label},d.value))}),v.jsx(gl,{className:"h-3 w-3 shrink-0 text-foreground-subtle"})]})]})}function G4({label:e,symbol:t,disabled:a,onClick:r}){return v.jsx("button",{type:"button","aria-label":e,disabled:a,onClick:r,className:ne("flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border bg-surface text-lg leading-none text-foreground-subtle transition-colors hover:bg-surface-hover hover:text-foreground active:scale-95",a&&"opacity-40 cursor-not-allowed"),children:t})}function VNe({value:e,min:t,max:a,accent:r}){const c=`${Math.min(1,Math.max(0,(e-t)/(a-t)))*100}%`;return v.jsxs("div",{className:"mt-2 w-full",children:[v.jsxs("div",{className:"relative h-1.5 w-full rounded-full bg-surface-subtle",children:[v.jsx("div",{className:"absolute inset-y-0 left-0 rounded-full",style:{width:c,background:r}}),v.jsx("div",{className:"absolute top-1/2 h-3 w-3 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-surface shadow",style:{left:c,background:r}})]}),v.jsxs("div",{className:"mt-0.5 flex justify-between text-[9px] tabular-nums text-foreground-subtle",children:[v.jsxs("span",{children:[t,"°"]}),v.jsxs("span",{children:[a,"°"]})]})]})}function KNe({mode:e,accent:t,periodSec:a,swaying:r}){const c=[0,1,2,3,4,5],m=e==="heat",d=e==="dry";return v.jsx("div",{"aria-hidden":!0,className:"absolute inset-0 overflow-hidden",children:e==="off"?v.jsx("div",{className:"flex h-full items-center justify-center gap-2 opacity-30",children:c.map(h=>v.jsx("span",{className:"h-8 w-1 rounded-full bg-foreground-subtle opacity-40"},h))}):e==="fan_only"?v.jsx("div",{className:"flex h-full items-center justify-center",children:v.jsx(GNe,{color:t,periodSec:Math.max(.5,a*.7),size:56})}):v.jsx("div",{className:ne("acv-sway-wrap absolute inset-0",r&&"acv-sway"),style:r?{animation:"acv-sway 2.6s ease-in-out infinite"}:void 0,children:c.map(h=>v.jsx("span",{className:"acv-streak absolute rounded-full",style:{left:`${8+h*15}%`,width:d?"0.4rem":"0.3rem",height:d?"0.4rem":"1.9rem",background:t,boxShadow:`0 0 6px ${t}`,animationName:m?"acv-rise":"acv-fall",animationTimingFunction:"linear",animationIterationCount:"infinite",animationDuration:`${a}s`,animationDelay:`${h%3*(a/3)+h*.05}s`}},h))})})}function GNe({color:e,periodSec:t,size:a}){return v.jsxs("svg",{width:a,height:a,viewBox:"0 0 100 100",className:"acv-fan",style:{animation:`acv-spin ${t}s linear infinite`,transformOrigin:"50% 50%"},"aria-hidden":!0,children:[[0,120,240].map(r=>v.jsx("path",{d:"M50 50 C 58 30, 78 26, 84 12 C 66 20, 54 34, 50 50 Z",fill:e,opacity:.85,transform:`rotate(${r} 50 50)`},r)),v.jsx("circle",{cx:"50",cy:"50",r:"7",fill:e})]})}function W4({axis:e,on:t,busy:a,onToggle:r}){const c=e==="vertical"?"Vertical":"Horizontal",m=e==="vertical"?pIe:mIe,d=e==="vertical"?"acv-swing-v":"acv-swing-h";return v.jsxs("button",{type:"button","aria-label":`${c} swing`,"aria-pressed":t,disabled:a,onClick:()=>{a||r(!t)},className:ne("flex items-center justify-center gap-2 rounded-lg border px-2 py-1.5 text-xs font-medium transition-colors",t?"border-transparent bg-indigo-400 text-indigo-950 shadow-sm":"border-border/60 bg-surface-subtle text-foreground-subtle hover:bg-surface-hover hover:text-foreground",a&&"opacity-40 cursor-not-allowed"),children:[v.jsx(m,{className:"acv-swing h-4 w-4","aria-hidden":!0,style:t?{animation:`${d} 1.4s ease-in-out infinite`}:void 0}),c]})}var WNe=5,ZNe=35;function Q1(e,t,a){return Math.min(1,Math.max(0,(e-t)/(a-t)))}function V1(e,t,a){return Math.round(t+e*(a-t))}var ao=176,tg=76,bf=2*Math.PI*tg,bu=bf*(270/360),K1=ao/2-tg-10;function Z4(e){const t=ao/2,a=ao/2,r=bf-bu,c=e.mode==="band"?(()=>{const m=e.band.from*bu,d=Math.max(0,(e.band.to-e.band.from)*bu);return{dasharray:`${d} ${bf-d}`,dashoffset:-m}})():(()=>{const m=e.fraction*bu;return{dasharray:`${m} ${bf-m}`,dashoffset:void 0}})();return v.jsxs("svg",{width:ao,height:ao,viewBox:`0 0 ${ao} ${ao}`,"aria-hidden":"true",className:"absolute inset-0",style:{transform:"rotate(135deg)"},children:[v.jsx("circle",{cx:t,cy:a,r:tg,fill:"none",stroke:"var(--color-border)",strokeWidth:12,strokeDasharray:`${bu} ${r}`,strokeLinecap:"round"}),v.jsx("circle",{cx:t,cy:a,r:tg,fill:"none",stroke:e.color,strokeWidth:12,strokeDasharray:c.dasharray,...c.dashoffset!==void 0?{strokeDashoffset:c.dashoffset}:{},strokeLinecap:"round"})]})}var YNe={heat:"#f59e0b",cool:"#60a5fa",auto:"#c084fc",heat_cool:"#e879f9",fan_only:"#94a3b8",dry:"#22d3ee",off:"#d4d4d8"};function XNe({trpc:e,deviceId:t,features:a,optimistic:r}){const{cap:c,slice:m,available:d}=Nt({trpc:e,deviceId:t,cap:B=>B.climateControl,slice:B=>B.state.climateControl}),{display:h,applyOptimistic:f}=ra(m,{enabled:r??!0});if(c===void 0||h===void 0)return null;const k=!d,x=YNe[h.mode],E=h.mode==="heat_cool"||h.targetLow!==null&&h.targetHigh!==null,R=WNe,T=ZNe,N=!E&&h.target!==null?Q1(h.target,R,T):0,j=E&&h.targetLow!==null?Q1(h.targetLow,R,T):0,q=E&&h.targetHigh!==null?Q1(h.targetHigh,R,T):0;return v.jsxs("div",{"data-mode":h.mode,className:ne("flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4 transition-colors",Ix[h.mode]),children:[v.jsxs("div",{className:"flex flex-col items-center gap-3",children:[v.jsxs("div",{className:"relative",style:{width:ao,height:ao},children:[E?v.jsx(Z4,{mode:"band",band:{from:j,to:q},color:x}):v.jsx(Z4,{mode:"fill",fraction:N,color:x}),E?v.jsxs(v.Fragment,{children:[v.jsx("div",{"data-testid":"arc-knob",children:v.jsx(vf,{fraction:j,color:x,knobTopPx:K1,onDragFraction:B=>{if(k||h.targetHigh===null)return;const F=Math.min(V1(B,R,T),h.targetHigh);f({targetLow:F}),c.setTargetRange({targetLow:F,targetHigh:h.targetHigh})}})}),v.jsx("div",{"data-testid":"arc-knob",children:v.jsx(vf,{fraction:q,color:x,knobTopPx:K1,onDragFraction:B=>{if(k||h.targetLow===null)return;const F=Math.max(V1(B,R,T),h.targetLow);f({targetHigh:F}),c.setTargetRange({targetLow:h.targetLow,targetHigh:F})}})})]}):v.jsx("div",{"data-testid":"arc-knob",children:v.jsx(vf,{fraction:N,color:x,knobTopPx:K1,onDragFraction:B=>{if(k)return;const F=V1(B,R,T);f({target:F}),c.setTarget({target:F})}})}),v.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-0.5 pointer-events-none",children:[v.jsxs("div",{"data-testid":"current-temp",className:"text-4xl font-bold tabular-nums text-foreground leading-none",children:[h.currentTemp!==null?h.currentTemp:"—",v.jsx("span",{className:"text-lg text-foreground-subtle font-normal ml-0.5",children:"°"})]}),!E&&h.target!==null&&v.jsxs("div",{className:"text-xs font-semibold",style:{color:x},children:["set ",h.target,"°"]}),E&&h.targetLow!==null&&h.targetHigh!==null&&v.jsxs("div",{className:"text-xs font-semibold",style:{color:x},children:[h.targetLow,"° – ",h.targetHigh,"°"]})]})]}),!E&&h.target!==null&&v.jsx("div",{className:"w-[200px]",children:v.jsx(UL,{value:`${h.target}°`,onDelta:B=>{if(k||h.target===null)return;const F=h.target+B;f({target:F}),c.setTarget({target:F})}})})]}),v.jsx("select",{"aria-label":"Mode",value:h.mode,disabled:k,onChange:B=>{B.stopPropagation();const F=B.target.value;!k&&F&&(f({mode:h.availableModes.find(U=>U===F)??h.mode}),c.setMode({mode:h.availableModes.find(U=>U===F)??h.mode}))},className:ne("w-full rounded border border-border bg-surface px-3 py-1.5 text-sm",k&&"opacity-40 cursor-not-allowed"),children:h.availableModes.map(B=>v.jsx("option",{value:B,children:B},B))})]})}function JNe(e){return e==="locked"||e==="locking"}function k8(e){return e==="jammed"}var eOe={locked:{colorClass:"border-success/30 bg-success/10 text-success",icon:"locked"},locking:{colorClass:"border-success/30 bg-success/10 text-success",icon:"locked"},unlocked:{colorClass:"border-warning/30 bg-warning/10 text-warning",icon:"open"},unlocking:{colorClass:"border-warning/30 bg-warning/10 text-warning",icon:"open"},jammed:{colorClass:"border-danger/30 bg-danger/10 text-danger",icon:"locked"}};function tOe({state:e}){const t=eOe[e];return v.jsx("div",{"data-testid":"lock-glyph","data-state":e,className:ne("flex h-16 w-16 items-center justify-center rounded-full border-2",t.colorClass),children:t.icon==="locked"?v.jsx(Bm,{className:"h-8 w-8","aria-hidden":"true"}):v.jsx(NS,{className:"h-8 w-8","aria-hidden":"true"})})}function aOe({state:e}){return v.jsx("span",{className:ne("text-sm font-medium capitalize",k8(e)?"text-danger":"text-foreground-muted"),children:e})}function nOe({busy:e,onOpen:t}){return v.jsxs("button",{type:"button","aria-label":"Open (unlatch)",title:"Open (unlatch)",disabled:e,onClick:a=>{a.stopPropagation(),t()},className:ne("inline-flex items-center gap-1.5 rounded-md border border-border px-3 py-1.5 text-xs font-medium","text-foreground-muted hover:bg-surface-hover transition-colors",e&&"opacity-40 cursor-not-allowed"),children:[v.jsx(Zc,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Open"]})}function iOe({trpc:e,deviceId:t,features:a,optimistic:r}){const{cap:c,slice:m,available:d}=Nt({trpc:e,deviceId:t,cap:j=>j.lockControl,slice:j=>j.state.lockControl}),{display:h,applyOptimistic:f}=ra(m,{enabled:r??!0});if(c===void 0||h===void 0)return null;const k=JNe(h.state),x=k8(h.state)||!d,E=a?.includes(Ht.LockOpen)===!0,R=()=>{x||(k?(f({state:"unlocking"}),c.unlock({})):(f({state:"locking"}),c.lock({})))},T=()=>{x||c.open({})},N=k?"Unlock":"Lock";return v.jsxs("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:[v.jsxs("div",{className:"flex flex-col items-center gap-2",children:[v.jsx(tOe,{state:h.state}),v.jsx(aOe,{state:h.state})]}),v.jsx("div",{className:ne(x&&"pointer-events-none opacity-40"),children:v.jsx(H_e,{on:k,targetLabel:N,onConfirm:R})}),E&&v.jsx("div",{className:"flex justify-center",children:v.jsx(nOe,{busy:x,onOpen:T})})]})}var nw=500,S8=150,rOe="linear-gradient(90deg, #9ec9ff, #ffffff, #ffb24d)";function oOe(e,t,a){return Math.min(1,Math.max(0,(e-t)/(a-t)))}function sOe(e){return oOe(e,S8,nw)}var lOe="#f4b740",cOe="#d4d4d8";function dOe({trpc:e,deviceId:t,features:a,optimistic:r}){const c=Nt({trpc:e,deviceId:t,cap:H=>H.switch,slice:H=>H.state.switch}),m=Nt({trpc:e,deviceId:t,cap:H=>H.brightness,slice:H=>H.state.brightness}),d=Nt({trpc:e,deviceId:t,cap:H=>H.color,slice:H=>H.state.color}),h=ra(c.slice,{enabled:r??!0}),f=ra(m.slice,{enabled:r??!0}),k=ra(d.slice,{enabled:r??!0});if(c.cap===void 0||h.display===void 0)return null;const x=h.display.on===!0,E=!c.available,R=f.display?.percentage??0,T=!m.available,N=x?R/100:0,j=x?lOe:cOe,q=(a?.includes(Ht.LightColorMired)??!1)&&d.cap!==void 0,B=k.display?.mireds,F=!d.available,U=()=>{if(E)return;const H=!x;h.applyOptimistic({on:H}),c.cap?.setState({on:H})};return v.jsxs("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:[v.jsxs("div",{className:"flex flex-col items-center gap-3",children:[v.jsxs(HL,{fraction:N,color:j,children:[v.jsxs("div",{"data-testid":"brightness-readout",className:"text-3xl font-bold tabular-nums text-foreground leading-none",children:[R,v.jsx("span",{className:"text-base text-foreground-subtle font-normal ml-0.5",children:"%"})]}),v.jsx(Fg,{className:"h-5 w-5 text-foreground-subtle","aria-hidden":"true"})]}),m.cap!==void 0&&v.jsxs("label",{className:"flex w-full items-center gap-2 text-xs text-foreground-subtle",children:[v.jsx("span",{className:"w-16",children:"Brightness"}),v.jsx("input",{"aria-label":"Brightness",type:"range",min:0,max:100,step:1,className:"flex-1",value:R,disabled:T||!x,onChange:H=>{const Q=Number(H.target.value);f.applyOptimistic({percentage:Q}),T||m.cap?.setBrightness({percentage:Q})}}),v.jsxs("span",{className:"tabular-nums w-9 text-right",children:[R,"%"]})]})]}),v.jsxs("div",{className:"flex items-center justify-between",children:[v.jsx("span",{className:"text-sm font-medium text-foreground-muted",children:x?"On":"Off"}),v.jsx(Cx,{on:x,busy:E,onToggle:U})]}),q&&v.jsxs("div",{className:"flex items-center gap-2","data-testid":"color-temp-strip",children:[v.jsx(Ug,{className:"h-4 w-4 text-foreground-subtle","aria-hidden":"true"}),v.jsxs("label",{className:"flex-1",children:[v.jsx("span",{className:"sr-only",children:"Colour temperature"}),v.jsx("input",{"aria-label":"Colour temperature",type:"range",min:S8,max:nw,step:1,className:"w-full",value:B??nw,disabled:F||!x,onChange:H=>{const Q=Number(H.target.value);k.applyOptimistic({mode:"mired",mireds:Q}),F||d.cap?.setColor({color:{mode:"mired",mireds:Q}})}}),v.jsx("div",{className:"pointer-events-none mt-1",children:v.jsx(ew,{fraction:B!==void 0?sOe(B):.5,color:rOe})})]})]})]})}var uOe="#3aa6a0",mOe="#d4d4d8";function pOe({trpc:e,deviceId:t,features:a,optimistic:r}){const c=Nt({trpc:e,deviceId:t,cap:W=>W.switch,slice:W=>W.state.switch}),m=Nt({trpc:e,deviceId:t,cap:W=>W.fanControl,slice:W=>W.state.fanControl}),d=ra(c.slice,{enabled:r??!0}),h=ra(m.slice,{enabled:r??!0});if(c.cap===void 0||d.display===void 0)return null;const f=d.display.on===!0,k=!c.available,x=h.display?.percentage??0,E=!m.available,R=f?x/100:0,T=f?uOe:mOe,N=a?.includes(Ht.FanSpeed)??!1,j=(a?.includes(Ht.FanOscillating)??!1)&&m.cap!==void 0,q=h.display?.availablePresets??[],B=(a?.includes(Ht.FanPreset)??!1)&&m.cap!==void 0&&q.length>0,F=h.display?.preset??"",U=h.display?.oscillating===!0,H=()=>{if(k)return;const W=!f;d.applyOptimistic({on:W}),c.cap?.setState({on:W})},Q=()=>{if(E)return;const W=!U;h.applyOptimistic({oscillating:W}),m.cap?.setOscillating({oscillating:W})},te=W=>{if(E)return;const oe=h.display;if(oe===void 0)return;const he=oe.percentageStep!==void 0&&oe.percentageStep>0?oe.percentageStep:1,Ae=Math.min(100,Math.max(0,Math.round(W*100/he)*he));h.applyOptimistic({percentage:Ae}),m.cap?.setPercentage({percentage:Ae})},K=W=>{E||W===""||(h.applyOptimistic({preset:W}),m.cap?.setPreset({preset:W}))};return v.jsxs("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:[v.jsx("div",{className:"flex flex-col items-center gap-3",children:N?v.jsxs(HL,{fraction:R,color:T,onDragFraction:te,children:[v.jsxs("div",{"data-testid":"speed-readout",className:"text-3xl font-bold tabular-nums text-foreground leading-none",children:[x,v.jsx("span",{className:"text-base text-foreground-subtle font-normal ml-0.5",children:"%"})]}),v.jsx(Vf,{className:"h-5 w-5 text-foreground-subtle","aria-hidden":"true"})]}):v.jsx("div",{"data-testid":"fan-onoff-icon",className:"flex h-[150px] w-[150px] items-center justify-center",children:v.jsx(Vf,{className:"h-16 w-16",style:{color:T},"aria-hidden":"true"})})}),B&&v.jsx("div",{className:"flex justify-center",children:v.jsxs("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[v.jsx("span",{children:"Preset"}),v.jsxs("select",{"aria-label":"Fan preset",value:F,disabled:E,onChange:W=>{W.stopPropagation(),K(W.target.value)},className:ne("bg-surface border border-border rounded px-1 py-0.5",E&&"opacity-40 cursor-not-allowed"),children:[v.jsx("option",{value:"",disabled:!0,children:"—"}),q.map(W=>v.jsx("option",{value:W,children:W},W))]})]})}),v.jsxs("div",{className:"flex items-center justify-between gap-2",children:[j?v.jsxs("button",{type:"button","aria-label":"Oscillate","aria-pressed":U,disabled:E,onClick:W=>{W.stopPropagation(),Q()},className:ne("inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs font-medium transition-colors",U?"border-success/50 bg-success/10 text-success":"border-border text-foreground-muted hover:bg-surface-hover",E&&"opacity-40 cursor-not-allowed"),children:[v.jsx(dx,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Oscillate"]}):v.jsx("span",{className:"text-sm font-medium text-foreground-muted",children:f?"On":"Off"}),v.jsx(Cx,{on:f,busy:k,onToggle:H})]})]})}function hOe({trpc:e,deviceId:t,optimistic:a}){const{cap:r,slice:c,available:m}=Nt({trpc:e,deviceId:t,cap:E=>E.switch,slice:E=>E.state.switch}),{display:d,applyOptimistic:h}=ra(c,{enabled:a??!0});if(r===void 0||d===void 0)return null;const f=d.on===!0,k=!m,x=()=>{if(k)return;const E=!f;h({on:E}),r.setState({on:E})};return v.jsxs("div",{className:"flex flex-col items-center gap-4 rounded-lg border border-border bg-surface p-6",children:[v.jsx("div",{"data-testid":"switch-glyph","data-state":f?"on":"off",className:ne("flex h-16 w-16 items-center justify-center rounded-full border-2 transition-colors",f?"border-success/30 bg-success/10 text-success":"border-border bg-surface-subtle text-foreground-subtle"),children:v.jsx($m,{className:"h-8 w-8","aria-hidden":"true"})}),v.jsx("span",{className:"text-sm font-medium text-foreground-muted",children:f?"On":"Off"}),v.jsx(Cx,{on:f,busy:k,onToggle:x})]})}function fOe(e){return e==="playing"||e==="buffering"?"pause":"play"}function gOe(e,t){return e===null||t===null||t<=0?0:Math.min(1,Math.max(0,e/t))}function Y4(e){if(e===null)return"--:--";const t=Math.floor(e/1e3);return`${Math.floor(t/60)}:${(t%60).toString().padStart(2,"0")}`}function vOe({title:e,subtitle:t}){return v.jsxs("div",{className:"flex flex-col items-center gap-1 text-center",children:[v.jsx(Lq,{className:"h-6 w-6 text-foreground-subtle","aria-hidden":"true"}),v.jsx("span",{className:"text-base font-semibold text-foreground line-clamp-1",children:e??"Nothing playing"}),t&&v.jsx("span",{className:"text-xs text-foreground-subtle line-clamp-1",children:t})]})}function G1({label:e,busy:t,onPress:a,children:r,primary:c}){return v.jsx("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:m=>{m.stopPropagation(),t||a()},className:ne("inline-flex items-center justify-center rounded-full transition-colors",c?"h-12 w-12 bg-primary text-primary-foreground hover:bg-primary/90 shadow-md":"h-10 w-10 text-foreground-muted hover:bg-surface-hover",t&&"opacity-40 cursor-not-allowed"),children:r})}function yOe({trpc:e,deviceId:t,features:a,optimistic:r}){const{cap:c,slice:m,available:d}=Nt({trpc:e,deviceId:t,cap:U=>U.mediaPlayer,slice:U=>U.state.mediaPlayer}),{display:h,applyOptimistic:f}=ra(m,{enabled:r??!0});if(c===void 0||h===void 0)return null;const k=!d,x=fOe(h.state),E=(a?.includes(Ht.MediaPlayerSeek)??!1)&&h.durationMs!==null&&h.durationMs>0,R=a?.includes(Ht.MediaPlayerNext)??!1,T=a?.includes(Ht.MediaPlayerPrevious)??!1,N=(a?.includes(Ht.MediaPlayerVolume)??!1)&&h.volumeLevel!==null,j=()=>{k||(x==="play"?(f({state:"playing"}),c.play({})):(f({state:"paused"}),c.pause({})))},q=h.currentMedia?.artist??h.currentMedia?.album??null,B=gOe(h.positionMs,h.durationMs),F=h.volumeLevel??0;return v.jsxs("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-6",children:[v.jsx(vOe,{title:h.currentMedia?.title??null,subtitle:q}),E&&v.jsxs("div",{"data-testid":"media-seek",className:"flex flex-col gap-1",children:[v.jsxs("label",{className:"relative block",children:[v.jsx("span",{className:"sr-only",children:"Seek"}),v.jsx("input",{"aria-label":"Seek",type:"range",min:0,max:h.durationMs??0,step:1e3,className:"absolute inset-0 h-4 w-full cursor-pointer opacity-0",value:h.positionMs??0,disabled:k,onChange:U=>{if(k)return;const H=Number(U.target.value);f({positionMs:H}),c.seek({positionMs:H})}}),v.jsx("div",{className:"pointer-events-none",children:v.jsx(ew,{fraction:B})})]}),v.jsxs("div",{className:"flex justify-between text-[11px] tabular-nums text-foreground-subtle",children:[v.jsx("span",{children:Y4(h.positionMs)}),v.jsx("span",{children:Y4(h.durationMs)})]})]}),v.jsxs("div",{className:"flex items-center justify-center gap-4",children:[T&&v.jsx(G1,{label:"Previous",busy:k,onPress:()=>{c.previous({})},children:v.jsx(EIe,{className:"h-5 w-5","aria-hidden":"true"})}),v.jsx(G1,{label:x==="play"?"Play":"Pause",busy:k,onPress:j,primary:!0,children:x==="play"?v.jsx(vl,{className:"h-6 w-6","aria-hidden":"true"}):v.jsx(Fm,{className:"h-6 w-6","aria-hidden":"true"})}),R&&v.jsx(G1,{label:"Next",busy:k,onPress:()=>{c.next({})},children:v.jsx(RIe,{className:"h-5 w-5","aria-hidden":"true"})})]}),N&&v.jsxs("div",{"data-testid":"media-volume",className:"flex items-center gap-2",children:[v.jsx("button",{type:"button","aria-label":h.isMuted===!0?"Unmute":"Mute",title:h.isMuted===!0?"Unmute":"Mute",disabled:k,onClick:U=>{if(U.stopPropagation(),k||h.isMuted===null)return;const H=!h.isMuted;f({isMuted:H}),c.setMute({muted:H})},className:ne("inline-flex h-7 w-7 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",k&&"opacity-40 cursor-not-allowed"),children:h.isMuted===!0?v.jsx(Vq,{className:"h-4 w-4","aria-hidden":"true"}):v.jsx(Qm,{className:"h-4 w-4","aria-hidden":"true"})}),v.jsxs("label",{className:"relative block flex-1",children:[v.jsx("span",{className:"sr-only",children:"Volume"}),v.jsx("input",{"aria-label":"Volume",type:"range",min:0,max:100,step:1,className:"absolute inset-0 h-4 w-full cursor-pointer opacity-0",value:F,disabled:k,onChange:U=>{if(k)return;const H=Number(U.target.value);f({volumeLevel:H}),c.setVolume({volumeLevel:H})}}),v.jsx("div",{className:"pointer-events-none",children:v.jsx(ew,{fraction:F/100})})]}),v.jsxs("span",{className:"w-9 text-right text-[11px] tabular-nums text-foreground-subtle",children:[F,"%"]})]})]})}var w8={disarmed:{label:"Disarmed",colorClass:"border-border bg-surface-subtle text-foreground-subtle",icon:"disarmed"},armed_home:{label:"Armed Home",colorClass:"border-success/30 bg-success/10 text-success",icon:"armed"},armed_away:{label:"Armed Away",colorClass:"border-success/30 bg-success/10 text-success",icon:"armed"},armed_night:{label:"Armed Night",colorClass:"border-success/30 bg-success/10 text-success",icon:"armed"},armed_vacation:{label:"Armed Vacation",colorClass:"border-success/30 bg-success/10 text-success",icon:"armed"},armed_custom_bypass:{label:"Armed (Bypass)",colorClass:"border-success/30 bg-success/10 text-success",icon:"armed"},arming:{label:"Arming…",colorClass:"border-warning/30 bg-warning/10 text-warning",icon:"pending"},disarming:{label:"Disarming…",colorClass:"border-warning/30 bg-warning/10 text-warning",icon:"pending"},pending:{label:"Pending",colorClass:"border-warning/30 bg-warning/10 text-warning",icon:"pending"},triggered:{label:"Triggered",colorClass:"border-danger/30 bg-danger/10 text-danger",icon:"triggered"}},x8={home:"Home",away:"Away",night:"Night",vacation:"Vacation",custom_bypass:"Bypass"};function M8(e){return e.startsWith("armed_")}function Rx(e){return e==="arming"||e==="disarming"}function C8({icon:e,sizeClass:t="h-8 w-8"}){return e==="disarmed"?v.jsx(AIe,{className:t,"aria-hidden":"true"}):e==="triggered"?v.jsx(Um,{className:t,"aria-hidden":"true"}):e==="pending"?v.jsx(IIe,{className:t,"aria-hidden":"true"}):v.jsx(CIe,{className:t,"aria-hidden":"true"})}function X4({label:e,active:t,busy:a,onSelect:r}){return v.jsx("button",{type:"button","aria-label":e,"aria-pressed":t,disabled:a,onClick:c=>{c.stopPropagation(),a||r()},className:ne("flex-1 rounded-md px-3 py-2 text-sm font-medium transition-colors",t?"bg-primary text-primary-foreground shadow-sm":"text-foreground-muted hover:bg-surface-hover",a&&"opacity-40 cursor-not-allowed"),children:e})}function bOe({state:e,availableModes:t,busy:a,onDisarm:r,onArm:c}){const m=M8(e),d=Rx(e);return v.jsxs("div",{className:ne("flex min-w-0 items-stretch gap-1 rounded-lg border border-border bg-surface-subtle p-1"),children:[v.jsx(X4,{label:"Disarm",active:!m&&!d,busy:a,onSelect:r}),t.map(h=>v.jsx(X4,{label:x8[h],active:!d&&e===`armed_${h}`,busy:a,onSelect:()=>c(h)},h))]})}function J4(e){return e instanceof Error?e.message:String(e)}function A8(e,t,a){const{cap:r,slice:c,available:m}=Nt({trpc:e,deviceId:t,cap:q=>q.alarmPanel,slice:q=>q.state.alarmPanel}),{display:d,applyOptimistic:h,rollback:f}=ra(c,{enabled:a??!0}),[k,x]=P.useState(null),E=()=>x(null),R=P.useRef(0);P.useEffect(()=>{x(null)},[c]);const T=!m;return{display:d,capPresent:r!==void 0,busy:T,handleDisarm:()=>{if(r===void 0||T)return;const q=++R.current;h({state:"disarming"}),r.disarm({}).catch(B=>{R.current===q&&(f(),x(J4(B)))})},handleArm:q=>{if(r===void 0||T)return;const B=++R.current;h({state:"arming"}),r.arm({mode:q}).catch(F=>{R.current===B&&(f(),x(J4(F)))})},error:k,clearError:E}}function kOe({trpc:e,deviceId:t,optimistic:a}){const{display:r,capPresent:c,busy:m,handleDisarm:d,handleArm:h,error:f}=A8(e,t,a);if(!c||r===void 0)return null;const k=w8[r.state],x=M8(r.state)?r.state.replace("armed_",""):"";return v.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[v.jsxs("span",{className:ne("inline-flex shrink-0 items-center gap-1 rounded-md border px-1.5 py-0.5 text-[11px] font-medium whitespace-nowrap",k.colorClass,Rx(r.state)&&"animate-pulse"),children:[v.jsx(C8,{icon:k.icon,sizeClass:"h-3 w-3"}),k.label]}),v.jsxs("select",{"aria-label":"Alarm mode",disabled:m,value:x,onClick:E=>E.stopPropagation(),onChange:E=>{E.stopPropagation();const R=E.target.value;R===""?d():h(R)},className:ne("min-w-0 shrink rounded-md border border-border bg-surface-subtle px-1.5 py-0.5 text-xs text-foreground-muted",m&&"cursor-not-allowed opacity-40"),children:[v.jsx("option",{value:"",children:"Disarm"}),r.availableModes.map(E=>v.jsx("option",{value:E,children:x8[E]},E))]}),f!==null&&v.jsx("span",{"data-testid":"alarm-inline-error",role:"alert",title:f,className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-danger/10 text-danger",children:v.jsx(Um,{className:"h-3 w-3","aria-hidden":"true"})})]})}function SOe({trpc:e,deviceId:t,optimistic:a}){const{display:r,capPresent:c,busy:m,handleDisarm:d,handleArm:h,error:f,clearError:k}=A8(e,t,a);if(!c||r===void 0)return null;const x=w8[r.state];return v.jsxs("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-6",children:[v.jsxs("div",{className:"flex flex-col items-center gap-2",children:[v.jsx("div",{"data-testid":"alarm-state","data-state":r.state,className:ne("flex h-16 w-16 items-center justify-center rounded-full border-2",x.colorClass,Rx(r.state)&&"animate-pulse"),children:v.jsx(C8,{icon:x.icon})}),v.jsx("span",{className:ne("text-sm font-medium",x.colorClass,"border-0 bg-transparent"),children:x.label})]}),v.jsx(bOe,{state:r.state,availableModes:r.availableModes,busy:m,onDisarm:d,onArm:h}),f!==null&&v.jsxs("div",{"data-testid":"alarm-error",role:"alert",className:"flex items-start justify-between gap-2 rounded-md border border-danger/30 bg-danger/10 px-3 py-2 text-sm text-danger",children:[v.jsx("span",{children:f}),v.jsx("button",{type:"button","aria-label":"Dismiss",onClick:E=>{E.stopPropagation(),k()},className:"shrink-0 font-medium text-danger/80 hover:text-danger",children:"×"})]})]})}function wOe(e,t){if(e<=0)return null;const a=Math.max(0,Math.round((t-e)/1e3));return a<60?"just now":a<3600?`${Math.floor(a/60)} min ago`:a<86400?`${Math.floor(a/3600)} h ago`:new Date(e).toLocaleDateString()}function Tx({atMs:e,neverLabel:t}){const a=wOe(e,Date.now());return v.jsx("span",{className:"text-xs text-foreground-subtle","data-testid":"last-run",children:a===null?t:a})}function I8({error:e}){return e===null||e===""?null:v.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-danger",title:e,"data-testid":"last-error",children:[v.jsx(Yc,{className:"h-3 w-3 shrink-0","aria-hidden":"true"}),v.jsx("span",{className:"truncate",children:e})]})}function E8(e,t,a){const{cap:r,slice:c,available:m}=Nt({trpc:e,deviceId:t,cap:x=>x.scriptRunner,slice:x=>x.state.scriptRunner}),{display:d,applyOptimistic:h}=ra(c,{enabled:a??!0}),f=!m,k=d?.isRunning===!0;return{display:d,capPresent:r!==void 0,busy:f,running:k,run:()=>{r===void 0||f||k||(h({isRunning:!0}),r.run({}))},stop:()=>{r===void 0||f||!k||(h({isRunning:!1}),r.stop({}))}}}function R8({running:e,busy:t,large:a,onRun:r,onStop:c}){const m=e?"Stop":"Run";return v.jsxs("button",{type:"button","aria-label":m,title:m,disabled:t,"data-testid":"script-run","data-running":e?"true":"false",onClick:d=>{d.stopPropagation(),e?c():r()},className:ne("inline-flex items-center gap-1 rounded transition-colors",a?"h-10 px-4 text-sm":"h-5 px-1.5 text-xs",e?"bg-danger text-danger-foreground hover:bg-danger/90":"bg-primary text-primary-foreground hover:bg-primary/90",t&&"cursor-not-allowed opacity-40"),children:[e?v.jsx(V3e,{className:a?"h-4 w-4":"h-3 w-3","aria-hidden":"true"}):v.jsx(vl,{className:a?"h-4 w-4":"h-3 w-3","aria-hidden":"true"}),v.jsx("span",{children:m})]})}function xOe({trpc:e,deviceId:t,optimistic:a}){const{display:r,capPresent:c,busy:m,running:d,run:h,stop:f}=E8(e,t,a);return!c||r===void 0?null:v.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[v.jsx(R8,{running:d,busy:m,large:!1,onRun:h,onStop:f}),v.jsx(Tx,{atMs:r.lastRunAt,neverLabel:"never run"})]})}function MOe({trpc:e,deviceId:t,optimistic:a}){const{display:r,capPresent:c,busy:m,running:d,run:h,stop:f}=E8(e,t,a);return!c||r===void 0?null:v.jsxs("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-6",children:[v.jsxs("div",{className:"flex flex-col items-center gap-2",children:[v.jsx("div",{"data-testid":"script-state","data-running":d?"true":"false",className:ne("flex h-16 w-16 items-center justify-center rounded-full border-2",d?"border-primary text-primary animate-pulse":"border-border text-foreground-subtle"),children:v.jsx(vl,{className:"h-8 w-8","aria-hidden":"true"})}),v.jsx("span",{className:"text-sm font-medium",children:d?"Running":"Idle"}),v.jsx(Tx,{atMs:r.lastRunAt,neverLabel:"never run"}),v.jsx(I8,{error:r.lastError})]}),v.jsx("div",{className:"flex justify-center",children:v.jsx(R8,{running:d,busy:m,large:!0,onRun:h,onStop:f})})]})}function T8(e,t,a){const{cap:r,slice:c,available:m}=Nt({trpc:e,deviceId:t,cap:k=>k.automationControl,slice:k=>k.state.automationControl}),{display:d,applyOptimistic:h}=ra(c,{enabled:a??!0}),f=!m;return{display:d,capPresent:r!==void 0,busy:f,setEnabled:k=>{r===void 0||f||(h({enabled:k}),k?r.enable({}):r.disable({}))},trigger:()=>{r===void 0||f||r.trigger({})}}}function _8({enabled:e,busy:t,onToggle:a}){return v.jsx("button",{type:"button",role:"switch","aria-checked":e,"aria-label":"Automation enabled",disabled:t,"data-testid":"automation-enabled",onClick:r=>{r.stopPropagation(),a(!e)},className:ne("inline-flex shrink-0 items-center gap-1 rounded-md border px-1.5 py-0.5","text-[11px] font-medium whitespace-nowrap transition-colors",e?"border-success/40 bg-success/10 text-success":"border-border bg-surface-subtle text-foreground-subtle",t&&"cursor-not-allowed opacity-40"),children:e?"Enabled":"Disabled"})}function P8({busy:e,large:t,onTrigger:a}){return v.jsxs("button",{type:"button","aria-label":"Trigger",title:"Run this automation now",disabled:e,"data-testid":"automation-trigger",onClick:r=>{r.stopPropagation(),a()},className:ne("inline-flex items-center gap-1 rounded transition-colors",t?"h-10 px-4 text-sm":"h-5 px-1.5 text-xs","bg-primary text-primary-foreground hover:bg-primary/90",e&&"cursor-not-allowed opacity-40"),children:[v.jsx(is,{className:t?"h-4 w-4":"h-3 w-3","aria-hidden":"true"}),v.jsx("span",{children:"Trigger"})]})}function COe({trpc:e,deviceId:t,optimistic:a}){const{display:r,capPresent:c,busy:m,setEnabled:d,trigger:h}=T8(e,t,a);return!c||r===void 0?null:v.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[v.jsx(_8,{enabled:r.enabled,busy:m,onToggle:d}),v.jsx(P8,{busy:m,large:!1,onTrigger:h})]})}function AOe({trpc:e,deviceId:t,optimistic:a}){const{display:r,capPresent:c,busy:m,setEnabled:d,trigger:h}=T8(e,t,a);return!c||r===void 0?null:v.jsxs("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-6",children:[v.jsxs("div",{className:"flex flex-col items-center gap-2",children:[v.jsx("div",{"data-testid":"automation-state","data-enabled":r.enabled?"true":"false",className:ne("flex h-16 w-16 items-center justify-center rounded-full border-2",r.enabled?"border-success text-success":"border-border text-foreground-subtle"),children:v.jsx(is,{className:"h-8 w-8","aria-hidden":"true"})}),v.jsx("span",{className:"text-sm font-medium",children:r.enabled?"Enabled":"Disabled"}),v.jsx(Tx,{atMs:r.lastTriggeredAt,neverLabel:"never triggered"}),v.jsx(I8,{error:r.lastError})]}),v.jsxs("div",{className:"flex items-center justify-center gap-3",children:[v.jsx(_8,{enabled:r.enabled,busy:m,onToggle:d}),v.jsx(P8,{busy:m,large:!0,onTrigger:h})]})]})}function IOe({children:e}){return v.jsx("div",{className:"flex flex-col items-stretch gap-3 rounded-lg border border-border bg-surface p-4",children:e})}function N8(e,t){const{cap:a}=Nt({trpc:e,deviceId:t,cap:r=>r.switch,slice:r=>r.state.switch});return a!==void 0}function EOe({trpc:e,deviceId:t,features:a,optimistic:r}){return N8(e,t)?v.jsx(Ax,{trpc:e,deviceId:t,features:a,layout:"compact",optimistic:r}):null}function ROe(e,t){const{cap:a}=Nt({trpc:e,deviceId:t,cap:r=>r.lockControl,slice:r=>r.state.lockControl});return a!==void 0}function TOe({trpc:e,deviceId:t,features:a,optimistic:r}){return ROe(e,t)?v.jsx(J_e,{trpc:e,deviceId:t,features:a,layout:"compact",optimistic:r}):null}function _Oe({trpc:e,deviceId:t,features:a,optimistic:r}){return N8(e,t)?v.jsxs("div",{className:"inline-flex items-center gap-2",children:[v.jsx(Ax,{trpc:e,deviceId:t,features:a,layout:"compact",optimistic:r}),v.jsx(ePe,{trpc:e,deviceId:t,features:a,layout:"compact",optimistic:r})]}):null}function POe(e,t){const{cap:a}=Nt({trpc:e,deviceId:t,cap:r=>r.fanControl,slice:r=>r.state.fanControl});return a!==void 0}function NOe({trpc:e,deviceId:t,features:a,optimistic:r}){return POe(e,t)?v.jsxs("div",{className:"inline-flex items-center gap-2",children:[v.jsx(Ax,{trpc:e,deviceId:t,features:a,layout:"compact",optimistic:r}),v.jsx(tPe,{trpc:e,deviceId:t,features:a,layout:"compact",optimistic:r})]}):null}function _x(e,t){const{cap:a}=Nt({trpc:e,deviceId:t,cap:r=>r.climateControl,slice:r=>r.state.climateControl});return a!==void 0}function OOe({trpc:e,deviceId:t,features:a,optimistic:r}){return _x(e,t)?v.jsx(nPe,{trpc:e,deviceId:t,features:a,layout:"compact",optimistic:r}):null}function DOe({trpc:e,deviceId:t,features:a,optimistic:r}){return _x(e,t)?v.jsx(b8,{trpc:e,deviceId:t,features:a,layout:"compact",optimistic:r}):null}function jOe({trpc:e,deviceId:t,features:a,optimistic:r}){return _x(e,t)?v.jsx(b8,{trpc:e,deviceId:t,features:a,layout:"full",optimistic:r}):null}function zOe(e,t){const{cap:a}=Nt({trpc:e,deviceId:t,cap:r=>r.mediaPlayer,slice:r=>r.state.mediaPlayer});return a!==void 0}function qOe({trpc:e,deviceId:t,features:a,optimistic:r}){return zOe(e,t)?v.jsx(cPe,{trpc:e,deviceId:t,features:a,layout:"compact",optimistic:r}):null}function O8(e,t){const{cap:a}=Nt({trpc:e,deviceId:t,cap:r=>r.control,slice:r=>r.state.control});return a!==void 0}function LOe({trpc:e,deviceId:t,features:a,optimistic:r}){return O8(e,t)?v.jsx(KL,{trpc:e,deviceId:t,features:a,layout:"compact",optimistic:r}):null}function BOe({trpc:e,deviceId:t,features:a,optimistic:r}){return O8(e,t)?v.jsx(IOe,{children:v.jsx(KL,{trpc:e,deviceId:t,features:a,layout:"full",optimistic:r})}):null}var FOe={cover:{InlineControl:IPe,HeroCard:TPe},valve:{InlineControl:mNe,HeroCard:gNe},humidifier:{InlineControl:yNe,HeroCard:kNe},"water-heater":{InlineControl:xNe,HeroCard:CNe},switch:{InlineControl:EOe,HeroCard:hOe},light:{InlineControl:_Oe,HeroCard:dOe},fan:{InlineControl:NOe,HeroCard:pOe},sensor:{InlineControl:OPe,HeroCard:$Pe},thermostat:{InlineControl:OOe,HeroCard:XNe},climate:{InlineControl:DOe,HeroCard:jOe},button:{InlineControl:W_e,HeroCard:Z_e},update:{InlineControl:UPe,HeroCard:HPe},lock:{InlineControl:TOe,HeroCard:iOe},"media-player":{InlineControl:qOe,HeroCard:yOe},alarm:{InlineControl:kOe,HeroCard:SOe},control:{InlineControl:LOe,HeroCard:BOe},weather:{InlineControl:ENe,HeroCard:_Ne},vacuum:{InlineControl:eNe,HeroCard:tNe},"lawn-mower":{InlineControl:cNe,HeroCard:dNe},image:{InlineControl:PNe,HeroCard:NNe},"pet-feeder":{InlineControl:jNe,HeroCard:zNe},script:{InlineControl:xOe,HeroCard:MOe},automation:{InlineControl:COe,HeroCard:AOe},dummy:{InlineControl:_Pe,HeroCard:PPe}};Object.fromEntries(Object.values(O).map(e=>[e,FOe[JCe[e]]]));O.Cover+"",O.Valve+"",O.Thermostat+"",O.Climate+"",O.Control+"",O.Button+"",O.MediaPlayer+"",O.AlarmPanel+"",O.Lock+"",O.Vacuum+"",O.LawnMower+"",O.Humidifier+"",O.Switch+"",O.Siren+"",O.Light+"",O.Fan+"",O.WaterHeater+"",O.Sensor+"",O.Presence+"",O.EventEmitter+"",O.Notifier+"",O.Script+"",O.Automation+"",O.Camera+"",O.Hub+"",O.Update+"",O.Generic+"",O.Weather+"",O.Container+"",O.Image+"",O.PetFeeder+"";new Set(Object.values(O));P.createContext(null);O.Sensor,O.Presence;var $Oe={};P.createContext($Oe);Oi("camstack:device-quick-detail",null);o({id:i(),stableId:n(),addonId:n(),type:n(),name:n(),online:w(),disabled:w(),parentDeviceId:i().nullable(),role:n().nullable().optional(),features:y(n()).optional(),isCamera:w().optional()});function to(e){return e.deviceKey!==void 0?`${e.agentNodeId}::${e.deviceKey}`:e.agentNodeId}function D8(e){const t=[];for(const a of e){const r=t[t.length-1];if(r&&r.agentNodeId===a.agentNodeId){const c=[...r.columns,a];t[t.length-1]={...r,columns:c,grouped:c.length>1}}else t.push({agentNodeId:a.agentNodeId,engineLabel:a.engineLabel,columns:[a],grouped:!1})}return t}function UOe(e){const t=[],a=(r,c)=>{for(const m of r)t.push({node:m,depth:c}),a(m.children,c+1)};return a(e,0),t}function HOe(e,t,a,r=208,c=t){return e<=0?!1:t<=1?e<a+r*c:e<a+r*2}var eT={detector:{label:"detector",className:"text-emerald-500"},cropper:{label:"cropper",className:"text-blue-500"},classifier:{label:"classifier",className:"text-violet-500"},refiner:{label:"refiner",className:"text-amber-500"},"audio-classifier":{label:"audio classifier",className:"text-pink-500"}};function QOe({slot:e}){const t=eT[e]??eT.classifier;return v.jsx("span",{className:ne("text-[9px] font-semibold uppercase tracking-widest leading-none",t.className),children:t.label})}var tT="inline-flex items-center rounded bg-muted px-1.5 py-px text-[9px] font-medium text-foreground-subtle";function VOe({inputs:e,outputs:t}){return e.length===0&&t.length===0?null:v.jsxs("span",{className:"inline-flex items-center gap-1 flex-wrap",children:[e.map(a=>v.jsx("span",{className:ne(tT,"bg-blue-500/10 text-blue-500"),children:a},`in-${a}`)),e.length>0&&t.length>0&&v.jsx("span",{className:"text-foreground-subtle/60 text-[9px]",children:"→"}),t.map(a=>v.jsx("span",{className:ne(tT,"bg-emerald-500/10 text-emerald-500"),children:a},`out-${a}`))]})}function j8({column:e}){const t=e.deviceLabel??e.deviceKey;return v.jsxs(v.Fragment,{children:[(t!==void 0||e.disabled===!0)&&v.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[t!==void 0&&v.jsx("span",{className:"truncate text-[10px] font-medium text-foreground/90",children:t}),e.disabled===!0&&v.jsx("span",{className:"shrink-0 rounded bg-muted px-1 text-[8px] font-semibold uppercase text-foreground-subtle",children:"off"})]}),v.jsx("div",{className:"truncate text-[9px] text-foreground-subtle",children:e.engineLabel}),e.detail!==void 0&&v.jsx("div",{className:"truncate font-mono text-[9px] text-foreground-subtle",title:e.detail,children:e.detail})]})}function KOe({group:e}){const t=e.columns[0]?.nodeLabel??e.agentNodeId;return v.jsxs("div",{role:"columnheader",className:"sticky top-0 z-10 min-w-0 border-b border-l border-border bg-muted/60",style:{gridColumn:`span ${e.columns.length}`},children:[v.jsx("div",{className:"truncate px-3 pt-2 pb-1 text-xs font-semibold text-foreground",children:t}),v.jsx("div",{className:"mt-1 flex border-t border-border/50",children:e.columns.map((a,r)=>v.jsx("div",{className:ne("min-w-0 flex-1 px-3 py-1",r>0&&"border-l border-border/50",a.disabled===!0&&"opacity-70"),title:`${a.deviceLabel??a.deviceKey} · ${a.engineLabel}${a.detail?` · ${a.detail}`:""}`,children:v.jsx(j8,{column:a})},to(a)))})]})}function GOe({node:e}){return v.jsxs("div",{className:"flex flex-col gap-1 min-w-0 flex-1",children:[v.jsx(QOe,{slot:e.slot}),v.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[v.jsx("span",{className:"font-semibold truncate",children:e.addonName}),v.jsx(VOe,{inputs:e.inputClasses,outputs:e.outputClasses})]})]})}function WOe(e){return e.kind==="enabled"?v.jsxs("span",{className:"flex min-w-0 items-center gap-1",title:e.overridden?"override":void 0,children:[v.jsx("span",{className:ne("h-1.5 w-1.5 rounded-full shrink-0",e.overridden?"bg-amber-500":"bg-emerald-500")}),v.jsx("span",{className:"font-mono text-foreground truncate",children:e.modelId}),e.suppliedByRoot!==void 0&&v.jsx("span",{className:"ml-auto shrink-0 truncate rounded bg-primary/10 px-1 text-[8px] font-semibold uppercase text-primary",title:`Uses the root model ${e.suppliedByRoot} — this step's own model does not run here`,children:"root"}),e.clusterWide===!0&&v.jsx("span",{className:"ml-auto shrink-0 text-[8px] font-semibold uppercase text-primary",title:"One value for the whole cluster — this step writes into a shared vector index",children:"cluster"}),e.jumpTo!==void 0&&v.jsxs("span",{className:"ml-auto shrink-0 text-[8px] font-semibold text-sky-500",title:`runs on ${e.jumpTo}`,children:["→ ",e.jumpTo]}),e.overridden&&e.jumpTo===void 0&&v.jsx("span",{className:"ml-auto shrink-0 text-[8px] font-semibold uppercase text-amber-500",children:"ovr"})]}):e.kind==="disabled"?v.jsxs("span",{className:"flex min-w-0 items-center gap-1 text-foreground-subtle",title:e.overridden?"override":void 0,children:[v.jsx("span",{className:ne("h-1.5 w-1.5 rounded-full shrink-0",e.overridden?"bg-amber-500":"border border-foreground-subtle/60")}),v.jsx("span",{className:"truncate",children:"off"}),e.overridden&&v.jsx("span",{className:"ml-auto shrink-0 text-[8px] font-semibold uppercase text-amber-500",children:"ovr"})]}):e.kind==="skip"?e.jumpTo!==void 0?v.jsxs("span",{className:"flex min-w-0 items-center gap-1 text-sky-500",title:`no build for this device — auto-jumps to ${e.jumpTo}`,children:[v.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-sky-500 shrink-0"}),v.jsxs("span",{className:"truncate font-medium",children:["→ ",e.jumpTo]})]}):v.jsxs("span",{className:"flex min-w-0 items-center gap-1 text-amber-500",title:"Gated on for this camera, but no compatible model on this node — click to provision",children:[v.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-amber-500 shrink-0"}),v.jsx("span",{className:"truncate font-medium",children:"⚠ skip"})]}):v.jsxs("span",{className:"flex min-w-0 items-center gap-1 text-foreground-subtle/70",children:[v.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-muted shrink-0"}),v.jsx("span",{className:"truncate",children:"—"})]})}function ZOe(e,t,a){return ne("text-left text-xs hover:bg-muted/40",e.kind==="enabled"&&"bg-emerald-500/5",e.kind==="skip"&&"bg-amber-500/5",e.kind==="na"&&"bg-muted/30",t&&"ring-2 ring-primary ring-inset",a)}var z8=18,YOe=z8*16,XOe=11;function JOe(e,t,a,r){const c=(m,d)=>({r:Math.max(0,Math.min(a-1,m)),c:Math.max(0,Math.min(r-1,d))});switch(e){case"ArrowRight":return c(t.r,t.c+1);case"ArrowLeft":return c(t.r,t.c-1);case"ArrowDown":return c(t.r+1,t.c);case"ArrowUp":return c(t.r-1,t.c);case"Home":return c(t.r,0);case"End":return c(t.r,r-1);case"PageDown":return c(a-1,t.c);case"PageUp":return c(0,t.c);default:return null}}function eDe({node:e,depth:t,r:a,tabbable:r,selected:c,badge:m,onClick:d,sticky:h}){return v.jsx("div",{role:"rowheader",className:ne("min-w-0 border-b border-border bg-surface",h&&"sticky left-0 z-10"),children:v.jsxs("button",{type:"button","data-r":a,"data-c":0,"data-step":e.addonId,"data-col":"",tabIndex:r?0:-1,"aria-current":c?"true":void 0,onClick:d?f=>d(f.detail===0):void 0,className:ne("flex h-full w-full min-w-0 items-start gap-2 px-3 py-2 text-left text-xs outline-none","hover:bg-muted/40 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",c&&"bg-primary/10 shadow-[inset_3px_0_0_var(--color-primary)]"),style:{paddingLeft:`${12+t*14}px`},children:[v.jsx(GOe,{node:e}),m]})})}function tDe({nodes:e,selected:t,onSelect:a}){return v.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",role:"tablist","aria-label":"Node",children:[v.jsx(MIe,{className:"h-3.5 w-3.5 text-foreground-subtle"}),v.jsx("span",{className:"text-[10px] uppercase tracking-wider text-foreground-subtle",children:"Node"}),v.jsx("div",{className:"flex overflow-hidden rounded-md border border-border text-[11px] font-medium",children:e.map((r,c)=>{const m=r.agentNodeId===t;return v.jsx("button",{type:"button",role:"tab","aria-selected":m,onClick:()=>a(r.agentNodeId),title:`${r.columns[0]?.nodeLabel??r.agentNodeId} · ${r.engineLabel}`,className:ne("px-2.5 py-1 transition-colors",m?"bg-primary/15 text-primary":"bg-transparent text-foreground-subtle hover:bg-surface-hover hover:text-foreground",c>0&&"border-l border-border"),children:r.columns[0]?.nodeLabel??r.agentNodeId},r.agentNodeId)})})]})}var aDe=P.forwardRef(function({tree:t,agents:a,getCellState:r,onCellClick:c,onStepClick:m,stepBadge:d,selectedCell:h,single:f,reserveRightPx:k,label:x},E){const R=P.useMemo(()=>UOe(t),[t]),T=P.useMemo(()=>D8(a),[a]),N=P.useRef(null),j=f?XOe:z8,q=`${j}rem repeat(${a.length}, 13rem)`,B=a.length+1,[F,U]=P.useState(!0);P.useLayoutEffect(()=>{const he=N.current;if(!he||k<=0){U(!0);return}const Ae=()=>{const we=he.getBoundingClientRect().left;U(window.innerWidth-k-we>=j*16+208+24)};return Ae(),window.addEventListener("resize",Ae),()=>window.removeEventListener("resize",Ae)},[k,j]);const H=P.useMemo(()=>{if(h===null)return null;const he=R.findIndex(we=>we.node.addonId===h.addonId);if(he<0)return null;const Ae=a.findIndex(we=>to(we)===to(h));return{r:he,c:Ae<0?0:Ae+1}},[h,R,a]),[Q,te]=P.useState({r:0,c:0});P.useEffect(()=>{H!==null&&te(H)},[H]);const K=Q.r<R.length&&Q.c<B?Q:{r:0,c:0},W=(he,Ae)=>{N.current?.querySelector(`[data-r="${he}"][data-c="${Ae}"]`)?.focus()};P.useImperativeHandle(E,()=>({focusCell:(he,Ae)=>{const we=R.findIndex(Me=>Me.node.addonId===he);if(we<0)return;const Ee=Ae===null?-1:a.findIndex(Me=>to(Me)===Ae),Ie=Ee<0?0:Ee+1;te({r:we,c:Ie}),W(we,Ie)}}),[R,a]),P.useLayoutEffect(()=>{if(H===null)return;const he=N.current,Ae=he?.querySelector(`[data-r="${H.r}"][data-c="${H.c}"]`);if(!he||!Ae||(typeof Ae.scrollIntoView=="function"&&Ae.scrollIntoView({block:"nearest",inline:"nearest"}),k<=0))return;const we=window.innerWidth-k-12,Ee=Ae.getBoundingClientRect().right;Ee>we&&(he.scrollLeft+=Ee-we)},[H,k,F]);const oe=he=>{if(!(he.target instanceof HTMLElement)||he.target.dataset.r===void 0)return;const Ae={r:Number(he.target.dataset.r),c:Number(he.target.dataset.c)},we=JOe(he.key,Ae,R.length,B);we!==null&&(he.preventDefault(),te(we),W(we.r,we.c))};return v.jsx("div",{ref:N,className:"overflow-auto rounded border border-border",children:v.jsxs("div",{className:"flex w-max",children:[v.jsxs("div",{role:"grid","aria-label":x,"aria-rowcount":R.length+1,className:"grid w-max",style:{gridTemplateColumns:q},onKeyDown:oe,children:[v.jsxs("div",{role:"row",className:"contents",children:[v.jsx("div",{role:"columnheader",className:ne("top-0 z-20 border-b border-border bg-muted/60 px-3 py-2 text-[10px] uppercase tracking-widest text-foreground-subtle",F?"sticky left-0":"sticky"),children:"Step"}),T.map(he=>he.grouped?v.jsx(KOe,{group:he},he.agentNodeId):he.columns.map(Ae=>v.jsxs("div",{role:"columnheader",className:ne("sticky top-0 z-10 min-w-0 border-b border-l border-border bg-muted/60 px-3 py-2",Ae.disabled===!0&&"opacity-70"),children:[v.jsx("div",{className:"truncate text-xs font-semibold text-foreground",children:Ae.nodeLabel??Ae.agentNodeId}),v.jsx(j8,{column:Ae})]},to(Ae))))]}),R.map(({node:he,depth:Ae},we)=>v.jsxs("div",{role:"row",className:"contents",children:[v.jsx(eDe,{node:he,depth:Ae,r:we,tabbable:K.r===we&&K.c===0,selected:h?.addonId===he.addonId,badge:d?.(he.addonId),onClick:m?Ee=>m(he.addonId,Ee):void 0,sticky:F}),a.map((Ee,Ie)=>{const Me=r(he.addonId,Ee),Y=h!==null&&h.addonId===he.addonId&&to(h)===to(Ee),de=Me.kind==="enabled"||Me.kind==="skip";return v.jsx("div",{role:"gridcell",className:"min-w-0 border-b border-l border-border",children:v.jsx("button",{type:"button","data-r":we,"data-c":Ie+1,"data-step":he.addonId,"data-col":to(Ee),tabIndex:K.r===we&&K.c===Ie+1?0:-1,"aria-disabled":!de,"aria-selected":Y,onClick:Re=>{de&&c(he.addonId,Ee,Re.detail===0)},className:ZOe(Me,Y,ne("h-full w-full min-w-0 overflow-hidden px-3 py-2 outline-none","focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",!de&&"cursor-default hover:bg-transparent",Ee.disabled===!0&&"opacity-70")),children:WOe(Me)})},to(Ee))})]},he.addonId))]}),k>0&&v.jsx("div",{"aria-hidden":!0,style:{width:k},className:"shrink-0"})]})})});P.forwardRef(function({tree:t,agents:a,getCellState:r,onCellClick:c,selectedCell:m,fallbackNodeId:d,onFallbackNodeChange:h,onStepClick:f,stepBadge:k,reserveRightPx:x=0,label:E="Detection steps"},R){const T=P.useRef(null),[N,j]=P.useState(0);P.useLayoutEffect(()=>{const Q=T.current;if(!Q)return;const te=()=>j(Q.getBoundingClientRect().width);te();const K=typeof ResizeObserver<"u"?new ResizeObserver(te):null;return K?.observe(Q),()=>K?.disconnect()},[]);const q=P.useMemo(()=>D8(a),[a]),B=HOe(N,q.length,YOe,208,a.length),F=P.useMemo(()=>q.length===0?null:q.find(Q=>Q.agentNodeId===d)??q[0]??null,[q,d]),U=m?.agentNodeId;P.useEffect(()=>{B&&U!==void 0&&U!==d&&h(U)},[B,U,d,h]);const H=B&&F?F.columns:a;return v.jsxs("div",{ref:T,className:"w-full space-y-2",children:[B&&F&&q.length>1&&v.jsx(tDe,{nodes:q,selected:F.agentNodeId,onSelect:h}),v.jsx(aDe,{ref:R,tree:t,agents:H,getCellState:r,onCellClick:c,onStepClick:f,stepBadge:k,selectedCell:m,single:B&&F!==null,reserveRightPx:x,label:E})]})});ne(cTe,"min-w-0 max-w-full gap-1.5 py-1 pl-1 pr-2.5 text-xs font-normal","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40");ne(dTe,"font-medium");function nDe({dirtyCount:e,saving:t,status:a,error:r,onSave:c,onDiscard:m,scope:d}){const h=e>0,f=t?"Saving…":h?`${e} unsaved change${e===1?"":"s"}`:a==="saved"?"Saved":a==="error"?r??"Save failed":"No unsaved changes";return v.jsxs("footer",{className:"shrink-0 space-y-2 border-t border-border bg-surface px-4 py-2 pb-[max(0.5rem,env(safe-area-inset-bottom))] md:pb-2",children:[d!==void 0&&v.jsx("div",{"data-save-scope":!0,children:d}),v.jsxs("div",{className:"flex items-center gap-2",children:[v.jsx("span",{role:"status",className:ne("min-w-0 flex-1 truncate text-[11px]",a==="error"&&!h?"text-danger":h?"text-amber-500":"text-foreground-subtle"),children:f}),v.jsx(pm,{variant:"outline",size:"md",disabled:!h||t,onClick:m,children:"Discard"}),v.jsx(pm,{variant:"primary",size:"md",disabled:!h||t,onClick:c,children:"Save"})]})]})}P.forwardRef(function({title:t,subtitle:a,headerActions:r,headerExtra:c,leading:m,saveBar:d,onEscape:h,children:f,className:k},x){const E=P.useId(),R=T=>{T.key!=="Escape"||h===void 0||(T.stopPropagation(),h())};return v.jsxs("section",{"aria-labelledby":E,onKeyDown:R,className:ne("flex min-h-0 flex-1 flex-col overflow-hidden bg-surface",k),children:[v.jsxs("header",{className:"shrink-0 space-y-2 border-b border-border px-4 py-2.5",children:[v.jsxs("div",{className:"flex flex-wrap items-start gap-x-3 gap-y-2",children:[m,v.jsxs("div",{className:"min-w-[9rem] flex-1",children:[v.jsx("h2",{id:E,ref:x,tabIndex:-1,title:t,className:"line-clamp-2 break-words text-sm font-semibold leading-snug text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary rounded",children:t}),a!==void 0&&v.jsx("div",{className:"mt-0.5 text-[11px] text-foreground-subtle",children:a})]}),r]}),c]}),v.jsx("div",{"data-inspector-body":!0,className:"min-h-0 flex-1 overflow-y-auto overscroll-contain px-4 py-3",children:f}),d!==void 0&&v.jsx(nDe,{...d})]})});Oi("camstack:player-overlays-state",null);var iDe=Oi("camstack:player-overlays-actions",null);function q8e(e){const t=P.useContext(iDe);P.useEffect(()=>{if(!(!t||!e))return t.setLayer(e),()=>t.removeLayer(e.id)},[t,e])}Oi("camstack:zone-editing",null);var aT=500,W1=800;function ku(e,t,a){try{const r=e.live;if(!r)return null;const c=r.onEvent;return!c||typeof c.subscribe!="function"?null:c.subscribe({category:t},{onData:a})}catch{return null}}function Fh(e,t){return e?.id===t}function rDe(e,t){const[a,r]=P.useState(null),[c,m]=P.useState(null),[d,h]=P.useState(null),[f,k]=P.useState("watching"),x=P.useRef(void 0),E=P.useRef(void 0),R=P.useRef(void 0),T=P.useRef(0);return P.useEffect(()=>{if(t===null)return;const N=ku(e,"detection.motion-analysis",j=>{const q=j;if(!Fh(q?.source,t))return;const B=q.data;!B?.regions||B.regions.length===0||(r({zones:B.regions.map(F=>({...F.bbox,intensity:F.intensity})),frameWidth:B.frameWidth,frameHeight:B.frameHeight}),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>r(null),aT))});return()=>{N?.unsubscribe(),x.current&&clearTimeout(x.current)}},[e,t]),P.useEffect(()=>{if(t===null)return;const N=ku(e,"detection.motion-zones-raw",j=>{const q=j;if(!Fh(q?.source,t))return;const B=q.data;B?.zones&&(m({boxes:B.zones.map(F=>({bbox:F.bbox,changeScore:F.changeScore})),frameWidth:B.frameSize?.width??0,frameHeight:B.frameSize?.height??0,motionScore:B.zones.length>0?B.zones.reduce((F,U)=>F+U.changeScore,0)/B.zones.length:0}),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>m(null),aT))});return()=>{N?.unsubscribe(),E.current&&clearTimeout(E.current)}},[e,t]),P.useEffect(()=>{if(T.current=0,t===null)return;const N=ku(e,"pipeline-analytics.frame-tracked",j=>{const q=j?.data;!q||q.deviceId!==t||q.detections?.length&&typeof q.detections[0]?.kind=="string"&&(T.current=Date.now(),h({detections:q.detections,frameWidth:q.frameWidth,frameHeight:q.frameHeight}),R.current&&clearTimeout(R.current),R.current=setTimeout(()=>h(null),W1))});return()=>{N?.unsubscribe(),R.current&&clearTimeout(R.current)}},[e,t]),P.useEffect(()=>{if(t===null)return;const N=ku(e,"detection.result",j=>{const q=j;if(!Fh(q?.source,t)||Date.now()-T.current<W1)return;const B=q.data?.frame;B?.detections?.length&&(h({detections:B.detections,frameWidth:B.width,frameHeight:B.height}),R.current&&clearTimeout(R.current),R.current=setTimeout(()=>h(null),W1))});return()=>{N?.unsubscribe(),R.current&&clearTimeout(R.current)}},[e,t]),P.useEffect(()=>{if(t===null)return;const N=ku(e,"detection.phase-transition",j=>{const q=j;Fh(q?.source,t)&&q.data?.to&&k(q.data.to)});return()=>{N?.unsubscribe()}},[e,t]),{motion:a,motionRaw:c,detection:d,phase:f}}P.lazy(()=>Hc(()=>import("./MaskShapeCanvas-DI4BY7W2-OFXMXri-.js"),[],import.meta.url).then(e=>({default:e.MaskShapeCanvas})));P.lazy(()=>Hc(()=>import("./MotionZonesSettings-CiYjd-yl-BirmOvge.js"),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.MotionZonesSettings})));P.lazy(()=>Hc(()=>import("./SceneMonitorEditor-J4Ix_0tu-03IFAET6.js"),__vite__mapDeps([3,1]),import.meta.url).then(e=>({default:e.SceneMonitorEditor})));P.lazy(()=>Hc(()=>import("./PrivacyMaskSettings-BmRdUrPp-D7nMj8O6.js"),__vite__mapDeps([2,1]),import.meta.url).then(e=>({default:e.PrivacyMaskSettings})));const q8=7;function oDe(e,t){return t!==void 0?e.toLocaleTimeString(t,{hour:"2-digit",minute:"2-digit"}):`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`}function nT(e){const t=new Date(e);return t.setHours(0,0,0,0),t.getTime()}function sDe(e,t){return Math.round((nT(t)-nT(e))/864e5)}function lDe(e){const t=(e??"en").toLowerCase();return t.startsWith("it")?"Ieri":t.startsWith("de")?"Gestern":t.startsWith("fr")?"Hier":t.startsWith("es")?"Ayer":"Yesterday"}function cDe(e,t,a){const r=new Date(e),c=oDe(r,a),m=sDe(e,t);if(m===0)return c;if(m===1)return`${lDe(a)} ${c}`;if(m>1&&m<=q8)return`${r.toLocaleDateString(a,{weekday:"short"})} ${c}`;const d=String(r.getDate()).padStart(2,"0"),h=String(r.getMonth()+1).padStart(2,"0");return`${d}/${h} ${c}`}const iT=6e4,rT=36e5,Z1=864e5,oT={en:{now:"now",m:"m",h:"h",d:"d"},it:{now:"ora",m:"m",h:"h",d:"g"}};function dDe(e,t,a){const r=t-e;if(r>=0&&r<q8*Z1){const c=oT[(a??"en").toLowerCase().slice(0,2)]??oT.en;return r<iT?c.now:r<rT?`${Math.floor(r/iT)}${c.m}`:r<Z1?`${Math.floor(r/rT)}${c.h}`:`${Math.floor(r/Z1)}${c.d}`}return new Date(e).toLocaleDateString(a,{day:"numeric",month:"short"})}const Px={unassignedFace:"unassigned face",reviewed:"reviewed",debug:"debug",train:"train",trained:"training complete",favourite:"favourite",active:"active",loadingMore:"Loading more events"},uDe={unassignedFace:"volto non assegnato",reviewed:"verificata",debug:"debug",train:"addestramento",trained:"addestramento completato",favourite:"preferita",active:"attiva",loadingMore:"Caricamento altri eventi"};function mDe(e){return e==="it"?uDe:Px}const pDe=Object.keys(Px),L8=$(n(),n());function B8(e,t){const a=mDe(t);if(e===null||typeof e!="object")return a;const r=e,c={...a};for(const m of pDe){const d=r[m];typeof d=="string"&&d.trim()!==""&&(c[m]=d)}return{unassignedFace:c.unassignedFace??a.unassignedFace,reviewed:c.reviewed??a.reviewed,debug:c.debug??a.debug,train:c.train??a.train,trained:c.trained??a.trained,favourite:c.favourite??a.favourite,active:c.active??a.active,loadingMore:c.loadingMore??a.loadingMore}}const hDe="/addon/pipeline-analytics/event-media",fDe="o",sT=64,gDe=320;function vDe(e){return e.replace(/\/+$/,"")}function yDe(e){const t=Math.round(e);return Number.isFinite(t)?Math.max(sT,Math.min(gDe,t)):sT}function Nx(e,t,a){const r=vDe(e),c=encodeURIComponent(t);return`${r}${hDe}/${fDe}/track/${c}?kind=thumbnailSmall&variant=thumb&size=${yDe(a)}`}const bDe="audio";function lT(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kDe(e){return SDe(F8(e))}function F8(e){const t=[];if(!Array.isArray(e))return t;for(const a of e){if(!lT(a))continue;const r=a.kinds;if(Array.isArray(r))for(const c of r)lT(c)&&t.push(c)}return t}function SDe(e){const t=new Map;for(const a of e){const r=a.kind;if(typeof r!="string"||r.length===0)continue;const c=a.parentKind;t.set(r,typeof c=="string"&&c.length>0?c:r)}return t}function $8(e,t){return t.get(e)??e}const cT="audio-",dT="audio";function Km(e){const t=e.toLowerCase();return t.startsWith(cT)?t:`${cT}${t}`}function wDe(e){return xDe(F8(e))}function xDe(e){const t=new Map;for(const a of e){const r=a.kind,c=a.iconId;typeof r!="string"||r.length===0||typeof c!="string"||c.length===0||t.set(r,c)}return t}function U8(e,t,a=!1){if(a){const c=t.get(e);if(c!==void 0)return c;if(e.toLowerCase()===dT)return dT;const m=Km(e);return t.get(m)??m}const r=e.toLowerCase();return t.get(e)??t.get(r)??r}function H8(e){const t=new Map;for(const[a,r]of Object.entries(e)){if(a.length===0||r.length===0)continue;t.set(a,r);const c=a.toLowerCase();t.has(c)||t.set(c,r)}return t}const Kg=new Map;function kf(e,t){return t.get(e)??t.get(e.toLowerCase())??e}function Q8(e,t){const a=Km(e);return t.get(a)??t.get(e)??e}const MDe={primary:"#f59e42",primaryForeground:"#0c0a09",background:"#0c0a09",backgroundElevated:"#1c1917",surface:"#1c1917",surfaceHover:"#292524",border:"#292524",borderSubtle:"#1c1917",foreground:"#fafaf9",foregroundMuted:"#a8a29e",foregroundSubtle:"#78716c",foregroundDisabled:"#57534e",success:"#4ade80",warning:"#fbbf24",danger:"#f87171",info:"#60a5fa",successFill:"#4ade80",successOn:"#0c0a09",warningFill:"#fbbf24",warningOn:"#0c0a09",dangerFill:"#f87171",dangerOn:"#0c0a09",infoFill:"#60a5fa",infoOn:"#0c0a09",primaryFill:"#f59e42",primaryOn:"#0c0a09",neutralFill:"#44403c",neutralOn:"#fafaf9",live:"#22d3ee",favourite:"#ff4d6d",onPicture:"#ffffff",onMedia:"#fafaf9",mediaBlack:"#000000",presence:"#34d399",presenceOff:"#71717a",stationary:"#8b98a5",eventsBackground:"#09090b",eventsCard:"#18181b",eventsRaised:"#27272a",eventsText:"#fafafa",eventsMuted:"#a1a1aa",eventsChip:"#3f3f46"},CDe={primary:"#e67e22",primaryForeground:"#ffffff",background:"#fafaf9",backgroundElevated:"#ffffff",surface:"#f5f5f4",surfaceHover:"#e7e5e4",border:"#d6d3d1",borderSubtle:"#e7e5e4",foreground:"#1c1917",foregroundMuted:"#57534e",foregroundSubtle:"#78716c",foregroundDisabled:"#a8a29e",success:"#16a34a",warning:"#d97706",danger:"#dc2626",info:"#2563eb",successFill:"#15803d",successOn:"#ffffff",warningFill:"#b45309",warningOn:"#ffffff",dangerFill:"#dc2626",dangerOn:"#ffffff",infoFill:"#2563eb",infoOn:"#ffffff",primaryFill:"#c2410c",primaryOn:"#ffffff",neutralFill:"#57534e",neutralOn:"#ffffff",live:"#0891b2",favourite:"#ff4d6d",onPicture:"#ffffff",onMedia:"#fafaf9",mediaBlack:"#000000",presence:"#34d399",presenceOff:"#71717a",stationary:"#8b98a5",eventsBackground:"#ffffff",eventsCard:"#f4f4f5",eventsRaised:"#e4e4e7",eventsText:"#18181b",eventsMuted:"#71717a",eventsChip:"#d4d4d8"};function V8(e,t){const a=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(e);if(!a)return e;const r=a[1].length===3?a[1].replace(/./g,f=>f+f):a[1],c=Math.min(1,Math.max(0,t)),m=parseInt(r.slice(0,2),16),d=parseInt(r.slice(2,4),16),h=parseInt(r.slice(4,6),16);return`rgba(${m}, ${d}, ${h}, ${Number(c.toFixed(3))})`}const ADe=.72;function IDe(e){return V8(e.background,ADe)}const Yt={dark:MDe,light:CDe},K8=HP(),EDe={ready:K8,origin:"pending",reason:null,serverUrl:null};let iw=EDe;const rw=new Set;function ow(e,t,a){return{ready:K8,origin:e,reason:t,serverUrl:a}}function RDe(e,t){return e.serverUrl===t?e:{...e,serverUrl:t}}function TDe(e){const t=JK.safeParse(e);return t.success?t.data.status==="unknown"?ow("unknown",t.data.reason,null):{ready:t.data,origin:"hub",reason:null,serverUrl:null}:ow("unknown","unreadable",null)}function _De(e){return e instanceof Error&&e.message.length>0&&e.message.length<=120?e.message:"unreachable"}function ag(e,t){return QP(e.ready.swatches,e.ready.fallbacks,t)}function PDe(e,t){return e.origin!==t.origin||e.reason!==t.reason||e.serverUrl!==t.serverUrl?!1:e.ready===t.ready?!0:e.origin!=="hub"&&t.origin!=="hub"}function ng(){return iw}function NDe(e){return rw.add(e),()=>{rw.delete(e)}}function Y1(e){if(!PDe(iw,e)){iw=e;for(const t of rw)t()}}function pd(){return P.useSyncExternalStore(NDe,ng,ng)}const uT={background:Yt.dark.eventsBackground,card:Yt.dark.eventsCard,cardHover:Yt.dark.eventsRaised,border:Yt.dark.eventsRaised,text:Yt.dark.eventsText,textMuted:Yt.dark.eventsMuted,skeleton:Yt.dark.eventsRaised,chip:Yt.dark.eventsChip,colorScheme:"dark"},mT={background:Yt.light.eventsBackground,card:Yt.light.eventsCard,cardHover:Yt.light.eventsRaised,border:Yt.light.eventsRaised,text:Yt.light.eventsText,textMuted:Yt.light.eventsMuted,skeleton:Yt.light.eventsRaised,chip:Yt.light.eventsChip,colorScheme:"light"};function Ox(e,t){return e==="light"?mT:e==="dark"||t?uT:mT}function sw(e,t=!1,a=ng()){return t?ag(a,"audio"):ag(a,e)}const ODe=/[_\-/.]+/g;function G8(e){return e.toLowerCase().replace(ODe," ").replace(/\s+/g," ").trim()}function DDe(e){if(e===void 0)return[];const t=e.trim().toLowerCase();if(t.length===0)return[];const a=G8(e);return a===t||a.length===0?[t]:[t,a]}const Gg=new Map,jDe=new Set(["plate-detection","plate-ocr","operator:plate-gallery"]),pT=new Set(["face-recognizer","face-embedding","operator:face-gallery"]),zDe=[],qDe=[];function X1(e,t){if(!Dx(e))return!1;const a=e.stepId;return typeof a=="string"&&t.has(a)}function ig(e){return e.source==="audio"}function Dx(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function es(e){return typeof e=="string"&&e.length>0?e:void 0}function J1(e){if(!Array.isArray(e))return[];const t=[];for(const a of e)typeof a=="string"&&a.length>0&&!t.includes(a)&&t.push(a);return t}function LDe(e){if(!Array.isArray(e))return[];const t=[];for(const a of e){const r=Dx(a)?es(a.label):void 0;r!==void 0&&!t.includes(r)&&t.push(r)}return t}function W8(e,t){if(!Dx(e))return null;const a=es(e.trackId),r=es(e.className);if(a===void 0||r===void 0||typeof e.deviceId!="number"||typeof e.firstSeen!="number"||typeof e.lastSeen!="number")return null;const c=es(e.label),m=es(e.subLabel),d=es(e.producingDeviceName),h=es(e.source),f=J1(e.classes);return{trackId:a,deviceId:e.deviceId,cameraName:t.get(e.deviceId)??`Camera ${e.deviceId}`,className:r,...c!==void 0?{label:c}:{},...m!==void 0?{subLabel:m}:{},...typeof e.importance=="number"?{importance:e.importance}:{},firstSeen:e.firstSeen,lastSeen:e.lastSeen,state:typeof e.state=="string"?e.state:"idle",active:e.active===!0,zonesVisited:J1(e.zonesVisited),zoneNames:J1(e.zoneNames),classes:f.includes(r)?f:[r,...f],audioLabels:LDe(e.audioLabels),bestEventId:es(e.bestEventId)??a,...d!==void 0?{producingDeviceName:d}:{},...h!==void 0?{source:h}:{},...e.hasEmbeddedFace===!0||X1(e.subLabelMeta,pT)?{hasAssignableFace:!0}:{},...e.hasEmbeddedFace===!0&&!X1(e.subLabelMeta,pT)?{hasUnassignedFace:!0}:{},...X1(e.subLabelMeta,jDe)?{hasPlate:!0}:{},...e.debug===!0?{debug:!0}:{},...e.markForTrain===!0?{markForTrain:!0}:{},...e.favourited===!0?{favourited:!0}:{},...e.retrainStatus==="none"||e.retrainStatus==="staging"||e.retrainStatus==="trained"?{retrainStatus:e.retrainStatus}:{}}}function hT(e,t){if(!Array.isArray(e))return[];const a=[];for(const r of e){const c=W8(r,t);c!==null&&a.push(c)}return a}function BDe(e,t){const a=new Set;for(const r of[e.className,...e.classes])r.length!==0&&(a.add(r),a.add($8(r,t)));if(e.audioLabels.length>0){a.add(bDe);for(const r of e.audioLabels)a.add(Km(r))}return a}function FDe(e,t,a=Gg){if(t.size===0)return!0;const r=BDe(e,a);for(const c of t)if(r.has(c))return!0;return!1}function $De(e,t=Gg){const a=new Set,r=c=>{for(const m of DDe(c))a.add(m)};for(const c of[e.className,...e.classes])r(c),c.length>0&&r($8(c,t));r(e.label),r(e.subLabel),r(e.cameraName),r(e.producingDeviceName);for(const c of e.audioLabels)r(c),r(Km(c));for(const c of e.zoneNames)r(c);for(const c of[e.label,e.subLabel]){if(c===void 0)continue;const m=t.get(c.trim().toLowerCase());m!==void 0&&r(m)}return a}function UDe(e,t,a=Gg){const r=t.trim().toLowerCase();if(r.length===0)return!0;const c=G8(t);for(const m of $De(e,a))if(m.includes(r)||c.length>0&&m.includes(c))return!0;return!1}function HDe(e,t){return!!(t.size===0||t.has("face")&&e.hasAssignableFace===!0||t.has("plate")&&e.hasPlate===!0)}function QDe(e,t={}){const a=t.debug===!0,r=t.train===!0,c=t.favourited===!0;if(!a&&!r&&!c)return!0;const m=t.reviewedTrackIds?.includes(e.trackId)===!0;return!!(a&&e.debug===!0&&!m||r&&e.markForTrain===!0||c&&e.favourited===!0)}function VDe(e,t){return t.size===0?!0:!t.has(e.source??"pipeline")}function fT(e,t,a,r=Gg,c=zDe,m={},d=qDe){const h=new Set(t),f=new Set(c),k=new Set(d);return e.filter(x=>VDe(x,k)&&FDe(x,h,r)&&HDe(x,f)&&UDe(x,a,r)&&QDe(x,m))}function Z8(e,t=Kg){return e.producingDeviceName!==void 0?{text:kf(e.className,t),tier:"device",fullText:e.producingDeviceName}:e.subLabel!==void 0?{text:e.subLabel,tier:"identity"}:e.label!==void 0&&e.label!==e.className?{text:kf(e.label,t),tier:"kind"}:{text:kf(e.className,t),tier:"class"}}function KDe(e,t,a,r=Kg){if(t)return"";const c=[a];for(const m of e.audioLabels){if(m===e.className||m===e.label)continue;const d=Q8(m,r);c.includes(d)||c.push(d)}return c.join(" · ")}function gT(e,t){let a=!1;const r=e.map(c=>{const m=t.get(c.deviceId);return m===void 0||m===c.cameraName?c:(a=!0,{...c,cameraName:m})});return a?r:e}function vT(e,t){if(Object.keys(t).length===0)return e;let r=!1;const c=e.map(m=>{const d=t[m.trackId];if(d===void 0)return m;const h=WDe(m,d);return h!==m&&(r=!0),h});return r?c:e}function GDe(e){const{debug:t,markForTrain:a,favourited:r,...c}=e;return c}function WDe(e,t){const a=t.debug===!0?!0:t.debug===!1?void 0:e.debug,r=t.markForTrain===!0?!0:t.markForTrain===!1?void 0:e.markForTrain,c=t.favourited===!0?!0:t.favourited===!1?void 0:e.favourited;return a===e.debug&&r===e.markForTrain&&c===e.favourited?e:{...GDe(e),...a===!0?{debug:!0}:{},...r===!0?{markForTrain:!0}:{},...c===!0?{favourited:!0}:{}}}function ZDe(e){const t=e.filter(a=>a.isCamera===!0).map(a=>a.id);return t.length>0?t:e.map(a=>a.id)}const lw=11,yT=9,ek=3,YDe=8,XDe=12,Y8=24,JDe=.58,e5e=.85;function t5e(e,t){return[...e].length*t*JDe}function a5e(e){return Math.max(Y8,e-YDe-XDe)}function bT(e,t,a){const r=a5e(t),c=a.maxLines===1?r:r*a.maxLines*e5e;return t5e(e,a.fontSizePx)<=c}function n5e(e,t){for(let a=1;a<=ek;a+=1){const r={fontSizePx:lw,maxLines:a};if(bT(e,t,r))return r}for(let a=lw-1;a>=yT;a-=1){const r={fontSizePx:a,maxLines:ek};if(bT(e,t,r))return r}return{fontSizePx:yT,maxLines:ek}}const i5e=12,tk=9,r5e=.56;function o5e(e,t){const a=Math.max(Y8,t-4),r=Math.min(i5e,Math.max(tk,Math.round(t/8)));for(let c=r;c>=tk;c-=1)if([...e].length*c*r5e<=a)return{fontSizePx:c,maxLines:1};return{fontSizePx:tk,maxLines:2}}const s5e="/viewer/camstack/embed/index.html",l5e=["off","icon","label"],c5e=I(l5e),jx=o({tileLabelMode:c5e.optional(),tileDetailCamera:w().optional(),tileDetailZone:w().optional()});function d5e(e,t){return{tileLabelMode:t.tileLabelMode??(e.label?"label":"off"),tileDetailCamera:t.tileDetailCamera??e.camera,tileDetailZone:t.tileDetailZone??e.badges}}const u5e=I(["reel","gallery"]),m5e=I(["small","medium","large"]);I(["time","importance"]);const p5e=I(["text","semantic"]),h5e=["face","plate"],zx=I(h5e),f5e=["pipeline","sensor","audio"],X8=I(f5e),g5e=I(["auto","dark","light"]),v5e=qe([_("auto"),i().int().min(1).max(12)]),y5e=o({label:w(),sublabel:w(),camera:w(),time:w(),badges:w(),importance:w()});o({view:u5e,rows:i().int().min(1).max(6).optional(),columns:v5e.optional(),thumb:m5e,deviceIds:y(i().int().nonnegative()),classes:y(n()).optional(),attrs:y(zx).optional(),search:n().optional(),searchMode:p5e.optional(),semanticLimit:i().int().min(1).max(200).optional(),semanticMinScore:i().min(0).max(1).optional(),sinceMs:i().int().nonnegative().optional(),untilMs:i().int().nonnegative().optional(),deviceNames:$(n(),n()).optional(),fields:y5e,...jx.shape,pageSize:i().int().min(1).max(500).optional(),maxRows:i().int().min(1).max(5e3).optional(),refreshMs:i().int().min(0).max(6e5).optional(),maxAgeMs:i().int().min(6e4).optional(),theme:g5e});const J8=4,b5e=768,k5e=212;function kT(e){return{edge:e,cardHeight:e}}function S5e(e){const{viewportWidth:t,viewportHeight:a,presetEdge:r,gap:c,padX:m}=e,d=Math.max(1,Math.floor(e.rows));if(t<b5e||a<=0)return kT(r);const h=t-m-c,f=a-J8*2,k=Math.floor((f-(d-1)*c)/d),x=Math.max(r,Math.min(k,k5e));if(h<=x)return kT(r);const E=Math.max(1,Math.ceil((h+c)/(x+c))),R=Math.floor((h-(E-1)*c)/E*100)/100;return{edge:R,cardHeight:R}}function qx(e){return e.startsWith("/")&&!e.startsWith("//")}function w5e(e){return e!==void 0&&e.length>0?{Authorization:`Bearer ${e}`}:{}}function x5e(e,t,a){if(!t.endsWith(a))return e;const r=t.slice(0,t.length-a.length);return r.length>0?r:e}function e7(e,t){e.token===void 0&&(qx(e.serverUrl)||t.addIssue({code:"custom",path:["token"],message:"token is required unless serverUrl is a same-origin path served through an authenticating relay"}))}const M5e=60,C5e=5e3,A5e=600,I5e=720*60*60*1e3,t7=I(["reel","gallery"]),a7=I(["small","medium","large"]),n7=I(["auto","dark","light"]),Lx=["en","it"];function i7(e){const t=(e??"").toLowerCase().split(/[-_]/)[0];return Lx.find(a=>a===t)}function Bx(e,t){return e??i7(t)??"en"}const E5e=o({label:w(),sublabel:w(),camera:w(),time:w(),badges:w(),importance:w().default(!1)}),R5e=o({label:w().optional(),sublabel:w().optional(),camera:w().optional(),time:w().optional(),badges:w().optional(),importance:w().optional()}),r7={label:!0,sublabel:!1,camera:!0,time:!0,badges:!0,importance:!1},o7=I(["text","semantic"]),s7=qe([_("auto"),i().int().min(1).max(12)]);function T5e(e){return e.view==="reel"?Math.min(e.maxRows,A5e):e.maxRows}const _5e=0,P5e=o({serverUrl:n().min(1),token:n().min(1).optional(),view:t7.default("reel"),rows:i().int().min(1).max(6).default(1),columns:s7.default("auto"),thumbSize:a7.default("medium"),fields:E5e.default(r7),...jx.shape,deviceIds:y(i().int().nonnegative()).default([]),classes:y(n()).default([]),attrs:y(zx).catch([]).default([]),deviceNames:$(n(),n()).default({}),kindLabels:$(n(),n()).default({}),labels:L8.default({}),strings:o({empty:n().optional(),emptyFiltered:n().optional(),error:n().optional(),retry:n().optional(),end:n().optional(),loadOlder:n().optional()}).default({}),search:n().default(""),searchMode:o7.default("text"),semanticLimit:i().int().min(1).max(200).default(50),semanticMinScore:i().min(0).max(1).optional(),filterDebug:w().default(!1),filterTrain:w().default(!1),filterFavourited:w().default(!1),showStationary:w().default(!1),excludeSources:y(X8).default([]),reviewedTrackIds:y(n()).default([]),showAdminFlags:w().default(!1),sinceMs:i().int().nonnegative().optional(),untilMs:i().int().nonnegative().optional(),pageSize:i().int().min(1).max(500).default(M5e),maxRows:i().int().min(1).max(5e3).default(C5e),refreshMs:i().int().min(0).max(6e5).default(_5e),maxAgeMs:i().int().min(6e4).default(I5e),theme:n7.default("auto"),locale:I(Lx).optional(),nativePullToRefresh:w().default(!1)}).superRefine(e7),l7=o({view:t7.optional(),rows:i().int().min(1).max(6).optional(),columns:s7.optional(),thumbSize:a7.optional(),fields:R5e.optional(),...jx.shape,deviceIds:y(i().int().nonnegative()).optional(),classes:y(n()).optional(),attrs:y(zx).optional(),deviceNames:$(n(),n()).optional(),kindLabels:$(n(),n()).optional(),labels:L8.optional(),strings:o({empty:n().optional(),emptyFiltered:n().optional(),error:n().optional(),retry:n().optional(),end:n().optional(),loadOlder:n().optional()}).optional(),search:n().optional(),searchMode:o7.optional(),semanticLimit:i().int().min(1).max(200).optional(),semanticMinScore:i().min(0).max(1).nullable().optional(),filterDebug:w().optional(),filterTrain:w().optional(),filterFavourited:w().optional(),showStationary:w().optional(),excludeSources:y(X8).optional(),reviewedTrackIds:y(n()).optional(),showAdminFlags:w().optional(),sinceMs:i().int().nonnegative().nullable().optional(),untilMs:i().int().nonnegative().nullable().optional(),pageSize:i().int().min(1).max(500).optional(),maxRows:i().int().min(1).max(5e3).optional(),refreshMs:i().int().min(0).max(6e5).optional(),maxAgeMs:i().int().min(6e4).optional(),theme:n7.optional(),locale:I(Lx).optional(),nativePullToRefresh:w().optional()});function cw(e){return e==="small"?60:e==="large"?106:80}function N5e(e,t=1){const a=Number.isFinite(t)&&t>0?t:1,r=Math.round(e*a);return Math.max(O5e,Math.min(D5e,r))}const O5e=64,D5e=320;function j5e(e){return cw(e)}function Fx(e){if(e==null)return{ok:!1,error:"config is required"};const t=P5e.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(a=>`${a.path.join(".")||"(root)"}: ${a.message}`).join("; ")}}function dw(e,t){const a=t.fields!==void 0?{...e.fields,...t.fields}:e.fields,{sinceMs:r,untilMs:c,semanticMinScore:m,...d}=t,{sinceMs:h,untilMs:f,semanticMinScore:k,...x}=e,E=ak(r,h),R=ak(c,f),T=ak(m,k);return{...x,...d,fields:a,...E!==void 0?{sinceMs:E}:{},...R!==void 0?{untilMs:R}:{},...T!==void 0?{semanticMinScore:T}:{}}}function ak(e,t){if(e!==null)return e??t}function z5e(e,t,a){const r=a[String(e)];return r!==void 0&&r.trim().length>0?r:t}const q5e={empty:"No events",emptyFiltered:"No events match this filter",error:"Couldn't load events",retry:"Retry",end:"·",loadOlder:"Load older events"};function mc(e,t){const a=e.strings[t];return a!==void 0&&a.trim().length>0?a:q5e[t]}const L5e=1e4;function c7(){try{return window.parent!==window}catch{return!0}}let uw=null;function d7(e){uw=e}function B5e(e){if(uw===null||typeof e!="object"||e===null)return e;const t=e;if(t.type!=="log")return e;const a=typeof t.data=="object"&&t.data!==null?t.data:{};return{...t,data:{deviceId:uw,...a}}}function qt(e){const t=B5e(e),a=window.ReactNativeWebView;if(a){a.postMessage(JSON.stringify(t));return}c7()&&window.parent.postMessage(t,"*")}function Gm(e){const t=a=>{const r=a.data;if(typeof r!="object"||r===null)return;const c=r;c.type!=="embed-command"||typeof c.command!="object"||c.command===null||e(c.command)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}function F5e(e,t,a,r,c){const m=t();if(m!=null)return Promise.resolve(a(m));if(c?.urlFirst===!0){const d=r!==void 0?r():null;if(d!==null)return Promise.resolve(d)}if(!c7()){const d=r!==void 0?r():null;return d!==null?Promise.resolve(d):Promise.resolve({ok:!1,error:`config global for mode "${e}" is not set`})}return new Promise(d=>{let h;const f=k=>{const x=k.data;if(typeof x!="object"||x===null)return;const E=x;E.type==="embed-config"&&(clearTimeout(h),window.removeEventListener("message",f),d(a(E.config)))};window.addEventListener("message",f),h=setTimeout(()=>{window.removeEventListener("message",f),d({ok:!1,error:"config handshake timed out"})},L5e),window.parent.postMessage({type:"embed-ready",mode:e},"*")})}function Wm(e,t,a,r,c){const[m,d]=P.useState(null),h=P.useRef(t);h.current=t;const f=P.useRef(a);f.current=a;const k=P.useRef(r);k.current=r;const x=c?.urlFirst===!0;return P.useEffect(()=>{let E=!0;return F5e(e,()=>h.current(),R=>f.current(R),()=>k.current!==void 0?k.current():null,{urlFirst:x}).then(R=>{E&&d(R)}),()=>{E=!1}},[e,x]),m}const tr=1,$5e=["window","semantic-search","macro-classes","device-names","kind-labels","heartbeat","track-list","attr-filters","flag-filters","debug-status","native-pull-refresh","track-list-delta"];function U5e(e){return{v:tr,type:"ready",view:e,features:[...$5e]}}function H5e(e){return{v:tr,type:"error",message:e}}function Sf(e,t){return t!==void 0?{v:tr,type:"state",state:e,message:t}:{v:tr,type:"state",state:e}}function Q5e(e){return{v:tr,type:"trackClick",...e}}function V5e(e,t){return{v:tr,type:"trackList",tracks:e,seq:t}}function K5e(e){return{v:tr,type:"trackListDelta",...e}}function ST(e,t,a,r="feed"){return{v:tr,type:"countChanged",loaded:e,shown:t,hasMore:a,mode:r}}function G5e(){return{v:tr,type:"heartbeat"}}function W5e(e){return{v:tr,type:"scroll",atTop:e}}function Z5e(){return{v:tr,type:"refreshed"}}function Ei(e){qt(e)}function qc(e,t,a="feed"){qt({type:"log",scope:a,msg:e,...t!==void 0?{data:t}:{}})}const Y5e=I(["full","delta"]),X5e=o({debug:w().optional(),markForTrain:w().optional(),favourited:w().optional()}),J5e=$(n(),X5e);function Su(e){if(typeof e!="object"||e===null)return null;const t=e,a=t.type;if(a==="refresh"||a==="reload"||a==="loadMore"||a==="scrollToTop"||a==="ping")return{type:a};if(a==="setWindow"){const c=eje.safeParse(t);return c.success?{type:"setWindow",...c.data.sinceMs!==void 0?{sinceMs:c.data.sinceMs}:{},...c.data.untilMs!==void 0?{untilMs:c.data.untilMs}:{}}:null}if(a==="setTrackListMode"){const c=Y5e.safeParse(t.mode);return c.success?{type:"setTrackListMode",mode:c.data}:null}if(a==="setTrackFlagPatches"){const c=J5e.safeParse(t.patches);return c.success?{type:"setTrackFlagPatches",patches:c.data}:null}if(a!=="setConfig")return null;const r=l7.safeParse(t.patch);return r.success?{type:"setConfig",patch:r.data}:null}const eje=o({sinceMs:i().int().nonnegative().nullable().optional(),untilMs:i().int().nonnegative().nullable().optional()});function tje(e){return{...e.sinceMs!==void 0?{sinceMs:e.sinceMs}:{},...e.untilMs!==void 0?{untilMs:e.untilMs}:{}}}const aje={blockedMs:0,maxLagMs:0,samples:0};function nje(e,t,a){if(a<=t)return aje;let r=0,c=0,m=0;for(const d of e){const h=d.at-d.lagMs,f=Math.min(d.at,a)-Math.max(h,t);f<=0||(r+=f,c=Math.max(c,d.lagMs),m+=1)}return{blockedMs:Math.round(r),maxLagMs:Math.round(c),samples:m}}function mw(e,t){const a=Math.min(Math.round(e),t.blockedMs);return{ms:Math.round(e),blockedMs:a,netMs:Math.max(0,Math.round(e)-a),maxLagMs:t.maxLagMs,lagSamples:t.samples}}const ije=250,wT=600,rje=8;let kc=[],xT=null;function oje(e){e.lagMs<rje||(kc.push(e),kc.length>wT&&(kc=kc.slice(kc.length-wT)))}function pw(e,t){return nje(kc,e,t)}function sje(e=ije,t=()=>performance.now(),a=(r,c)=>{const m=setInterval(r,c);return()=>clearInterval(m)}){if(xT!==null)return;let r=t()+e;xT={stop:a(()=>{const m=t();oje({at:m,lagMs:Math.max(0,m-r)}),r=m+e},e)}}function lje(e){return e.responseEnd<=0||e.requestStart===0&&e.responseStart===0?null:{totalMs:Math.round(e.responseEnd-e.startTime),queuedMs:Math.round(Math.max(0,e.requestStart-e.startTime)),ttfbMs:Math.round(Math.max(0,e.responseStart-e.requestStart)),transferSize:Math.round(e.transferSize??0)}}function cje(e,t){let a=null;for(const r of e)r.startTime+1<t||(a===null||r.startTime<a.startTime)&&(a=r);return a}function dje(){if(typeof performance>"u")return null;const e=performance;if(typeof e!="object"||e===null||!("getEntriesByName"in e))return null;const t=e.getEntriesByName;return typeof t!="function"?null:{getEntriesByName:(a,r)=>t.call(performance,a,r)}}function uje(e,t,a=dje()){if(a===null)return null;try{const r=cje(a.getEntriesByName(e,"resource"),t);return r===null?null:lje(r)}catch{return null}}const mje=250,ro=new Map,nk=new Map,pje=6,hje=1e4,fje=5e3,ik=[250,750];let rk=5;const MT=32;function gje(e){try{const t=new URL(e),a=t.pathname.lastIndexOf("/"),r=a>=0?`${t.pathname.slice(0,a)}/<id>`:t.pathname;return{origin:t.origin,path:r,query:t.search}}catch{const t=e.slice(0,MT);return{origin:"(unparseable)",path:e.length>MT?`${t}…`:t,query:""}}}function vje(e){return e instanceof Error?{errorName:e.name,errorMessage:e.message}:{errorName:"unknown",errorMessage:String(e)}}let rg=0,u7=[];async function yje(){if(rg<pje){rg+=1;return}await new Promise(e=>{u7.push(e)})}function bje(){const e=u7.shift();if(e!==void 0){e();return}rg=Math.max(0,rg-1)}function kje(e,t){for(ro.set(e,t);ro.size>mje;){const a=ro.keys().next();if(a.done===!0)break;const r=ro.get(a.value);ro.delete(a.value),r!==void 0&&URL.revokeObjectURL(r)}}async function m7(e,t){const a=ro.get(e);if(a!==void 0)return ro.delete(e),ro.set(e,a),{status:"ready",src:a};const r=nk.get(e);if(r!==void 0)return r;const c=(async()=>{const m=performance.now(),d=gje(e);let h={lastStatus:null,errorName:null,errorMessage:null},f=0;try{for(let k=0;k<=ik.length;k+=1){const x=performance.now();await yje(),f+=performance.now()-x;const E=performance.now(),R=new AbortController,T=setTimeout(()=>R.abort(),hje);try{const j=await fetch(e,{headers:w5e(t),signal:R.signal});if(j.ok){const q=Math.round(performance.now()-E),B=await j.blob(),F=Math.round(performance.now()-m),U=Math.round(performance.now()-E),H=URL.createObjectURL(B);if(kje(e,H),rk>0||F>=500){rk=Math.max(0,rk-1);const Q=uje(e,E),te=mw(performance.now()-E,pw(E,performance.now()));qc("thumbnail ready",{ms:F,queuedMs:Math.round(f),headersMs:q,blobMs:U-q,blockedMs:te.blockedMs,maxLagMs:te.maxLagMs,netTotalMs:Q?.totalMs??null,netQueuedMs:Q?.queuedMs??null,netTtfbMs:Q?.ttfbMs??null,bytes:B.size,attempt:k+1,serverTiming:j.headers?.get("server-timing")??null},"media")}return{status:"ready",src:H}}if(j.status===401||j.status===403||j.status===404)return qc("thumbnail missing",{ms:Math.round(performance.now()-m),queuedMs:Math.round(f),status:j.status,attempt:k+1,...d},"media"),{status:"missing"};h={lastStatus:j.status,errorName:null,errorMessage:null}}catch(j){h={lastStatus:null,...vje(j)}}finally{clearTimeout(T),bje()}const N=ik[k];N!==void 0&&await new Promise(j=>setTimeout(j,N))}return qc("thumbnail transient failure",{ms:Math.round(performance.now()-m),queuedMs:Math.round(f),attempts:ik.length+1,...h,...d},"media"),{status:"transient-failure"}}finally{nk.delete(e)}})();return nk.set(e,c),c}async function Sje(e,t){const a=await m7(e,t);return a.status==="ready"?a.src:null}function p7(e,t){const[a,r]=P.useState({status:"loading"}),[c,m]=P.useState(0);return P.useEffect(()=>{if(e===null){r({status:"loading"});return}const d=ro.get(e);if(d!==void 0){r({status:"ready",src:d});return}let h=!0,f;return r({status:"loading"}),m7(e,t).then(k=>{if(h){if(k.status==="ready"){r({status:"ready",src:k.src});return}if(k.status==="missing"){r({status:"failed"});return}f=setTimeout(()=>m(x=>x+1),fje)}}),()=>{h=!1,f!==void 0&&clearTimeout(f)}},[e,t,c]),a}function wje(e){const t=e?.clientHeight??0;return t>0?t:600}function xje(e,t){const{root:a,disabled:r}=t,[c,m]=P.useState(r===!0),d=P.useRef(c);return d.current=c,P.useEffect(()=>{if(d.current)return;if(r===!0){m(!0);return}const h=e.current;if(!h||typeof IntersectionObserver!="function"){m(!0);return}const f=new IntersectionObserver(k=>{k.some(x=>x.isIntersecting)&&(m(!0),f.disconnect())},{root:a,rootMargin:`${wje(a)}px`});return f.observe(h),()=>f.disconnect()},[e,a,r]),c}const Mje={display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:14,height:14,padding:"0 3px",borderRadius:4,fontSize:9,fontWeight:700,lineHeight:"14px",letterSpacing:.2},Cje=P.memo(function({row:t,serverUrl:a,token:r,thumbPx:c,width:m,heroPx:d,fields:h,display:f,palette:k,nowMs:x,locale:E,variant:R,iconId:T,kindLabels:N=Kg,labels:j=Px,scrollRoot:q,eagerImages:B,showAdminFlags:F,onClick:U}){const H=pd(),Q=Yt[k.colorScheme],te=IDe({background:k.background}),K=k.text,W=Yt.light.primaryForeground,oe={...Mje,background:te,color:K},he=P.useRef(null),we=xje(he,{root:q,...B===!0?{disabled:!0}:{}})?Nx(a,t.trackId,c):null,Ee=p7(we,r),Ie=sw(t.className,ig(t),H),Me=R==="reel",Y=d,de=Z8(t,N),Re=f.tileLabelMode!=="off",Qe=f.tileLabelMode==="label"&&de.tier!=="class",re=Re&&!Qe,V=n5e(de.text,d),ie=f.tileLabelMode==="label",fe=KDe(t,ie,de.text,N),be=jS(T),ee=v.jsxs("div",{style:{position:"relative",width:Me?d:"100%",height:Me?d:void 0,aspectRatio:Me?void 0:"1 / 1",borderRadius:10,overflow:"hidden",background:k.skeleton,border:`1px solid ${k.border}`,boxSizing:"border-box",flex:"0 0 auto"},children:[v.jsx("div",{className:Ee.status==="loading"?"events-skeleton":void 0,"data-testid":"card-image-backing",style:{position:"absolute",inset:0,background:Ee.status==="failed"?`${Ie}22`:k.skeleton,boxShadow:`inset 0 0 0 1px ${k.border}`}}),Ee.status==="ready"?v.jsx("img",{src:Ee.src,alt:"",draggable:!1,style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover",display:"block"}}):null,Re&&v.jsxs("div",{style:{position:"absolute",left:4,right:4,bottom:4,display:"flex",flexWrap:Me?"nowrap":"wrap",gap:3,alignItems:"center",pointerEvents:"none"},children:[re&&v.jsx("span",{"data-testid":"card-class-glyph",title:kf(t.className,N),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",background:`${Ie}E6`,color:W,borderRadius:4,padding:"2px 4px",flex:"0 0 auto"},children:v.jsx(be,{size:13,color:W})}),Qe&&v.jsx("span",{"data-testid":"card-title",title:de.fullText??de.text,style:{background:te,color:K,fontSize:Me?lw:V.fontSizePx,fontWeight:700,lineHeight:1.35,padding:"2px 6px",borderRadius:4,overflow:"hidden",minWidth:0,...Me?{textOverflow:"ellipsis",whiteSpace:"nowrap"}:{display:"-webkit-box",WebkitLineClamp:V.maxLines,WebkitBoxOrient:"vertical",whiteSpace:"normal",overflowWrap:"anywhere"}},children:de.text}),!Me&&Re&&t.audioLabels.filter(wt=>wt!==t.className&&wt!==t.label).map(wt=>{const sa=Km(wt),nt=jS(sa);return v.jsx("span",{title:Q8(wt,N),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",background:`${sw("audio",!0,H)}E6`,color:W,borderRadius:4,padding:"2px 4px",flex:"0 0 auto"},children:v.jsx(nt,{size:13,color:W})},`audio-${wt}`)})]}),(F===!0&&(t.debug===!0||t.reviewed===!0||t.markForTrain===!0||t.retrainStatus==="trained")||t.favourited===!0)&&v.jsxs("span",{"data-testid":"card-flags",style:{position:"absolute",top:4,left:4,display:"inline-flex",gap:2,zIndex:2},children:[F===!0&&t.reviewed===!0&&v.jsx("span",{title:j.reviewed,style:oe,children:"✓"}),F===!0&&t.debug===!0&&t.reviewed!==!0&&v.jsx("span",{title:j.debug,style:oe,children:"D"}),F===!0&&t.markForTrain===!0&&v.jsx("span",{title:j.train,style:oe,children:"T"}),F===!0&&t.retrainStatus==="trained"&&t.markForTrain!==!0&&v.jsx("span",{title:j.trained,"data-testid":"retrain-status-trained",style:oe,children:"✓T"}),t.favourited===!0&&v.jsx("span",{title:j.favourite,style:{...oe,color:Q.warning},children:"★"})]}),h.badges&&t.active&&v.jsx("span",{title:j.active,style:{position:"absolute",top:4,right:4,width:8,height:8,borderRadius:999,background:Q.success,boxShadow:`0 0 0 2px ${V8(k.background,.35)}`}}),h.time?v.jsx("span",{"data-testid":"card-time",style:{position:"absolute",top:4,right:h.badges&&t.active?16:4,background:te,color:K,fontSize:9,fontWeight:700,fontVariantNumeric:"tabular-nums",padding:"1px 5px",borderRadius:5,zIndex:2},children:dDe(t.lastSeen,x,E)}):null]});if(Me)return v.jsx("button",{ref:he,type:"button",onClick:()=>U(t),"data-track-id":t.trackId,"data-device-id":t.deviceId,style:{width:m,height:Y,minWidth:m,minHeight:Y,display:"flex",flexDirection:"column",alignItems:"center",padding:0,border:"none",background:"transparent",cursor:"pointer",font:"inherit",color:k.text,boxSizing:"border-box",contain:"layout paint",overflow:"hidden"},children:ee});const Se=t.cameraName,_e=f.tileDetailCamera,Be=f.tileDetailZone&&t.zonesVisited.length>0,Ge=h.sublabel&&fe.length>0,Ft=_e||Be||Ge,Ot=o5e(Se,d);return v.jsxs("button",{ref:he,type:"button",onClick:()=>U(t),"data-track-id":t.trackId,"data-device-id":t.deviceId,style:{width:m,display:"flex",flexDirection:"column",gap:2,padding:0,border:"none",background:"transparent",cursor:"pointer",textAlign:"left",font:"inherit",color:k.text,boxSizing:"border-box"},children:[ee,Ft&&v.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:1,minWidth:0,paddingBottom:1},children:[Ge&&v.jsx("span",{style:{fontSize:Math.max(9,Ot.fontSizePx-1),color:k.textMuted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:fe}),_e&&v.jsx("span",{"data-testid":"card-camera",title:Se,style:{fontSize:Ot.fontSizePx,fontWeight:600,lineHeight:1.2,display:"-webkit-box",WebkitLineClamp:Ot.maxLines,WebkitBoxOrient:"vertical",overflow:"hidden",overflowWrap:"anywhere"},children:Se}),Be&&v.jsx("span",{"data-testid":"card-zone",style:{fontSize:Math.max(9,Ot.fontSizePx-2),color:k.textMuted,background:k.chip,borderRadius:5,padding:"1px 5px",alignSelf:"flex-start",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"100%"},children:t.zonesVisited.join(" · ")})]})]})}),h7=new Map,CT=new Set;function AT(e,t){const a=`${e}|${t??""}`;CT.has(a)||(CT.add(a),qt({type:"log",scope:"palette",msg:"display palette unknown; painting the bundled preset",data:{reason:t,serverUrl:e}}))}async function IT(e){const t=e.serverUrl;try{const a=await e.trpcClient.displayPalette.getPalette.query(),r=RDe(TDe(a),t);return r.origin==="unknown"?AT(t,r.reason):h7.set(t,r),r}catch(a){const r=_De(a);return AT(t,r),ow("unknown",r,t)}}function Aje(e){P.useEffect(()=>{const t=h7.get(e.serverUrl);t!==void 0&&Y1(t);let a=!1;return IT(e).then(r=>{a||Y1(r)}),()=>{a=!0}},[e]),P.useEffect(()=>{let t=null;return e.subscribeConnectionEvents(a=>{const r=t;t=a,r!==null&&r!=="connected"&&a==="connected"&&IT(e).then(c=>Y1(c))})},[e])}function Wg({system:e}){Aje(e);const t=pd();return t.origin!=="unknown"||t.reason===null?null:v.jsx("p",{role:"status","data-testid":"palette-unknown",style:{margin:0,padding:"6px 10px",fontSize:12,color:Yt.dark.warning,background:Yt.dark.background},children:`Palette unreadable (${t.reason}). Using the CamStack preset.`})}function Ije(e){return{listRecentTracks:t=>e.trpcClient.pipelineAnalytics.listRecentTracks.query(t),listDevices:()=>e.trpcClient.deviceManager.listAll.query({isCamera:!0,projection:"slim"}),searchObjectEvents:t=>e.trpcClient.pipelineAnalytics.searchObjectEvents.query(t),listEventKinds:t=>e.trpcClient.pipelineAnalytics.listEventKindsBatch.query({deviceIds:t})}}const ET=200,Eje=45;function hw(e){return{trackId:e.trackId,deviceId:e.deviceId,bestEventId:e.bestEventId,className:e.className,firstSeen:e.firstSeen,lastSeen:e.lastSeen}}function fw(e,t){if(e.length!==t.length)return!1;for(let a=0;a<e.length;a+=1)if(e[a]!==t[a])return!1;return!0}function Rje(e,t){const a=t.map(T=>T.trackId);if(fw(e,a))return{kind:"unchanged"};if(e.length===0)return{kind:"reset"};const r=new Set(e);let c=a.length-1,m=e.length-1,d=a.length;for(;c>=0&&!r.has(a[c]);)d=c,c-=1;const h=[];for(;c>=0&&m>=0;){if(a[c]===e[m]){c-=1,m-=1;continue}h.push(e[m]),m-=1}const f=c+1;for(;m>=0;)h.push(e[m]),m-=1;const k=new Set(h),x=[...a.slice(0,f),...e.filter(T=>!k.has(T)),...a.slice(d)];if(!fw(x,a))return{kind:"reset"};const E=f+(a.length-d);return ET*E+Eje*h.length>=ET*a.length?{kind:"reset"}:{kind:"delta",prepend:t.slice(0,f).map(hw),append:d===a.length?[]:t.slice(d).map(hw),removeIds:h}}const Tje={seq:0,sentIds:null,mode:"full"};function wf(e,t,a){const r=e.seq+1;return{state:{seq:r,sentIds:a,mode:e.mode},message:V5e(t.map(hw),r)}}function _je(e,t){const a=t.map(m=>m.trackId);if(e.sentIds===null)return wf(e,t,a);if(e.mode==="full")return fw(e.sentIds,a)?{state:e,message:null}:wf(e,t,a);const r=Rje(e.sentIds,t);if(r.kind==="unchanged")return{state:e,message:null};if(r.kind==="reset")return wf(e,t,a);const c=e.seq+1;return{state:{seq:c,sentIds:a,mode:e.mode},message:K5e({seq:c,baseSeq:e.seq,prepend:r.prepend,append:r.append,removeIds:r.removeIds,count:a.length})}}function Pje(e,t,a){const r=a.map(c=>c.trackId);return wf({...e,mode:t},a,r)}function Nje(e){let t=Tje,a=[];const r=c=>{t=c.state,c.message!==null&&e(c.message)};return{report:c=>{a=c,r(_je(t,c))},setMode:c=>{r(Pje(t,c,a))}}}const Oje=2e3,Dje=1e3;function RT(e,t){const a=Math.max(1,Math.floor(e)),r=Math.max(1,Math.floor(t)),c=Math.max(1,Math.floor(Oje/r));return Math.min(a,Dje,c)}function f7(e,t){return e.lastSeen!==t.lastSeen?t.lastSeen-e.lastSeen:e.trackId===t.trackId?0:e.trackId<t.trackId?1:-1}const Tu={rows:[],cursor:null,exhausted:!1,rebuild:null},jje=8;function gw(e,t){const a=new Map;for(const r of e)a.set(r.trackId,r);for(const r of t)a.set(r.trackId,r);return[...a.values()].sort(f7)}function zje(e,t,a){const r=e.rebuild;if(r===null)return{rows:gw(e.rows,t),cursor:a,exhausted:a===null,rebuild:null};const c=gw(r.rows,t),m=r.pages+1,d=c.length>=r.floor;return a===null||d||m>=jje?{rows:c,cursor:a,exhausted:a===null,rebuild:null}:{...e,rebuild:{rows:c,cursor:a,exhausted:!1,floor:r.floor,pages:m}}}function qje(e){return e.rows.length===0?Tu:{...e,rebuild:{rows:[],cursor:null,exhausted:!1,floor:e.rows.length,pages:0}}}function Lje(e){return e.rebuild===null?e:{...e,rebuild:null}}function Bje(e){return e.rebuild!==null}function TT(e){return e.rebuild!==null?e.rebuild.cursor:e.cursor}function Fje(e,t,a){const r=new Set(e.rows.map(m=>m.trackId));let c=0;for(const m of t)r.has(m.trackId)||(c+=1);return{state:{...e,rows:gw(e.rows,t)},gap:a!==null,deltaCursor:a,added:c}}function $je(e){const t=e.rows[0];return t!==void 0?t.lastSeen:null}function g7(e,t){const a=e.rebuild??e;return a.exhausted?"exhausted":a.rows.length<Math.max(1,t)?"more":"ceiling"}function _T(e,t){return g7(e,t)==="more"}function Uje(e,t){return Math.max(0,e-Math.max(0,t))}function Hje(e){const t=e.sinceMs??Uje(e.anchorMs,e.maxAgeMs);return e.untilMs!==void 0?{since:t,until:e.untilMs}:{since:t}}function Qje(e,t){return e===void 0||e>t}function Vje(e,t){return e}function Kje(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wu(e){return typeof e=="string"&&e.length>0?e:void 0}function Gje(e,t,a){const r=t.length===1?t[0]:void 0;return{text:e,limit:a.semanticLimit,...a.semanticMinScore!==void 0?{minScore:a.semanticMinScore}:{},...r!==void 0?{deviceId:r}:{},...a.sinceMs!==void 0?{since:a.sinceMs}:{},...a.untilMs!==void 0?{until:a.untilMs}:{}}}function Wje(e,t){if(!Kje(e))return null;const a=wu(e.id),r=wu(e.className);if(a===void 0||r===void 0||typeof e.deviceId!="number"||typeof e.timestamp!="number"||typeof e.score!="number")return null;const c=wu(e.trackId),m=typeof e.mediaId=="number"?String(e.mediaId):void 0,d=wu(e.label),h=wu(e.subLabel);return{trackId:c??a,deviceId:e.deviceId,cameraName:t.get(e.deviceId)??`Camera ${e.deviceId}`,className:r,...d!==void 0?{label:d}:{},...h!==void 0?{subLabel:h}:{},...typeof e.importance=="number"?{importance:e.importance}:{},firstSeen:e.timestamp,lastSeen:e.timestamp,state:"idle",active:!1,zonesVisited:[],zoneNames:[],classes:[r],audioLabels:[],bestEventId:m??c??a,score:e.score}}function Zje(e,t){if(!Array.isArray(e))return[];const a=new Map;for(const r of e){const c=Wje(r,t);if(c===null)continue;const m=a.get(c.trackId);(m===void 0||c.score>m.score)&&a.set(c.trackId,c)}return[...a.values()].sort((r,c)=>r.score!==c.score?c.score-r.score:c.lastSeen-r.lastSeen)}function Yje(e,t,a){const r=new Map;for(const c of e)r.set(c.trackId,c);for(const c of t)r.set(c.trackId,c);return Vje([...r.values()].sort(f7))}function Xje(e,t){if(e.length===0)return e;const a=Math.max(1,Math.floor(t.rowsPerColumn)),r=Math.max(1,t.cardWidth+t.gap),c=Math.max(0,Math.floor(Math.max(0,t.scrollLeft)/r)),m=t.viewportWidth>0?t.viewportWidth:t.cardWidth,d=Math.max(c+1,Math.ceil((Math.max(0,t.scrollLeft)+m*2)/r));return e.slice(c*a,Math.min(e.length,d*a))}const Jje=18;function eze(e){const t=Math.max(0,e.gap),a=Math.max(1,e.cardWidth),r=Math.max(0,e.viewportWidth),c=e.columns??"auto",m=c==="auto"?Math.max(1,Math.floor((r+t)/(a+t))):Math.max(1,Math.floor(c)),d=r>0?(r-(m-1)*t)/m:a;return{columns:m,columnWidth:d,rowStridePx:Math.max(1,d+Jje+t)}}const tze=2,aze={startRow:0,endRow:0,padTopPx:0,padBottomPx:0,totalPx:0};function nze(e){const t=Math.max(0,Math.floor(e.rowCount));if(t===0)return aze;const a=e.estimatedRowPx>0?e.estimatedRowPx:1,r=q=>{const B=e.measuredPx.get(q);return B!==void 0&&B>0?B:a};let c=0;for(let q=0;q<t;q+=1)c+=r(q);if(e.viewportHeight<=0)return{startRow:0,endRow:t,padTopPx:0,padBottomPx:0,totalPx:c};const m=Math.max(0,e.scrollTop),d=m+e.viewportHeight;let h=0,f=0;for(;h<t-1&&f+r(h)<=m;)f+=r(h),h+=1;let k=h,x=f;for(;k<t&&x<d;)x+=r(k),k+=1;const E=Math.max(0,Math.floor(e.overscanRows??tze)),R=Math.max(0,h-E),T=Math.min(t,k+E);let N=0;for(let q=0;q<R;q+=1)N+=r(q);let j=0;for(let q=R;q<T;q+=1)j+=r(q);return{startRow:R,endRow:T,padTopPx:N,padBottomPx:Math.max(0,c-N-j),totalPx:c}}function ize(e,t){let a=0,r=0;for(const c of e.values())c>0&&(a+=c,r+=1);return r===0?Math.max(1,t):Math.max(1,a/r)}const rze=24,oze=2;function sze(e,t,a){if(e.length===0)return e;const r=Math.max(1,Math.floor(a)),c=Math.max(0,t.startRow)*r,m=Math.max(1,t.endRow-t.startRow+oze),d=Math.min(e.length,c+Math.min(m*r,rze));return e.slice(c,d)}function lze(e){const{rowCount:t,scrollTop:a,viewportHeight:r,fallbackRowPx:c,geometryKey:m}=e,d=P.useRef(new Map),h=P.useRef(new Map),[f,k]=P.useState(()=>new Map),x=P.useRef(m);P.useEffect(()=>{x.current!==m&&(x.current=m,h.current=new Map,k(new Map))},[m]);const E=P.useCallback(T=>{const N=h.current.get(T);if(N!==void 0)return N;const j=q=>{q===null?d.current.delete(T):d.current.set(T,q)};return h.current.set(T,j),j},[]);return P.useLayoutEffect(()=>{let T=null;for(const[N,j]of d.current){const q=Math.round(j.getBoundingClientRect().height);q<=0||f.get(N)!==q&&(T??=new Map(f),T.set(N,q))}T!==null&&k(T)}),{window:P.useMemo(()=>nze({rowCount:t,scrollTop:a,viewportHeight:r,estimatedRowPx:ize(f,c),measuredPx:f}),[t,a,r,c,f]),measureRow:E}}const cze=1,dze=s5e,uze=["label","sublabel","camera","time","badges","importance"];function pc(e,t){const a=e.get(t);if(a===null||a.trim()==="")return;const r=Number.parseInt(a,10);return Number.isFinite(r)?r:void 0}function PT(e,t){const a=e.get(t)?.trim().toLowerCase();if(a==="1"||a==="true")return!0;if(a==="0"||a==="false")return!1}function mze(e){if(e===null)return;if(e.trim()==="")return[];const t=[];for(const a of e.split(",")){const r=Number.parseInt(a.trim(),10);Number.isFinite(r)&&r>=0&&t.push(r)}return t}function vw(e){if(e!==null)return e.trim()===""?[]:e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function pze(e){if(e===null)return;const t=new Set((vw(e)??[]).map(r=>r.toLowerCase())),a={};for(const r of uze)a[r]=t.has(r.toLowerCase());return a}function hze(e,t){const a=e.startsWith("?")?e.slice(1):e;for(const r of a.split("&")){if(r.length===0)continue;const c=r.indexOf("=");if((c===-1?r:r.slice(0,c))===t)return c===-1?"":r.slice(c+1)}return null}function fze(e){if(e===null)return;const t={};if(e.trim()==="")return t;for(const a of e.split(",")){const r=a.indexOf(":");if(r<=0)continue;const c=a.slice(0,r).trim();if(!/^\d+$/.test(c))continue;let m;try{m=decodeURIComponent(a.slice(r+1))}catch{continue}m.trim().length!==0&&(t[c]=m)}return t}function NT(e,t){const a=e.get(t);if(a===null)return;if(a.trim()==="")return null;const r=Number.parseInt(a,10);return Number.isFinite(r)&&r>=0?r:void 0}function gze(e){if(e===null||e.trim()==="")return;if(e==="auto")return"auto";const t=Number.parseInt(e,10);return Number.isFinite(t)?t:void 0}function vze(e){const t=e.startsWith("#")?e.slice(1):e;if(t.length===0)return null;const a=new URLSearchParams(t).get("t");return a!==null&&a.length>0?a:null}function v7(e){const t=new URLSearchParams(e.startsWith("?")?e.slice(1):e),a=t.get("v");if(a===null)return null;if(Number.parseInt(a,10)!==cze)return{ok:!1,error:`unsupported events URL version "${a}"`};const c={},m=t.get("view");m!==null&&(c.view=m);const d=pc(t,"rows");d!==void 0&&(c.rows=d);const h=gze(t.get("cols"));h!==void 0&&(c.columns=h);const f=t.get("thumb");f!==null&&(c.thumbSize=f);const k=pze(t.get("fields"));k!==void 0&&(c.fields=k);const x=t.get("tileLabelMode");x!==null&&(c.tileLabelMode=x);const E=PT(t,"tileDetailCamera");E!==void 0&&(c.tileDetailCamera=E);const R=PT(t,"tileDetailZone");R!==void 0&&(c.tileDetailZone=R);const T=mze(t.get("devices"));T!==void 0&&(c.deviceIds=T);const N=vw(t.get("classes"));N!==void 0&&(c.classes=N);const j=vw(t.get("attrs"));j!==void 0&&(c.attrs=j);const q=t.get("q");q!==null&&(c.search=q);const B=pc(t,"page");B!==void 0&&(c.pageSize=B);const F=pc(t,"max");F!==void 0&&(c.maxRows=F);const U=pc(t,"refresh");U!==void 0&&(c.refreshMs=U);const H=pc(t,"age");H!==void 0&&(c.maxAgeMs=H);const Q=t.get("theme");Q!==null&&(c.theme=Q);const te=i7(t.get("lang"));te!==void 0&&(c.locale=te);const K=t.get("smode");K!==null&&(c.searchMode=K);const W=pc(t,"slimit");W!==void 0&&(c.semanticLimit=W);const oe=t.get("sscore");if(oe!==null&&oe.trim()!==""){const Ie=Number.parseFloat(oe);Number.isFinite(Ie)&&(c.semanticMinScore=Ie)}const he=NT(t,"since");he!==void 0&&(c.sinceMs=he);const Ae=NT(t,"until");Ae!==void 0&&(c.untilMs=Ae);const we=fze(hze(e,"names"));we!==void 0&&(c.deviceNames=we);const Ee=l7.safeParse(c);return Ee.success?{ok:!0,patch:Ee.data}:{ok:!1,error:Ee.error.issues.map(Ie=>`${Ie.path.join(".")||"(root)"}: ${Ie.message}`).join("; ")}}function yze(e,t,a,r=""){const c=v7(e);if(c===null)return null;if(!c.ok)return{ok:!1,error:c.error};const m=x5e(a,r,dze),d=vze(t);return d===null&&!qx(m)?null:Fx({serverUrl:m,...d!==null?{token:d}:{},fields:r7,...c.patch})}function y7(){const e=yze(location.search,location.hash,location.origin,location.pathname);return e!==null&&location.hash!==""&&history.replaceState(null,"",location.pathname+location.search),e}function bze(){const e=v7(location.search);return e===null||!e.ok?null:e.patch}function kze(e,t){return!e.ok||t===null?e:{ok:!0,config:dw(e.config,t)}}const Sze=/^(10\.|127\.|192\.168\.|169\.254\.|172\.(1[6-9]|2\d|3[01])\.)/;function wze(e){let t;try{const m=qx(e)&&typeof location<"u"?location.href:void 0;t=new URL(e,m).host}catch{return"unknown:(unparseable)"}const a=t.trim().toLowerCase().replace(/^\[([^\]]*)\].*$/,"$1"),r=a.lastIndexOf(":"),c=r!==-1&&a.indexOf(":")===r?a.slice(0,r):a;return c==="localhost"||c==="::1"||c.startsWith("127.")?`loopback:${t}`:Sze.test(c)||/^f[cd][0-9a-f]{2}:/.test(c)||c.startsWith("fe80:")||c.endsWith(".local")?`lan:${t}`:c.includes(".")?`public:${t}`:`unknown:${t}`}const xze=4,Mze=1e3,OT=4e3,Cze=new Set(["UNAUTHORIZED","FORBIDDEN","NOT_FOUND"]),Aze=new Set([401,403,404]),Ize=.8,Eze=.4;function yw(e,t){if(typeof e!="object"||e===null)return null;const a=Reflect.get(e,t);return typeof a=="string"?a:null}function DT(e,t){if(typeof e!="object"||e===null)return null;const a=Reflect.get(e,t);return typeof a=="number"?a:null}function jT(e){return typeof e!="object"||e===null?null:Reflect.get(e,"data")}function zT(e){if(typeof e!="object"||e===null)return null;const t=Reflect.get(e,"shape");return typeof t!="object"||t===null?null:Reflect.get(t,"data")}function Rze(e){return typeof e=="string"?e:yw(e,"message")}function qT(e){return e!==null&&Cze.has(e)}function LT(e){return e!==null&&Aze.has(e)}function Tze(e){return e===null?!1:e.includes("UNAUTHORIZED")||e.includes("FORBIDDEN")||e.includes("NOT_FOUND")}function b7(e){return qT(yw(jT(e),"code"))||LT(DT(jT(e),"httpStatus"))||qT(yw(zT(e),"code"))||LT(DT(zT(e),"httpStatus"))?!0:Tze(Rze(e))}function _ze(e,t,a=Math.random){if(b7(t)||!Number.isInteger(e)||e<0||e+1>=xze)return null;const r=Math.min(OT,Mze*2**e),c=Math.min(1,Math.max(0,a())),m=Math.round(r*(Ize+c*Eze));return Math.min(OT,m)}const BT=5;let Pze=0;function Nze(e){if(typeof e!="object"||e===null)return!1;const t=e;return"tracks"in t&&(t.nextCursor===null||typeof t.nextCursor=="string")}const Oze=()=>{},Dze=[];function jze(e){const{client:t,deviceIds:a,nameById:r,pageSize:c,maxRows:m,refreshMs:d,maxAgeMs:h}=e,f=e.log??Oze,k=P.useRef(f);P.useEffect(()=>{k.current=f},[f]);const{sinceMs:x,untilMs:E,devicesResolved:R}=e,T=e.includeStationary===!0,N=e.excludeSources??Dze,j=[...N].sort().join(","),[q,B]=P.useState(Tu),[F,U]=P.useState(!1),[H,Q]=P.useState(!1),[te,K]=P.useState(null),[W,oe]=P.useState(0),[he,Ae]=P.useState(m),we=P.useRef(m);we.current=he;const Ee=P.useRef(Tu);Ee.current=q;const Ie=P.useRef(!1),Me=P.useRef(!1),Y=P.useRef(0),de=P.useRef(null),Re=P.useRef(Date.now()),Qe=P.useRef(r);Qe.current=r;const re=P.useRef(e.channel);re.current=e.channel;const V=P.useRef(null);P.useEffect(()=>{sje()},[]);const ie=a.join(","),fe=P.useCallback(async(ft,lt=0)=>{const Dt=`feed-${String(++Pze)}`,bt=performance.now();try{const ve=await t.listRecentTracks(ft),Fe=performance.now(),Le=mw(Fe-bt,pw(bt,Fe)),ot={requestId:Dt,waitMs:Math.round(lt),...Le};return Nze(ve)?{ok:!0,page:ve,timing:ot}:(k.current("request invalid",{...ot,channel:re.current}),{ok:!1,message:"unexpected response shape",error:new Error("unexpected response shape")})}catch(ve){const Fe=ve instanceof Error?ve.message:String(ve),Le=performance.now();return k.current("listRecentTracks failed",{error:Fe,devices:ft.deviceIds.length,limit:ft.limit,since:ft.since,cursor:ft.cursor??null,requestId:Dt,channel:re.current,waitMs:Math.round(lt),...mw(Le-bt,pw(bt,Le))}),{ok:!1,message:Fe,error:ve}}},[t]),be=P.useCallback((ft,lt)=>{k.current("request complete",{...ft,channel:re.current,...lt})},[]),ee=P.useCallback(()=>{if(Ie.current){Me.current=!0,V.current===null&&(V.current=performance.now());return}const ft=Ee.current;if(!_T(ft,we.current)||a.length===0)return;const lt=V.current;V.current=null;const Dt=lt===null?0:performance.now()-lt;Ie.current=!0,Q(!0);const bt=RT(c,a.length),ve=Hje({anchorMs:Re.current,maxAgeMs:h,...x!==void 0?{sinceMs:x}:{},...E!==void 0?{untilMs:E}:{}}),Fe=TT(ft)!==null;fe({deviceIds:[...a],since:ve.since,limit:bt,projection:"slim",...T?{includeStationary:!0}:{},...N.length>0?{excludeSources:[...N]}:{},...ve.until!==void 0?{until:ve.until}:{},...(()=>{const Le=TT(ft);return Le!==null?{cursor:Le}:{}})()},Dt).then(Le=>{if(Le.ok){const $t=performance.now(),ze=hT(Le.page.tracks,Qe.current),st=zje(Ee.current,ze,Le.page.nextCursor);Ee.current=st,B(st),be(Le.timing,{rows:ze.length,devices:a.length,limit:bt,paged:Fe,parseMs:Math.round(performance.now()-$t)}),Y.current=0,K(null),U(!0);return}const ot=Y.current,He=_ze(ot,Le.error);if(He!==null){Y.current=ot+1,k.current("page failed — retrying",{attempt:ot+1,backoffMs:He}),de.current=setTimeout(()=>{de.current=null,Se.current()},He);return}k.current("page failed — giving up",{attempt:ot+1,terminal:b7(Le.error)}),Y.current=0;const ea=Lje(Ee.current);Ee.current=ea,B(ea),K(Le.message),U(!0)}).finally(()=>{if(Ie.current=!1,Q(!1),Bje(Ee.current)){Se.current();return}Me.current&&(Me.current=!1,Se.current())})},[fe,be,a,ie,c,h,x,E,T,j]),Se=P.useRef(ee);Se.current=ee;const _e=P.useCallback(()=>{if(Ie.current||a.length===0)return Promise.resolve();const ft=$je(Ee.current);if(ft===null)return Ot.current(),Promise.resolve();Ie.current=!0;const lt=RT(c,a.length);return(async()=>{let Dt=null,bt=0,ve=!0;for(;ve&&bt<BT;){const Fe=await fe({deviceIds:[...a],since:ft,limit:lt,projection:"slim",...T?{includeStationary:!0}:{},...N.length>0?{excludeSources:[...N]}:{},...E!==void 0?{until:E}:{},...Dt!==null?{cursor:Dt}:{}});if(!Fe.ok)return;const Le=Fe.page,ot=performance.now(),He=hT(Le.tracks,Qe.current),ea=Fje(Ee.current,He,Le.nextCursor);Ee.current=ea.state,B(ea.state),be(Fe.timing,{rows:He.length,devices:a.length,limit:lt,paged:Dt!==null,delta:!0,parseMs:Math.round(performance.now()-ot)}),K(null),ve=ea.gap,Dt=ea.deltaCursor,bt+=1}ve&&k.current("delta drain hit its page bound — newer rows may be missing",{since:ft,pages:bt,bound:BT})})().finally(()=>{Ie.current=!1,Me.current&&(Me.current=!1,Se.current())})},[fe,be,a,ie,c,ee,E,T,j]),Be=P.useCallback(()=>{de.current!==null&&(clearTimeout(de.current),de.current=null),Y.current=0},[]),Ge=P.useCallback(()=>{const ft=we.current+Math.max(1,m);we.current=ft,Ae(ft),Se.current()},[m]),Ft=P.useCallback(()=>{Be(),K(null),U(!1),Se.current()},[Be]),Ot=P.useRef(()=>{}),wt=P.useCallback(()=>{Be(),Re.current=Date.now(),Me.current=!1,Ee.current=Tu,B(Tu),U(!1),Q(!1),K(null),we.current=m,Ae(m),oe(ft=>ft+1)},[Be,m]),sa=P.useCallback(()=>{Be(),Re.current=Date.now(),Me.current=!1;const ft=qje(Ee.current);Ee.current=ft,B(ft),ft.rows.length===0&&U(!1),Q(!1),K(null),oe(lt=>lt+1)},[Be]),nt=`${ie}|${h}|${x??""}|${E??""}|${T?"1":"0"}|${j}`,za=P.useRef(nt);return P.useEffect(()=>{za.current!==nt&&(za.current=nt,!(Ee.current.rows.length===0&&!F)&&wt())},[nt,wt,F]),P.useEffect(()=>{if(a.length===0){R&&U(!0);return}ee()},[W,ie,R]),P.useEffect(()=>{if(d<=0||a.length===0||!Qje(E,Date.now()))return;const ft=setInterval(()=>{_e()},d);return()=>clearInterval(ft)},[d,_e,a.length,E]),Ot.current=Ft,P.useEffect(()=>Be,[Be]),{rows:q.rows,retry:Ft,loading:!F,loadingMore:H&&F,error:te,hasMore:_T(q,he),tail:g7(q,he),loadMore:ee,loadOlder:Ge,refresh:_e,reload:sa}}const zze=3,qze=250;function Lze(e){const{urls:t,token:a,paused:r,enabled:c}=e,m=P.useRef(0),d=P.useRef(0),h=P.useRef(!1),f=P.useRef(t),k=P.useRef(t[0]??"");f.current=t;const x=t[0]??"";k.current!==x&&(k.current=x,m.current=0),P.useEffect(()=>{if(h.current=!1,!c||r)return;let E=!1;const R=()=>{if(!(E||h.current))for(;d.current<zze;){const T=f.current,N=m.current;if(N>=T.length)return;m.current=N+1;const j=T[N];j===void 0||j.length===0||(d.current+=1,Sje(j,a).finally(()=>{d.current=Math.max(0,d.current-1),R()}))}};return R(),()=>{E=!0,h.current=!0}},[c,r,a,t.length])}const Bze=.5,k7=56,Fze=88;function $ze(e){return e<=0?0:Math.min(e*Bze,Fze)}function FT(e){return e>=k7}function Uze(e,t,a){return e==="gallery"&&!t&&!a}function Hze(e){const{root:t,onRefresh:a,enabled:r}=e,[c,m]=P.useState(0),d=P.useRef(null),h=P.useRef(0);h.current=c;const f=P.useRef(a);f.current=a;const k=P.useCallback(()=>{d.current=null,m(0)},[]);return P.useEffect(()=>{if(!r||t===null)return;const x=N=>{if(t.scrollTop>0){d.current=null;return}const j=N.touches[0];d.current=j!==void 0?j.clientY:null},E=N=>{const j=d.current;if(j===null)return;const q=N.touches[0];if(q!==void 0){if(t.scrollTop>0){d.current=null,m(0);return}m($ze(q.clientY-j))}},R=()=>{if(d.current===null)return;const N=h.current;k(),FT(N)&&f.current()},T={passive:!0};return t.addEventListener("touchstart",x,T),t.addEventListener("touchmove",E,T),t.addEventListener("touchend",R,T),t.addEventListener("touchcancel",k,T),()=>{t.removeEventListener("touchstart",x),t.removeEventListener("touchmove",E),t.removeEventListener("touchend",R),t.removeEventListener("touchcancel",k)}},[t,r,k]),{distance:c,armed:FT(c)}}const ok=8,$h=3,$T=10,UT=4,Qze=400;function Vze(e){return Math.max(Qze,Math.round(e))}function S7(e,t){return{display:"flex",alignItems:"center",justifyContent:"center",padding:e?"0 12px":"10px 0",width:e?"max-content":"100%",height:e?t:void 0,...e?{gridColumn:"auto"}:{},whiteSpace:"nowrap"}}function HT(e,t,a){return{...S7(e,t),font:"inherit",fontSize:12,color:a.text,background:a.card,border:`1px solid ${a.border}`,borderRadius:8,cursor:"pointer"}}const Kze=8;function QT({message:e,palette:t}){return P.useEffect(()=>{Ei(H5e(e)),Ei(Sf("error",e))},[e]),v.jsxs("div",{style:{position:"fixed",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:t.background,color:"var(--color-danger)",fontFamily:"system-ui, sans-serif",fontSize:13,padding:16,textAlign:"center"},children:["Events embed config error: ",e]})}function Gze({client:e,initialConfig:t}){const[a,r]=P.useState(t),[c,m]=P.useState({}),[d,h]=P.useState(()=>window.matchMedia?.("(prefers-color-scheme: dark)").matches??!0),[f,k]=P.useState(()=>Date.now()),[x,E]=P.useState(null);P.useEffect(()=>{let xe=!1;return e.listDevices().then(Oe=>{xe||E(Oe)}).catch(()=>{xe||E([])}),()=>{xe=!0}},[e]);const R=P.useMemo(()=>{const xe=new Map;for(const Oe of x??[])xe.set(Oe.id,z5e(Oe.id,Oe.name??`Camera ${Oe.id}`,a.deviceNames));for(const[Oe,xt]of Object.entries(a.deviceNames)){const ha=Number(Oe);Number.isInteger(ha)&&!xe.has(ha)&&xt.trim().length>0&&xe.set(ha,xt)}return xe},[x,a.deviceNames]),[T,N]=P.useState(()=>new Map),[j,q]=P.useState(()=>new Map),B=P.useMemo(()=>H8(a.kindLabels),[a.kindLabels]),F=Bx(a.locale,typeof navigator>"u"?void 0:navigator.language),U=P.useMemo(()=>B8(a.labels,F),[a.labels,F]),H=P.useMemo(()=>a.deviceIds.length>0?a.deviceIds:x===null?[]:ZDe(x),[a.deviceIds,x]);P.useEffect(()=>{if(H.length===0)return;let xe=!1;return e.listEventKinds([...H]).then(Oe=>{xe||(N(kDe(Oe)),q(wDe(Oe)))}).catch(()=>{qc("event-kind taxonomy unavailable — class filter is exact-id only")}),()=>{xe=!0}},[e,H]);const Q=jze({client:e,log:qc,deviceIds:H,nameById:R,pageSize:a.pageSize,maxRows:T5e(a),refreshMs:a.refreshMs,maxAgeMs:a.maxAgeMs,channel:wze(a.serverUrl),devicesResolved:a.deviceIds.length>0||x!==null,...a.showStationary?{includeStationary:!0}:{},excludeSources:a.excludeSources,...a.sinceMs!==void 0?{sinceMs:a.sinceMs}:{},...a.untilMs!==void 0?{untilMs:a.untilMs}:{}}),te=a.searchMode==="semantic"?a.search.trim():"",[K,W]=P.useState({query:"",rows:[],loading:!1});P.useEffect(()=>{if(te.length===0||H.length===0){W({query:"",rows:[],loading:!1});return}let xe=!1;return W(Oe=>({...Oe,query:te,loading:!0})),e.searchObjectEvents(Gje(te,H,{semanticLimit:a.semanticLimit,semanticMinScore:a.semanticMinScore,sinceMs:a.sinceMs,untilMs:a.untilMs})).then(Oe=>{xe||W({query:te,rows:Zje(Oe,R),loading:!1})}).catch(Oe=>{xe||(qc("searchObjectEvents failed",{error:Oe instanceof Error?Oe.message:String(Oe)}),W({query:te,rows:[],loading:!1}))}),()=>{xe=!0}},[e,te,H,R,a.semanticLimit,a.semanticMinScore,a.sinceMs,a.untilMs]);const oe=te.length>0,he=P.useMemo(()=>new Set(a.reviewedTrackIds),[a.reviewedTrackIds]),Ae=xe=>he.size===0?[...xe]:xe.map(Oe=>he.has(Oe.trackId)?{...Oe,reviewed:!0}:Oe),we=P.useMemo(()=>Ae(vT(gT(Q.rows,R),c)),[Q.rows,R,he,c]),Ee=P.useMemo(()=>Ae(vT(gT(K.rows,R),c)),[K.rows,R,he,c]),Ie=P.useMemo(()=>{const xe={debug:a.filterDebug,train:a.filterTrain,favourited:a.filterFavourited,reviewedTrackIds:a.reviewedTrackIds},Oe=fT(we,a.classes,a.search,T,a.attrs,xe,a.excludeSources);if(oe){const xt=fT(Ee,a.classes,"",T,a.attrs,xe,a.excludeSources);return Yje(xt,Oe)}return Oe},[oe,Ee,we,a.classes,a.attrs,a.filterDebug,a.filterTrain,a.filterFavourited,a.reviewedTrackIds,a.search,a.excludeSources,T]),Me=Ox(a.theme,d),Y=F,de=P.useRef(null),[Re,Qe]=P.useState(null),re=P.useRef(null),V=P.useRef(Q.loadMore);V.current=Q.loadMore;const ie=P.useRef(Q.refresh);ie.current=Q.refresh;const fe=P.useRef(Q.reload);fe.current=Q.reload;const[be]=P.useState(()=>Nje(Ei)),ee=P.useCallback(xe=>{if(xe.type==="setConfig"){r(Oe=>dw(Oe,xe.patch));return}if(xe.type==="setWindow"){r(Oe=>dw(Oe,tje(xe)));return}if(xe.type==="setTrackFlagPatches"){m(xe.patches);return}if(xe.type==="setTrackListMode"){be.setMode(xe.mode);return}if(xe.type==="refresh"){ie.current().finally(()=>Ei(Z5e()));return}if(xe.type==="reload"){fe.current();return}if(xe.type==="loadMore"){V.current();return}if(xe.type==="ping"){Ei(G5e());return}de.current?.scrollTo({top:0,left:0,behavior:"smooth"})},[be]);P.useEffect(()=>(window.__camstackEvents={setConfig:xe=>{const Oe=Su({type:"setConfig",patch:xe});Oe!==null&&ee(Oe)},setWindow:xe=>{const Oe=Su({type:"setWindow",...xe});Oe!==null&&ee(Oe)},setTrackFlagPatches:xe=>{const Oe=Su({type:"setTrackFlagPatches",patches:xe});Oe!==null&&ee(Oe)},setTrackListMode:xe=>{const Oe=Su({type:"setTrackListMode",mode:xe});Oe!==null&&ee(Oe)},refresh:()=>ee({type:"refresh"}),reload:()=>ee({type:"reload"}),loadMore:()=>ee({type:"loadMore"}),scrollToTop:()=>ee({type:"scrollToTop"}),ping:()=>ee({type:"ping"})},Gm(xe=>{const Oe=Su(xe);Oe!==null&&ee(Oe)})),[ee]),P.useEffect(()=>{Ei(U5e(a.view))},[]),P.useEffect(()=>{Ei(oe?ST(K.rows.length,Ie.length,!1,"semantic"):ST(Q.rows.length,Ie.length,Q.hasMore,"feed"))},[Q.rows.length,Ie.length,Q.hasMore,oe,K.rows.length]),P.useEffect(()=>{be.report(Ie)},[be,Ie]),P.useEffect(()=>{if(Q.error!==null&&!oe){Ei(Sf("error",Q.error));return}if(oe?K.loading:Q.loading){Ei(Sf("loading"));return}Ei(Sf(Ie.length===0?"empty":"ready"))},[Q.loading,Q.error,Ie.length,oe,K.loading]),P.useEffect(()=>{const xe=window.matchMedia?.("(prefers-color-scheme: dark)");if(!xe)return;const Oe=xt=>h(xt.matches);return xe.addEventListener("change",Oe),()=>xe.removeEventListener("change",Oe)},[]),P.useEffect(()=>{document.documentElement.style.colorScheme=Me.colorScheme,document.body.style.background=Me.background},[Me]),P.useEffect(()=>{const xe="camstack-events-keyframes";if(document.getElementById(xe)!==null)return;const Oe=document.createElement("style");Oe.id=xe,Oe.textContent="@keyframes camstack-spin{to{transform:rotate(360deg)}}",document.head.appendChild(Oe)},[]),P.useEffect(()=>{const xe=setInterval(()=>k(Date.now()),6e4);return()=>clearInterval(xe)},[]);const[Se,_e]=P.useState(0);P.useEffect(()=>{const xe=Re;if(xe===null)return;const Oe=()=>{const ha=a.view==="reel"?xe.clientWidth:xe.clientHeight;_e(xn=>xn===ha?xn:ha)};if(Oe(),typeof ResizeObserver!="function")return;const xt=new ResizeObserver(Oe);return xt.observe(xe),()=>xt.disconnect()},[Re,a.view]);const Be=Q.rows.length,Ge=Be>0;P.useEffect(()=>{const xe=de.current,Oe=re.current;if(!xe||!Oe||oe||!Ge)return;const xt=Vze(a.view==="reel"?xe.clientWidth:xe.clientHeight),ha=new IntersectionObserver(xn=>{xn.some(Yn=>Yn.isIntersecting)&&V.current()},{root:xe,rootMargin:`${xt}px`});return ha.observe(Oe),()=>ha.disconnect()},[a.view,Q.hasMore,oe,Ge,Se]);const Ft=P.useRef(0),Ot=P.useRef(0);P.useEffect(()=>{if(oe||Q.loading||Q.loadingMore||!Q.hasMore)return;const xe=de.current;if(!xe||Be===0)return;const Oe=a.view==="reel";if((Oe?xe.clientWidth:xe.clientHeight)===0)return;if(Oe?xe.scrollWidth>xe.clientWidth+1:xe.scrollHeight>xe.clientHeight+1){Ft.current=0,Ot.current=Be;return}Be>Ot.current&&(Ft.current=0,Ot.current=Be),!(Ft.current>=Kze)&&(Ft.current+=1,V.current())},[Ie.length,Be,Q.loading,Q.loadingMore,Q.hasMore,oe,a.view]);const wt=Hze({root:Re,enabled:Uze(a.view,oe,a.nativePullToRefresh),onRefresh:()=>{ie.current()}}),sa=P.useRef(null);P.useEffect(()=>{const xe=Re;if(!a.nativePullToRefresh||xe===null){sa.current=null;return}const Oe=()=>{const xt=a.view==="gallery"&&!oe&&xe.scrollTop<=0;sa.current!==xt&&(sa.current=xt,Ei(W5e(xt)))};return Oe(),xe.addEventListener("scroll",Oe,{passive:!0}),()=>xe.removeEventListener("scroll",Oe)},[Re,a.nativePullToRefresh,a.view,oe]);const nt=a.view==="reel",[za,ft]=P.useState(!1),[lt,Dt]=P.useState({scrollLeft:0,scrollTop:0,viewportWidth:0,viewportHeight:0});P.useEffect(()=>{const xe=Re;if(xe===null)return;let Oe=null;const xt=()=>{Dt({scrollLeft:xe.scrollLeft,scrollTop:xe.scrollTop,viewportWidth:xe.clientWidth,viewportHeight:xe.clientHeight})},ha=()=>{xt(),ft(!0),Oe!==null&&clearTimeout(Oe),Oe=setTimeout(()=>ft(!1),qze)};return xt(),xe.addEventListener("scroll",ha,{passive:!0}),window.addEventListener("resize",xt),()=>{xe.removeEventListener("scroll",ha),window.removeEventListener("resize",xt),Oe!==null&&clearTimeout(Oe)}},[Re]);const bt=P.useMemo(()=>S5e({viewportWidth:lt.viewportWidth,viewportHeight:lt.viewportHeight,rows:a.rows,presetEdge:cw(a.thumbSize),gap:ok,padX:$T}),[lt.viewportWidth,lt.viewportHeight,a.rows,a.thumbSize]),ve=nt?bt.edge:cw(a.thumbSize),Fe=nt?bt.cardHeight:j5e(a.thumbSize),Le=N5e(ve,window.devicePixelRatio||1),ot=P.useMemo(()=>eze({viewportWidth:lt.viewportWidth-2*UT,cardWidth:ve,gap:$h,columns:a.columns}),[lt.viewportWidth,ve,a.columns]),He=P.useMemo(()=>d5e(a.fields,{tileLabelMode:a.tileLabelMode,tileDetailCamera:a.tileDetailCamera,tileDetailZone:a.tileDetailZone}),[a.fields,a.tileLabelMode,a.tileDetailCamera,a.tileDetailZone]),ea=nt?0:Math.ceil(Ie.length/ot.columns),$t=lze({rowCount:ea,scrollTop:lt.scrollTop,viewportHeight:lt.viewportHeight,fallbackRowPx:ot.rowStridePx,geometryKey:`${ot.columns}|${ve}|${a.fields.sublabel?"s":""}${He.tileDetailCamera?"c":""}${He.tileDetailZone?"z":""}`}),ze=P.useMemo(()=>nt?Xje(Ie,{scrollLeft:lt.scrollLeft,viewportWidth:lt.viewportWidth,cardWidth:ve,gap:ok,rowsPerColumn:a.rows}):sze(Ie,$t.window,ot.columns),[nt,Ie,lt.scrollLeft,lt.viewportWidth,ve,a.rows,$t.window,ot.columns]),st=P.useMemo(()=>ze.map(xe=>Nx(a.serverUrl,xe.trackId,Le)),[ze,a.serverUrl,Le]);Lze({urls:st,token:a.token,paused:za,enabled:!Q.loading&&Ie.length>0});const Lt=P.useCallback(xe=>{Ei(Q5e({trackId:xe.trackId,deviceId:xe.deviceId,bestEventId:xe.bestEventId,className:xe.className,firstSeen:xe.firstSeen,lastSeen:xe.lastSeen}))},[]),Kt=nt?{display:"grid",gridTemplateRows:`repeat(${a.rows}, ${Fe}px)`,gridAutoFlow:"column",gridAutoColumns:`${ve}px`,gap:ok,alignContent:"start"}:{display:"grid",gridTemplateColumns:`repeat(${ot.columns}, minmax(0, 1fr))`,columnGap:$h,rowGap:$h,paddingBottom:$h,alignContent:"start"},qa=oe?K.loading:Q.loading,fn=!oe&&Q.loadingMore&&Be>0,ct=!oe&&Q.error!==null,Ut=!oe&&!Q.loadingMore&&Be>0,La=Ut&&ct,Sa=Ut&&!ct&&Q.tail==="exhausted",Di=Ut&&!ct&&Q.tail==="ceiling",Zn=ct&&Ie.length===0,ji=!qa&&!ct&&!Q.loadingMore&&Ie.length===0,gn=ji&&Be>0,Pn=(xe,Oe)=>v.jsx(Cje,{row:xe,eagerImages:!nt&&Oe<8,serverUrl:a.serverUrl,token:a.token,thumbPx:Le,width:nt?`${ve}px`:"100%",heroPx:nt?ve:ot.columnWidth,variant:nt?"reel":"gallery",iconId:U8(xe.className,j,ig(xe)),kindLabels:B,labels:U,scrollRoot:Re,fields:a.fields,display:He,showAdminFlags:a.showAdminFlags===!0,palette:Me,nowMs:f,locale:Y,onClick:Lt},xe.trackId),vn=v.jsxs(v.Fragment,{children:[fn&&v.jsx("div",{"data-testid":"tail-loading","aria-label":U.loadingMore,style:{width:nt?ve:"100%",height:nt?Fe:void 0,aspectRatio:nt?void 0:"1 / 1",borderRadius:10,background:Me.skeleton,border:`1px solid ${Me.border}`,boxSizing:"border-box",opacity:.6,display:"flex",alignItems:"center",justifyContent:"center"},children:v.jsx("span",{style:{width:14,height:14,borderRadius:999,border:`2px solid ${Me.chip}`,borderTopColor:Me.textMuted,animation:"camstack-spin 700ms linear infinite"}})}),Sa&&v.jsx("div",{"data-testid":"tail-end",style:{...S7(nt,ve),color:Me.textMuted,fontSize:11,opacity:.75},children:mc(a,"end")}),Di&&v.jsx("button",{type:"button","data-testid":"tail-more",onClick:()=>Q.loadOlder(),style:HT(nt,ve,Me),children:mc(a,"loadOlder")}),La&&v.jsx("button",{type:"button","data-testid":"tail-error",onClick:()=>Q.retry(),style:{...HT(nt,ve,Me),color:"var(--color-danger)"},children:mc(a,"retry")}),v.jsx("div",{ref:re,style:{width:1,height:1,gridRow:nt?1:"auto"},"aria-hidden":!0})]});return v.jsxs("div",{ref:xe=>{de.current=xe,Qe(Oe=>Oe===xe?Oe:xe)},"data-testid":"events-scroller",className:nt?"events-reel-scroller":void 0,style:{position:"fixed",inset:0,background:Me.background,color:Me.text,fontFamily:"system-ui, -apple-system, sans-serif",overflowX:nt?"auto":"hidden",overflowY:nt?"hidden":"auto",padding:nt?`${J8}px ${$T}px`:UT,boxSizing:"border-box",WebkitOverflowScrolling:"touch"},children:[wt.distance>0&&v.jsx("div",{"data-testid":"pull-indicator","data-armed":wt.armed?"true":"false","aria-hidden":!0,style:{position:"absolute",top:Math.max(0,wt.distance-28),left:0,right:0,display:"flex",justifyContent:"center",pointerEvents:"none",zIndex:2,opacity:Math.min(1,wt.distance/k7)},children:v.jsx("span",{style:{width:22,height:22,borderRadius:999,border:`2px solid ${Me.chip}`,borderTopColor:Me.textMuted,background:Me.card,boxShadow:"0 1px 4px rgba(0,0,0,0.25)",transform:`rotate(${wt.distance*4}deg)`,animation:Q.loadingMore?"camstack-spin 700ms linear infinite":void 0}})}),Zn&&v.jsxs("div",{"data-testid":"state-error",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",color:"var(--color-danger)",fontSize:13,padding:16,textAlign:"center"},children:[v.jsx("span",{children:mc(a,"error")}),v.jsx("button",{type:"button","data-testid":"state-retry",onClick:()=>Q.retry(),style:{marginTop:10,font:"inherit",fontSize:12,color:Me.text,background:Me.card,border:`1px solid ${Me.border}`,borderRadius:8,padding:"5px 14px",cursor:"pointer"},children:mc(a,"retry")})]}),ji&&v.jsx("div",{"data-testid":gn?"state-empty-filtered":"state-empty",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:Me.textMuted,fontSize:13,padding:"0 24px",textAlign:"center"},children:mc(a,gn?"emptyFiltered":"empty")}),qa&&Ie.length===0&&v.jsx("div",{"data-testid":"state-loading",style:Kt,children:Array.from({length:nt?8:12},(xe,Oe)=>v.jsx("div",{style:{width:nt?ve:"100%",height:nt?Fe:void 0,aspectRatio:nt?void 0:"1 / 1",borderRadius:10,background:Me.skeleton,border:`1px solid ${Me.border}`,boxSizing:"border-box",opacity:.6}},`skeleton-${Oe}`))}),nt?v.jsxs("div",{style:Kt,children:[Ie.map(Pn),vn]}):v.jsxs("div",{"data-testid":"events-gallery",children:[v.jsx("div",{"data-testid":"gallery-pad-top",style:{height:$t.window.padTopPx},"aria-hidden":!0}),Array.from({length:$t.window.endRow-$t.window.startRow},(xe,Oe)=>{const xt=$t.window.startRow+Oe,ha=xt*ot.columns;return v.jsx("div",{"data-row-index":xt,ref:$t.measureRow(xt),style:Kt,children:Ie.slice(ha,ha+ot.columns).map((xn,Yn)=>Pn(xn,ha+Yn))},xt)}),v.jsx("div",{"data-testid":"gallery-pad-bottom",style:{height:$t.window.padBottomPx},"aria-hidden":!0}),vn]})]})}function Wze(){const e=Wm("events",()=>window.__CAMSTACK_EVENTS__,Fx,y7,{urlFirst:!0}),t=P.useMemo(()=>bze(),[]),a=P.useMemo(()=>e===null?null:kze(e,t),[e,t]),r=P.useMemo(()=>{if(a===null||!a.ok)return null;const m=xm({serverUrl:a.config.serverUrl,token:a.config.token});return{system:m,client:Ije(m)}},[a]);P.useEffect(()=>{if(r)return()=>r.system.close()},[r]);const c=Ox(a!==null&&a.ok?a.config.theme:"auto",window.matchMedia?.("(prefers-color-scheme: dark)").matches??!0);return a===null?null:a.ok?r?v.jsxs(v.Fragment,{children:[v.jsx(Wg,{system:r.system}),v.jsx(Gze,{client:r.client,initialConfig:a.config})]}):v.jsx(QT,{message:"Failed to initialise the events embed",palette:c}):v.jsx(QT,{message:a.error,palette:c})}const og={play:"Play",pause:"Pause",listen:"Listen",mute:"Mute",talk:"Talk",stopTalk:"Stop talk",ptz:"PTZ",linkedDevices:"Linked devices",viewOptions:"View options",moreActions:"More actions",open:"Open",removeFromView:"Remove from view",resizeWidth:"Resize width",resizeHeight:"Resize height",noActiveCameras:"No active cameras",camera:"Camera"},Zze=Object.keys(og),Yze=$(n(),n()).optional();function Xze(e){if(e===null||typeof e!="object")return og;const t=e,a={...og};for(const r of Zze){const c=t[r];typeof c=="string"&&c.trim()!==""&&(a[r]=c)}return a}const w7=I(["auto","high","mid","low"]).catch("auto"),Jze=qe([_("auto"),i().int().min(1)]),x7=o({enabled:w(),motion:w(),motionHoldSec:i().optional(),audio:I(["off","sensor","level"]),audioDb:i(),audioHoldSec:i(),detection:w(),detectionHoldSec:i(),detectionClasses:y(n()).optional(),appearance:o({motionColor:n(),audioColor:n(),detectionColor:n(),thickness:i()}).optional()}),xu=I(["off","top-left","top-center","top-right","left-center","right-center","bottom-left","bottom-center","bottom-right"]),eqe=o({motionBoxes:w().optional(),motionBadge:xu.optional(),audioMeter:xu.optional(),occupancy:xu.optional(),stats:w().optional(),statsAt:xu.exclude(["off"]).optional(),viewers:xu.optional(),size:I(["small","medium","large"]).optional()}),tqe=o({cw:i(),ch:i()}),aqe=o({serverUrl:n().min(1),token:n().min(1).optional(),devices:y(i().int().nonnegative()).min(1),layout:Jze,quality:w7,showName:w(),showBadges:w(),muted:w(),paused:w(),highlight:x7.optional(),activeOnly:w().optional(),showBoxes:w().optional(),audioOnIds:y(i().int().nonnegative()).optional(),pausedIds:y(i().int().nonnegative()).optional(),snapshots:$(n(),n()).optional(),ptzIds:y(i().int().nonnegative()).optional(),overlays:$(n(),eqe).optional(),editable:w().optional(),cellPanels:w().optional(),spans:$(n(),tqe).optional(),labels:Yze}).superRefine(e7);function M7(e){if(e==null)return{ok:!1,error:"config is required"};const t=aqe.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(a=>`${a.path.join(".")||"(root)"}: ${a.message}`).join("; ")}}const nqe=1,C7=I(["auto","high","mid","low"]),iqe=qe([_("auto"),i().int().min(1)]),A7=o({enabled:w(),motion:w(),audio:I(["off","sensor","level"]),audioDb:i(),audioHoldSec:i(),detection:w(),detectionHoldSec:i(),detectionClasses:y(n()).optional(),appearance:o({motionColor:n(),audioColor:n(),detectionColor:n(),thickness:i()}).optional()}),rqe=o({devices:y(i().int().nonnegative()).min(1),layout:iqe,quality:C7,showName:w(),audioOnIds:y(i().int().nonnegative()).optional(),activeOnly:w().optional(),boxes:w().optional(),highlight:A7.optional()}),oqe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function sqe(e){let t="",a=0;for(;a<e.length;){const r=e[a];if(r===void 0)return null;let c,m;if(r<128)c=r,m=0;else if((r&224)===192)c=r&31,m=1;else if((r&240)===224)c=r&15,m=2;else if((r&248)===240)c=r&7,m=3;else return null;for(let d=1;d<=m;d++){const h=e[a+d];if(h===void 0||(h&192)!==128)return null;c=c<<6|h&63}a+=m+1,t+=String.fromCodePoint(c)}return t}function lqe(e){if(e.length%4===1)return null;const t=[];for(const c of e){const m=oqe.indexOf(c);if(m<0)return null;t.push(m)}const a=[];for(let c=0;c<t.length;c+=4){const m=t[c],d=t[c+1];if(m===void 0||d===void 0)return null;const h=t[c+2],f=t[c+3];a.push(m<<2|d>>4),h!==void 0&&a.push((d&15)<<4|h>>2),f!==void 0&&h!==void 0&&a.push((h&3)<<6|f)}const r=sqe(a);if(r===null)return null;try{return JSON.parse(r)}catch{return null}}function $x(e,t){return e.startsWith(t)?e.slice(t.length):e}function I7(e){const a=new URLSearchParams($x(e,"#")).get("t");return a!==null&&a.length>0?a:null}function cqe(e,t){return new URLSearchParams($x(e,"?")).has("v")||I7(t)!==null}function VT(e){if(e.length===0)return null;const t=[];for(const a of e.split(",")){if(!/^\d+$/.test(a))return null;t.push(Number(a))}return t}function Xi(e){return{ok:!1,error:e}}function dqe(e,t){const a=new URLSearchParams($x(e,"?")),r=a.get("mode");if(r!==null&&r!=="grid")return Xi(`unsupported mode "${r}"`);const c=a.get("v");if(c===null)return Xi("missing share-link version (v)");if(c!==String(nqe))return Xi(`unsupported share-link version "${c}"`);const m=a.get("devices"),d=m===null?null:VT(m);if(d===null||d.length===0)return Xi("invalid or missing devices list");const h=a.get("layout");let f;if(h===null||h==="auto")f="auto";else if(/^\d+$/.test(h)&&Number(h)>=1)f=Number(h);else return Xi(`invalid layout "${h}"`);const k=a.get("q")??"auto",x=C7.safeParse(k),E=x.success?x.data:"auto",R=a.get("names")??"0";if(R!=="0"&&R!=="1")return Xi(`invalid names flag "${R}"`);const T=a.get("audio");let N;if(T!==null){const K=VT(T);if(K===null)return Xi(`invalid audio list "${T}"`);N=K}const j=a.get("activeOnly");if(j!==null&&j!=="0"&&j!=="1")return Xi(`invalid activeOnly flag "${j}"`);const q=j==="1",B=a.get("boxes");if(B!==null&&B!=="0"&&B!=="1")return Xi(`invalid boxes flag "${B}"`);const F=B==="1",U=a.get("hl");let H;if(U!==null){const K=lqe(U),W=A7.safeParse(K);if(K===null||!W.success)return Xi("invalid highlight config (hl)");H=W.data}const Q={devices:[...d],layout:f,quality:E,showName:R==="1",...N!==void 0&&N.length>0?{audioOnIds:[...N]}:{},...q?{activeOnly:!0}:{},...F?{boxes:!0}:{},...H!==void 0?{highlight:H}:{}},te=rqe.safeParse(Q);return te.success?{ok:!0,params:te.data,token:I7(t)}:Xi(te.error.issues.map(K=>`${K.path.join(".")||"(root)"}: ${K.message}`).join("; "))}function uqe(e,t,a){if(!cqe(e,t))return null;const r=dqe(e,t);if(!r.ok)return{ok:!1,error:r.error};if(r.token===null)return{ok:!1,error:"share token missing — the link must end with #t=<token>"};const c=r.params,m={serverUrl:a,token:r.token,devices:[...c.devices],layout:c.layout,quality:c.quality,showName:c.showName,showBadges:!0,muted:!0,paused:!1,...c.highlight!==void 0?{highlight:c.highlight}:{},...c.activeOnly===!0?{activeOnly:!0}:{},...c.boxes===!0?{showBoxes:!0}:{},...c.audioOnIds!==void 0&&c.audioOnIds.length>0?{audioOnIds:[...c.audioOnIds]}:{}};return M7(m)}function mqe(){const e=uqe(location.search,location.hash,location.origin);return e!==null&&location.hash!==""&&history.replaceState(null,"",location.pathname+location.search),e}const sg=16/9,KT={cols:0,rows:0,cellW:0,cellH:0,wallW:0,wallH:0};function GT(e,t,a,r,c){const m=Math.min(r/e,c/t*sg),d=m/sg;return{cols:e,rows:t,cellW:m,cellH:d,wallW:Math.min(e,a)*m,wallH:t*d,empty:e*t-a}}function WT(e){return{cols:e.cols,rows:e.rows,cellW:e.cellW,cellH:e.cellH,wallW:e.wallW,wallH:e.wallH}}const ZT=1e-9;function pqe(e,t){const a=e.cellW*e.cellH,r=t.cellW*t.cellH,c=Math.max(a,r,1);return a-r>c*ZT?!0:r-a>c*ZT?!1:e.empty!==t.empty?e.empty<t.empty:e.rows<t.rows}function hqe(e,t,a,r){if(e<=0||t<=0||a<=0)return KT;if(typeof r=="number"&&r>=1){const m=Math.floor(r);return WT(GT(m,Math.ceil(e/m),e,t,a))}let c=null;for(let m=1;m<=e;m++){const d=Math.ceil(e/m);if(Math.ceil(e/d)!==m)continue;const h=GT(d,m,e,t,a);(c===null||pqe(h,c))&&(c=h)}return c===null?KT:WT(c)}function fqe(e,t){if(e.length===0)return[];const a=t>=1?Math.floor(t):e.length,r=[];for(let c=0;c<e.length;c+=a)r.push(e.slice(c,c+a));return r}function gqe(e,t){if(e.length===0||t.cellW<=0||t.cellH<=0)return[];const a=[];return fqe(e,t.cols).forEach((c,m)=>{const d=(t.wallW-c.length*t.cellW)/2;c.forEach((h,f)=>{a.push({deviceId:h,x:d+f*t.cellW,y:m*t.cellH,w:t.cellW,h:t.cellH})})}),a}const YT={wallW:0,wallH:0,placements:[]};function vqe(e,t){const a=e!==void 0&&Number.isFinite(e.cw)?Math.round(e.cw):1,r=e!==void 0&&Number.isFinite(e.ch)?Math.round(e.ch):1;return{cw:Math.min(Math.max(a,1),Math.max(t,1)),ch:Math.max(r,1)}}function yqe(e){if(e===void 0)return!1;for(const t of Object.keys(e)){const a=e[t];if(a!==void 0&&(a.cw!==1||a.ch!==1))return!0}return!1}function bqe(e,t,a){const r=new Set,c=[];let m=0;const d=(h,f,k,x)=>{for(let E=h;E<h+x;E++)for(let R=f;R<f+k;R++)if(r.has(`${E}:${R}`))return!1;return!0};for(const h of e){const{cw:f,ch:k}=vqe(t[String(h)],a),x=m+k+e.length;let E=!1;for(let R=0;R<=x&&!E;R++)for(let T=0;T+f<=a;T++)if(d(R,T,f,k)){for(let N=R;N<R+k;N++)for(let j=T;j<T+f;j++)r.add(`${N}:${j}`);c.push({deviceId:h,col:T,row:R,cw:f,ch:k}),m=Math.max(m,R+k),E=!0;break}}return{cells:c,rows:m,cols:a}}function kqe(e,t,a,r,c){const m=hqe(e.length,t,a,r);if(!yqe(c)||m.cols<=0)return{wallW:m.wallW,wallH:m.wallH,placements:gqe(e,m)};if(e.length===0||t<=0||a<=0)return YT;const d=bqe(e,c??{},m.cols);if(d.rows<=0)return YT;const h=Math.min(t/d.cols,a/d.rows*sg),f=h/sg;return{wallW:d.cells.reduce((x,E)=>Math.max(x,E.col+E.cw),0)*h,wallH:d.rows*f,placements:d.cells.map(x=>({deviceId:x.deviceId,x:x.col*h,y:x.row*f,w:x.cw*h,h:x.ch*f}))}}function E7(){const[e,t]=P.useState(null),[a,r]=P.useState("idle"),c=P.useRef(null),m=P.useRef(null),d=P.useRef(null),h=P.useRef(0),f=P.useRef(null),k=XEe(),x=JEe(),E=eRe(),R=P.useRef({start:k.mutateAsync,answer:x.mutateAsync,stop:E.mutateAsync});R.current={start:k.mutateAsync,answer:x.mutateAsync,stop:E.mutateAsync};const T=P.useCallback(()=>{if(c.current){try{c.current.close()}catch{}c.current=null}if(m.current){for(const B of m.current.getTracks())try{B.stop()}catch{}m.current=null}},[]),N=P.useCallback(async()=>{const B=d.current;if(d.current=null,T(),B)try{await R.current.stop({deviceId:B.deviceId,sessionId:B.sessionId})}catch{}},[T]),j=P.useCallback(async B=>{if(f.current===B){h.current+=1,f.current=null,t(null),r("idle"),await N();return}h.current+=1;const F=h.current;f.current=B,t(B),r("starting");let U;try{U=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}catch{F===h.current&&(f.current=null,t(null),r("error"));return}if(F!==h.current){for(const Q of U.getTracks())Q.stop();return}if(await N(),F!==h.current){for(const Q of U.getTracks())Q.stop();return}let H=null;try{m.current=U;const Q=await R.current.start({deviceId:B});if(F!==h.current){try{await R.current.stop({deviceId:B,sessionId:Q.sessionId})}catch{}T();return}d.current={deviceId:B,sessionId:Q.sessionId},H=new RTCPeerConnection,c.current=H,H.oniceconnectionstatechange=()=>{if(F!==h.current||!H)return;const K=H.iceConnectionState;K==="connected"||K==="completed"?r("talking"):(K==="failed"||K==="closed"||K==="disconnected")&&(f.current=null,t(null),r("idle"),N())};for(const K of U.getAudioTracks())H.addTrack(K,U);await H.setRemoteDescription({type:"offer",sdp:Q.sdpOffer});const te=await H.createAnswer();if(await H.setLocalDescription(te),F!==h.current)return;await R.current.answer({deviceId:B,sessionId:Q.sessionId,sdpAnswer:H.localDescription?.sdp??te.sdp??""})}catch{if(H)try{H.close()}catch{}T();const Q=d.current;if(d.current=null,Q)try{await R.current.stop({deviceId:Q.deviceId,sessionId:Q.sessionId})}catch{}F===h.current&&(f.current=null,t(null),r("error"))}},[N,T]),q=P.useCallback(B=>{if(B===null){h.current+=1,f.current=null,t(null),r("idle"),N();return}f.current!==B&&j(B)},[N,j]);return P.useEffect(()=>()=>{h.current+=1,N()},[N]),{activeMicId:e,micState:a,toggleMic:B=>{j(B)},setActiveMic:q}}const Sqe=6e3,wqe=500;function xqe(e,t){const a=P.useRef(new Map),[,r]=P.useState(0),c=t?.motion??!1,m=t?.audio??"off",d=t?.audioDb??-30,h=t?.audioHoldSec??5,f=t?.detection??!1,k=t?.detectionHoldSec??3,x=t?.detectionClasses??[],E=(N,j)=>{a.current.set(N,Date.now()+j),r(q=>q+1)};kr(Ke.MotionOnMotionChanged,N=>{if(!c)return;const j=N.data;j&&j.detected&&E(j.deviceId,Sqe)}),kr(Ke.PipelineAudioInferenceResult,N=>{if(m==="off")return;const j=N.data;if(!j)return;(m==="sensor"?j.frame.detections.length>0:(j.frame.level?.dbfs??Number.NEGATIVE_INFINITY)>=d)&&E(j.deviceId,h*1e3)}),kr(Ke.DetectionResult,N=>{if(!f)return;const j=N.data;if(!j)return;j.frame.detections.some(B=>x.length===0||x.includes(B.macroClass))&&E(j.frame.deviceId,k*1e3)}),P.useEffect(()=>{const N=setInterval(()=>r(j=>j+1),wqe);return()=>clearInterval(N)},[]);const R=Date.now(),T=new Set;for(const N of e){const j=a.current.get(N);j!==void 0&&R<j&&T.add(N)}return T}function Mqe(e){return{type:"tileOpen",deviceId:e}}function Cqe(e){return{type:"audioToggle",deviceId:e}}function Aqe(e){return{type:"pauseToggle",deviceId:e}}function Iqe(e){return{type:"ptzOpen",deviceId:e}}function Eqe(e,t){return{type:"cellPanelOpen",deviceId:e,panel:t}}function Rqe(e){return{type:"tileRemove",deviceId:e}}function Tqe(e,t,a){return{type:"tileResize",deviceId:e,cw:t,ch:a}}function R7(e,t,a){return{type:"state",state:e,...t!==void 0?{message:t}:{},...a!==void 0?{commands:a}:{}}}function _qe(e){return{type:"layout",tiles:e}}function vr(e){qt(e)}const Pqe=["top-left","top-center","top-right","left-center","right-center","bottom-left","bottom-center","bottom-right"];function sk(e){return typeof e=="string"&&Pqe.includes(e)}const Nqe={"top-left":{top:8,left:8},"top-center":{top:8,left:0,right:0,justifyContent:"center"},"top-right":{top:8,right:8},"left-center":{left:8,top:0,bottom:0,alignItems:"center"},"right-center":{right:8,top:0,bottom:0,alignItems:"center"},"bottom-left":{bottom:8,left:8},"bottom-center":{bottom:8,left:0,right:0,justifyContent:"center"},"bottom-right":{bottom:8,right:8}};function Zg(e){return{position:"absolute",display:"flex",...Nqe[e]}}const T7=[-60,-53,-46,-39,-32,-24],Oqe=T7.length,lk=["#22c55e","#84cc16","#eab308","#f59e0b","#f97316","#ef4444"];function Dqe(e){const t=Math.min(Math.max(0,e),lk.length-1);return lk[t]??lk[0]}function jqe(e){if(e===null||!Number.isFinite(e))return 0;let t=0;for(const a of T7)e>=a&&(t+=1);return t}function zqe(e){if(e==="off")return null;const t=e.split("-"),a=t.includes("top")?"top":t.includes("bottom")?"bottom":"center",r=t.includes("left")?"left":t.includes("right")?"right":"center";return a!=="center"&&r!=="center"?"compact":r==="center"?"horizontal":"vertical"}const XT=[8,11,14,17,21,26],ck={horizontal:{width:8,height:16},vertical:{width:24,height:7},compactWidth:4};function qqe(e,t){if(e==="vertical")return ck.vertical;if(e==="horizontal")return ck.horizontal;const a=XT[t]??XT[0];return{width:ck.compactWidth,height:a}}function Lqe(e){const t=Array.from({length:Oqe},(a,r)=>r);return e==="vertical"?[...t].reverse():t}function al(e){return typeof e=="object"&&e!==null}function Bqe(e){if(!al(e))return[];if(e.detected!==!0)return[];const t=typeof e.frameWidth=="number"?e.frameWidth:0,a=typeof e.frameHeight=="number"?e.frameHeight:0;if(t<=0||a<=0)return[];const r=e.regions;if(!Array.isArray(r))return[];const c=[];for(const m of r){if(!al(m)||!al(m.bbox))continue;const{x:d,y:h,w:f,h:k}=m.bbox;typeof d!="number"||typeof h!="number"||typeof f!="number"||typeof k!="number"||!(f>0)||!(k>0)||c.push({x:d/t,y:h/a,w:f/t,h:k/a,pixelCount:typeof m.pixelCount=="number"?m.pixelCount:0})}return c}function Fqe(e){return!Number.isFinite(e)||e<=0?.08:Math.min(.28,.08+e/4e3*.28)}function JT(e){if(!al(e))return[];const t=al(e.frame)?e.frame.byClass:void 0,a=al(t)?t:e.byClass;if(!al(a))return[];const r=[];for(const[c,m]of Object.entries(a))typeof m!="number"||!Number.isFinite(m)||m<=0||r.push({className:c,count:Math.round(m)});return r.sort((c,m)=>m.count-c.count||c.className.localeCompare(m.className))}function $qe(e,t,a){if(a<=0)return 0;const r=t-e;return r<=0?0:Math.round(r*1e3/a)}function Uqe(e){if(e===null)return"—";const t=[e.resolution,`${e.fps}fps`];return e.dropped>0&&t.push(`${e.dropped} dropped`),t.join(" · ")}const Hqe="medium",Qqe=11,Vqe={small:.012,medium:.018,large:.028},Kqe={small:.5,medium:.6,large:.75},Gqe=2;function Wqe(e,t){if(!Number.isFinite(e)||e<=0)return 1;const a=e*Vqe[t]/Qqe;return Math.min(Gqe,Math.max(Kqe[t],a))}const _7="--ov";function ba(e){return`calc(${e}px * var(${_7}, 1))`}function Zqe(e){return{[_7]:e}}const Yqe=1e4;function Xqe(e){return typeof e=="object"&&e!==null}function Jqe(e){if(!Array.isArray(e))return null;const t={};for(const a of e){if(!Xqe(a))continue;const{deviceId:r,viewers:c}=a;typeof r!="number"||!Number.isInteger(r)||r<0||typeof c!="number"||!Number.isFinite(c)||c<1||(t[r]=Math.floor(c))}return t}function e6e(e,t){return e===null?null:e[t]??0}async function t6e(e){if(typeof e!="object"||e===null)return null;const t=Reflect.get(e,"streamBroker");if(typeof t!="object"||t===null)return null;const a=Reflect.get(t,"getLiveViewerCounts");if(typeof a!="object"||a===null)return null;const r=Reflect.get(a,"query");if(typeof r!="function")return null;try{return Jqe(await r.call(a))}catch{return null}}class a6e{constructor(t){this.deps=t}deps;counts=null;listeners=new Set;timer=null;getSnapshot=()=>this.counts;subscribe=t=>(this.listeners.add(t),this.listeners.size===1&&this.start(),()=>{this.listeners.delete(t),this.listeners.size===0&&this.stop()});get isRunning(){return this.timer!==null}start(){this.tick(),this.timer=this.deps.setInterval(()=>{this.tick()},Yqe)}stop(){this.timer!==null&&this.deps.clearInterval(this.timer),this.timer=null,this.counts=null}async tick(){const t=await this.deps.fetchCounts();if(this.listeners.size!==0){this.counts=t;for(const a of this.listeners)a()}}}const n6e=1200,i6e=1e3;function r6e({deviceId:e}){const[t,a]=P.useState([]),r=P.useRef(void 0);return kr(Ke.MotionAnalysis,c=>{const m=c.data;!m||m.deviceId!==e||(a(Bqe(m)),r.current&&clearTimeout(r.current),r.current=setTimeout(()=>a([]),n6e))}),P.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[e]),t.length===0?null:v.jsx("div",{style:{position:"absolute",inset:0,overflow:"hidden",pointerEvents:"none"},children:t.map((c,m)=>v.jsx("div",{style:{position:"absolute",left:`${c.x*100}%`,top:`${c.y*100}%`,width:`${c.w*100}%`,height:`${c.h*100}%`,border:"1px dashed #f59e0b",borderRadius:2,background:`rgba(245,158,11,${Fqe(c.pixelCount)})`}},`${c.x}:${c.y}:${c.w}:${c.h}:${m}`))})}function o6e({deviceId:e,anchor:t}){const[a,r]=P.useState(null);kr(Ke.PipelineAudioInferenceResult,f=>{const k=f.data;!k||k.deviceId!==e||r(k.frame.level?.dbfs??null)});const c=jqe(a),m=zqe(t);if(m===null)return null;const d=m==="horizontal",h=m==="vertical";return v.jsx("div",{style:{...Zg(t),pointerEvents:"none"},children:v.jsx("span",{className:"cs-chip",style:{display:"flex",flexDirection:h?"column":"row",alignItems:h||d?"center":"flex-end",gap:ba(h||d?4:3),padding:d||h?`${ba(4)} ${ba(8)}`:`${ba(3)} ${ba(6)}`,borderRadius:ba(8)},children:Lqe(m).map(f=>{const k=f<c,x=qqe(m,f);return v.jsx("span",{style:{width:ba(x.width),height:ba(x.height),borderRadius:ba(2),background:k?Dqe(f):"#71717a",opacity:k?1:.35}},f)})})})}function s6e(e,t){if(typeof e!="object"||e===null)return null;const a=Reflect.get(e,"zoneAnalytics");if(typeof a!="object"||a===null)return null;const r=Reflect.get(a,"getCurrentSnapshot");if(typeof r!="object"||r===null)return null;const c=Reflect.get(r,"query");if(typeof c!="function")return null;const m=c.call(r,{deviceId:t});return m instanceof Promise?m:Promise.resolve(m)}function l6e({system:e,deviceId:t,anchor:a}){const[r,c]=P.useState([]);return P.useEffect(()=>{let m=!1;const d=s6e(e.trpcClient,t);if(d!==null)return d.then(h=>{m||c(JT(h))}).catch(()=>{m||c([])}),()=>{m=!0}},[e,t]),kr(Ke.ZoneAnalyticsOccupancyChanged,m=>{const d=m.data;d.deviceId===t&&c(JT(d))}),r.length===0?null:v.jsx("div",{style:{...Zg(a),gap:ba(4),pointerEvents:"none"},children:r.slice(0,4).map(m=>v.jsx("span",{className:"cs-chip",style:{padding:`${ba(2)} ${ba(6)}`,borderRadius:ba(6),fontSize:ba(11),fontWeight:700,fontFamily:"system-ui, sans-serif",whiteSpace:"nowrap"},children:`${m.className} ${m.count}`},m.className))})}const c6e="top-right";function d6e({containerRef:e,anchor:t}){const[a,r]=P.useState(null),c=P.useRef(null);return P.useEffect(()=>{const m=()=>{const h=e.current?.querySelector("video");if(!h){r(null);return}const f=typeof h.getVideoPlaybackQuality=="function"?h.getVideoPlaybackQuality():null,k=f?.totalVideoFrames??0,x=Date.now(),E=c.current;c.current={frames:k,at:x},r({resolution:h.videoWidth>0?`${h.videoWidth}x${h.videoHeight}`:"—",fps:E===null?0:$qe(E.frames,k,x-E.at),dropped:f?.droppedVideoFrames??0})};m();const d=setInterval(m,i6e);return()=>{clearInterval(d),c.current=null}},[e]),v.jsx("div",{style:{...Zg(t),pointerEvents:"none"},children:v.jsx("div",{className:"cs-chip",style:{maxWidth:"100%",padding:`${ba(2)} ${ba(6)}`,borderRadius:ba(6),fontSize:ba(10),fontWeight:600,fontFamily:"system-ui, sans-serif",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",pointerEvents:"none"},children:Uqe(a)})})}const e_=new WeakMap;function u6e(e){const t=e_.get(e);if(t)return t;const a=new a6e({fetchCounts:()=>t6e(e.trpcClient),setInterval:(r,c)=>setInterval(r,c),clearInterval:r=>{r!=null&&clearInterval(r)}});return e_.set(e,a),a}function m6e(e,t){const a=u6e(e),r=P.useSyncExternalStore(a.subscribe,a.getSnapshot);return e6e(r,t)}function p6e({system:e,deviceId:t,anchor:a}){const r=m6e(e,t);return r===null||r<1?null:v.jsx("div",{style:{...Zg(a),pointerEvents:"none"},"data-testid":"tile-viewers",children:v.jsxs("span",{role:"img","aria-label":`${r} watching live`,className:"cs-chip",style:{display:"flex",alignItems:"center",gap:ba(4),padding:`${ba(2)} ${ba(6)}`,borderRadius:ba(6),fontSize:ba(11),fontWeight:700,fontFamily:"system-ui, sans-serif",fontVariantNumeric:"tabular-nums",whiteSpace:"nowrap"},children:[v.jsxs("svg",{style:{width:ba(13),height:ba(13)},viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[v.jsx("path",{d:"M2.06 12.35a1 1 0 0 1 0-.7C3.4 8.4 7.3 5 12 5s8.6 3.4 9.94 6.65a1 1 0 0 1 0 .7C20.6 15.6 16.7 19 12 19s-8.6-3.4-9.94-6.65"}),v.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),r]})})}const h6e=1e4,t_=1e3,a_=[0,5e3,15e3,3e4],f6e=4;function g6e(e){const t=Math.max(0,Math.min(e,a_.length-1));return a_[t]??0}function v6e(e){return!e.playing||e.lastFrameAt===null?!1:e.nowMs-e.lastFrameAt>=e.stallMs}function P7(e){const{containerRef:t,playing:a,onRecover:r,stallMs:c=h6e}=e,m=e.now??Date.now,[d,h]=P.useState({recovering:!1,attempts:0}),f=P.useRef(null),k=P.useRef(0),x=P.useRef(0),E=P.useRef(r);E.current=r;const R=P.useRef(m);R.current=m;const T=P.useCallback(()=>{const N=R.current(),j=f.current;f.current=N,k.current>0&&j!==null&&N-j<c&&(k.current=0,h({recovering:!1,attempts:0}))},[c]);return P.useEffect(()=>{if(!a){f.current=null;return}const j=t.current?.querySelector("video");if(!j)return;let q=!1,B=null;if(typeof j.requestVideoFrameCallback=="function"){const H=()=>{q||(T(),B=j.requestVideoFrameCallback?.(H)??null)};return B=j.requestVideoFrameCallback(H),()=>{q=!0,B!==null&&j.cancelVideoFrameCallback?.(B)}}let F=j.currentTime;const U=setInterval(()=>{if(q)return;const H=j.currentTime;H!==F&&(F=H,T())},t_);return()=>{q=!0,clearInterval(U)}},[a,t,T]),P.useEffect(()=>{if(!a)return;const N=setInterval(()=>{const j=R.current();if(j<x.current||!v6e({lastFrameAt:f.current,nowMs:j,stallMs:c,playing:a})||k.current>=f6e)return;const q=k.current;k.current=q+1,f.current=j,x.current=j+g6e(q+1)+c,h({recovering:!0,attempts:q+1}),E.current()},t_);return()=>clearInterval(N)},[a,c]),d}const y6e=300,b6e=130,k6e=["devices","viewOptions"],S6e={inline:k6e,overflow:!1},w6e={inline:[],overflow:!0};function x6e(e,t){return e>=y6e&&t>=b6e?S6e:w6e}const M6e=120,C6e=68;function A6e(e,t,a){return e&&t>=M6e&&a>=C6e}const I6e=16/9,E6e={left:0,top:0,width:0,height:0},n_=.5;function R6e(e,t,a){if(!(e>0)||!(t>0))return E6e;const r={left:0,top:0,width:e,height:t};if(!Number.isFinite(a))return r;const c=Math.min(e,t*a),m=c/a;return e-c<n_&&t-m<n_?r:{left:(e-c)/2,top:(t-m)/2,width:c,height:m}}const T6e=500;function N7(e,t,a){const{motion:r,detection:c}=rDe(e.trpcClient,t),m=P.useRef(0),d=P.useRef(0),h=P.useRef(0),f=P.useRef(!1),[,k]=P.useState(0),x=a?.audio??"off",E=a?.audioDb??-30,R=a?.audioHoldSec??5,T=a?.motionHoldSec??0,N=a?.detectionHoldSec??3,j=a?.detectionClasses??[],q=j.join(",");kr(Ke.MotionOnMotionChanged,U=>{const H=U.data;!H||H.deviceId!==t||!a?.motion||(H.detected===!0?(h.current=Date.now()+Math.max(1,T)*1e3,f.current=!0,k(Q=>Q+1)):H.detected===!1&&f.current&&(h.current=Date.now()+T*1e3,f.current=!1,k(Q=>Q+1)))}),kr(Ke.PipelineAudioInferenceResult,U=>{const H=U.data;if(!H||H.deviceId!==t||x==="off")return;(x==="sensor"?H.frame.detections.length>0:(H.frame.level?.dbfs??Number.NEGATIVE_INFINITY)>=E)&&(m.current=Date.now()+R*1e3,k(te=>te+1))}),P.useEffect(()=>{if(!c)return;c.detections.some(H=>j.length===0||j.includes(H.macroClass))&&(d.current=Date.now()+N*1e3,k(H=>H+1))},[c,N,q]),P.useEffect(()=>{const U=r!==null;(U||f.current)&&(h.current=Date.now()+T*1e3,U||k(H=>H+1)),f.current=U},[r,T]);const B=a?.enabled===!0;if(P.useEffect(()=>{if(!B)return;const U=setInterval(()=>k(H=>H+1),T6e);return()=>clearInterval(U)},[B]),!a?.enabled)return null;const F=Date.now();return a.detection&&F<d.current?"detection":x!=="off"&&F<m.current?"audio":a.motion&&(r!==null||F<h.current)?"motion":null}function Lc(e,t){return ag(t,e)}const _6e=2500;function P6e(e,t=ng()){return ag(t,e)}function Uh(e){return e<0?0:e>1?1:e}function N6e(e){if(e.width<=0||e.height<=0)return[];const t=[];for(const a of e.detections){const{bbox:r}=a,c=Uh(r.x/e.width),m=Uh(r.y/e.height),d=Uh((r.x+r.width)/e.width),h=Uh((r.y+r.height)/e.height);d<=c||h<=m||t.push({label:a.macroClass,score:a.score,x1:c,y1:m,x2:d,y2:h})}return t}function O6e({deviceId:e}){const t=pd(),[a,r]=P.useState([]),c=P.useRef(void 0);return kr(Ke.DetectionResult,m=>{const d=m.data;!d||d.frame.deviceId!==e||(r(N6e(d.frame)),c.current&&clearTimeout(c.current),c.current=setTimeout(()=>r([]),_6e))}),P.useEffect(()=>()=>{c.current&&clearTimeout(c.current),r([])},[e]),a.length===0?null:v.jsx("div",{style:{position:"absolute",inset:0,overflow:"hidden",pointerEvents:"none"},children:a.map((m,d)=>{const h=P6e(m.label,t),f=Math.round(m.score*100);return v.jsx("div",{style:{position:"absolute",left:`${m.x1*100}%`,top:`${m.y1*100}%`,width:`${(m.x2-m.x1)*100}%`,height:`${(m.y2-m.y1)*100}%`,border:`2px solid ${h}`,borderRadius:3},children:v.jsx("span",{style:{position:"absolute",left:-2,bottom:"100%",background:h,color:Yt.dark.onPicture,fontSize:10,fontWeight:700,fontFamily:"system-ui, sans-serif",lineHeight:"14px",padding:"0 4px",borderRadius:3,whiteSpace:"nowrap"},children:`${m.label} ${f}%`})},`${m.label}-${d}`)})})}function D6e(e,t,a,r){const c=Number.isFinite(e)&&e>0?e:0,m=Number.isFinite(t)&&t>0?t:0;if(!Number.isFinite(a)||!Number.isFinite(r)||a<=0||r<=0)return{width:c,height:m};const d=Math.min(c/a,m/r);return{width:a*d,height:r*d}}function j6e(e,t,a){return!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(a)?0:Math.max(0,(a*t-e)/2)}function i_(e,t,a,r){if(!Number.isFinite(e))return 0;const c=j6e(t,a,r);return Math.max(-c,Math.min(c,e))}function z6e(e){"worklet";const{viewportWidth:t,viewportHeight:a,contentAspect:r}=e;if(!Number.isFinite(t)||!Number.isFinite(a)||!Number.isFinite(r)||t<=0||a<=0||r<=0)return 1;const c=t/a/r;return c>=1?c:1/c}const r_=.01;function q6e(e){"worklet";const{minScale:t,maxScale:a,cover:r,fallbackStep:c}=e;if((Number.isFinite(e.current)?e.current:t)>t+r_)return{kind:"fit"};const d=Number.isFinite(r)&&r>t+r_?r:c;return{kind:"zoom",scale:Math.max(t,Math.min(a,d))}}const o_=4,L6e=2,s_=8,B6e=300;function l_(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function c_(e){return e>1?"none":"pan-y"}function F6e({children:e,onTap:t}){const a=P.useRef(null),r=P.useRef(null),c=P.useRef(new Map),m=P.useRef(1),d=P.useRef(0),h=P.useRef(0),f=P.useRef(null),k=P.useRef(null),x=P.useRef(0),E=()=>{const U=r.current;U&&(U.style.transform=`translate(${d.current}px, ${h.current}px) scale(${m.current})`);const H=a.current;H&&(H.style.touchAction=c_(m.current))},R=()=>{const U=r.current?.querySelector("video")??null,H=U?null:r.current?.querySelector("img")??null;return{iw:U?.videoWidth??H?.naturalWidth??0,ih:U?.videoHeight??H?.naturalHeight??0}},T=()=>{const U=a.current?.getBoundingClientRect();if(!U||U.width<=0||U.height<=0)return;const{iw:H,ih:Q}=R(),te=D6e(U.width,U.height,H,Q);d.current=i_(d.current,U.width,te.width,m.current),h.current=i_(h.current,U.height,te.height,m.current)},N=()=>{m.current=1,d.current=0,h.current=0,E()},j=(U,H)=>{const Q=a.current?.getBoundingClientRect();if(!Q||Q.width<=0||Q.height<=0)return;const{iw:te,ih:K}=R(),W=q6e({current:m.current,minScale:1,maxScale:o_,cover:z6e({viewportWidth:Q.width,viewportHeight:Q.height,contentAspect:te>0&&K>0?te/K:Number.NaN}),fallbackStep:L6e});if(W.kind==="fit"){N();return}const oe=W.scale;m.current=oe,d.current=(U-Q.left-Q.width/2)*(1-oe),h.current=(H-Q.top-Q.height/2)*(1-oe),T(),E()},q=U=>{try{U.currentTarget.setPointerCapture(U.pointerId)}catch{}if(c.current.set(U.pointerId,{x:U.clientX,y:U.clientY}),c.current.size===2){const H=[...c.current.values()],Q=H[0],te=H[1];Q&&te&&(f.current={dist:l_(Q,te),scale:m.current,cx:(Q.x+te.x)/2,cy:(Q.y+te.y)/2,tx:d.current,ty:h.current}),k.current=null}else c.current.size===1&&(k.current={x:U.clientX,y:U.clientY,tx:d.current,ty:h.current,moved:!1})},B=U=>{if(!c.current.has(U.pointerId))return;if(c.current.set(U.pointerId,{x:U.clientX,y:U.clientY}),c.current.size>=2&&f.current){const Q=[...c.current.values()],te=Q[0],K=Q[1];if(!te||!K)return;const W=l_(te,K);f.current.dist>0&&(m.current=Math.max(1,Math.min(o_,f.current.scale*(W/f.current.dist))));const oe=(te.x+K.x)/2,he=(te.y+K.y)/2;d.current=f.current.tx+(oe-f.current.cx),h.current=f.current.ty+(he-f.current.cy),T(),E();return}const H=k.current;if(c.current.size===1&&H){const Q=U.clientX-H.x,te=U.clientY-H.y;(Math.abs(Q)>s_||Math.abs(te)>s_)&&(H.moved=!0),m.current>1&&(d.current=H.tx+Q,h.current=H.ty+te,T(),E())}},F=U=>{const H=c.current.size===1,Q=k.current;if(c.current.delete(U.pointerId),c.current.size<2&&(f.current=null),c.current.size===0&&(k.current=null,H&&Q&&!Q.moved)){const te=Date.now();te-x.current<B6e?(x.current=0,j(U.clientX,U.clientY)):(x.current=te,t())}};return v.jsx("div",{ref:a,style:{position:"absolute",inset:0,overflow:"hidden",touchAction:c_(1)},onPointerDown:q,onPointerMove:B,onPointerUp:F,onPointerCancel:F,children:v.jsx("div",{ref:r,style:{width:"100%",height:"100%",transformOrigin:"center center",willChange:"transform"},children:e})})}function $6e(e,t){if(t==null||t.length===0)return null;if(/^https?:\/\//i.test(t))return t;const a=e.replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${a}${r}`}function U6e(e,t){const a=t[0];return a===void 0?null:$6e(e,a.url)}function H6e(e,t){return{handleOffer:(a,r,c)=>e(t,a,r,c),reoffer:(a,r,c,m)=>e(c,r,a,m)}}const Q6e=3500;function V6e(e){return e==="auto"?{kind:"adaptive"}:{kind:"profile",profile:e}}function K6e({system:e,deviceId:t,name:a,online:r,quality:c,muted:m,paused:d,showName:h,audioActive:f,micActive:k,onTogglePause:x,onToggleAudio:E,onToggleMic:R,onOpen:T,ptzSupported:N,onPtz:j,cellW:q,cellH:B,onCellPanel:F,highlight:U,showBoxes:H,overlay:Q,reconnectSignal:te,onStall:K,posterUrl:W,labels:oe=og,editable:he,span:Ae,onRemove:we,onResize:Ee,probeAuthToken:Ie}){const Me=pd(),{handleOffer:Y,getIceServers:de,addIceCandidate:Re,getIceCandidates:Qe,closeSession:re,getSessionState:V,getSessionDebug:ie,applyDownlinkProbe:fe}=IL(e.trpcClient,t),be=N7(e,t,U),ee=P.useRef(null),[Se,_e]=P.useState(0),[Be,Ge]=P.useState("idle"),Ft=P7({containerRef:ee,playing:Be==="playing"&&!d,onRecover:()=>{_e(ct=>ct+1),K?.(t)}}),[Ot,wt]=P.useState(void 0);P.useEffect(()=>{if(W||d)return;let ct=!1;const Ut=q!==void 0&&q>0?Math.round(q):void 0;return e.trpcClient.snapshot.getSnapshotLinks.query({targets:[{deviceId:t,...Ut!==void 0?{width:Ut}:{}}]}).then(La=>{if(ct)return;const Sa=U6e(e.serverUrl,La??[]);Sa!==null&&wt(Sa)}).catch(()=>{}),()=>{ct=!0}},[W,d,e,t,q]);const sa=W??Ot,nt=P.useMemo(()=>V6e(c),[c]),za=`grid:${t}:${c}`,ft=P.useMemo(()=>H6e(Y,nt),[Y,nt]),[lt,Dt]=P.useState(!1),bt=P.useRef(null),ve=()=>{bt.current&&clearTimeout(bt.current),bt.current=setTimeout(()=>Dt(!1),Q6e)},Fe=()=>{Dt(!0),ve()},Le=()=>{Dt(ct=>{const Ut=!ct;return Ut&&ve(),Ut})},ot=x6e(q??0,B??0),He=ct=>{ct.stopPropagation(),Fe()},ea=q!==void 0&&B!==void 0&&q>0&&B>0,$t=R6e(q??0,B??0,I6e),ze=ea?{position:"absolute",left:$t.left,top:$t.top,width:$t.width,height:$t.height}:{position:"absolute",inset:0},st=Math.max(1,Math.round(Ae?.cw??1)),Lt=Math.max(1,Math.round(Ae?.ch??1)),Kt=ea&&q!==void 0?q/st:0,qa=ea&&B!==void 0?B/Lt:0,fn=A6e(he===!0,q??0,B??0);return P.useEffect(()=>()=>{bt.current&&clearTimeout(bt.current)},[]),v.jsxs("div",{ref:ee,"data-stall-recovering":Ft.recovering?"true":void 0,style:{position:"relative",width:"100%",height:"100%",background:Yt.dark.mediaBlack},children:[v.jsxs("div",{style:ze,children:[v.jsx(F6e,{onTap:Le,children:d?v.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:Yt.dark.onMedia},children:v.jsx(u_,{size:28})}):v.jsx(AL,{applyDownlinkProbe:fe,serverUrl:e.serverUrl,streamKey:za,autoPlay:!0,muted:m,showControls:!1,className:"w-full h-full",handleOffer:ft.handleOffer,reoffer:ft.reoffer,getSessionState:V,getSessionDebug:ie,getIceServers:de,addIceCandidate:Re,getIceCandidates:Qe,closeSession:re,reconnectSignal:(te??0)+Se,onStateChange:Ge,posterUrl:sa,probeAuthToken:Ie,onClientNetworkSample:c==="auto"?ct=>{e.trpcClient.networkQuality.reportClientStats.mutate({deviceId:t,...ct}).catch(()=>{})}:void 0},za)}),H&&!d?v.jsx(O6e,{deviceId:t}):null,Q?.motionBoxes===!0&&!d?v.jsx(r6e,{deviceId:t}):null]}),v.jsxs("div",{style:{...ze,pointerEvents:"none",...Zqe(Wqe(ea?$t.width:q??0,Q?.size??Hqe))},children:[sk(Q?.audioMeter)&&!d?v.jsx(o6e,{deviceId:t,anchor:Q.audioMeter}):null,sk(Q?.occupancy)&&!d?v.jsx(l6e,{system:e,deviceId:t,anchor:Q.occupancy}):null,Q?.stats===!0&&!d?v.jsx(d6e,{containerRef:ee,anchor:Q.statsAt??c6e}):null,sk(Q?.viewers)&&!d?v.jsx(p6e,{system:e,deviceId:t,anchor:Q.viewers}):null]}),be&&(()=>{const ct=U?.appearance,Ut=be==="motion"?ct?.motionColor??Lc("motion",Me):be==="audio"?ct?.audioColor??Lc("audio",Me):ct?.detectionColor??Lc("detection",Me),La=ct?.thickness??3;return v.jsx("div",{style:{position:"absolute",inset:0,border:`${La}px solid ${Ut}`,boxShadow:`inset 0 0 12px ${Ut}`,pointerEvents:"none"}})})(),(h||lt)&&v.jsxs("div",{className:"cs-glass cs-fade","data-on":h||lt,style:{position:"absolute",left:0,right:0,top:0,display:"flex",alignItems:"center",gap:6,padding:"4px 8px",fontSize:12,fontWeight:600,fontFamily:"system-ui, sans-serif",pointerEvents:"none",opacity:h||lt?1:0},children:[v.jsx("span",{style:{width:8,height:8,borderRadius:4,background:r?Yt.dark.presence:Yt.dark.presenceOff}}),v.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a})]}),v.jsxs("div",{className:"cs-fade","data-on":lt,style:{position:"absolute",inset:0,opacity:lt?1:0,pointerEvents:"none"},children:[v.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"},children:v.jsx(Xo,{label:d?oe.play:oe.pause,big:!0,enabled:lt,onClick:ct=>{He(ct),x(t)},children:d?v.jsx(u_,{size:22}):v.jsx(G6e,{size:22})})}),v.jsxs("div",{style:{position:"absolute",left:8,bottom:8,display:"flex",gap:8,pointerEvents:"none"},children:[v.jsx(Xo,{label:f?oe.mute:oe.listen,active:f,enabled:lt,onClick:ct=>{He(ct),E(t)},children:f?v.jsx(W6e,{size:18}):v.jsx(Z6e,{size:18})}),v.jsx(Xo,{label:k?oe.stopTalk:oe.talk,active:k,enabled:lt,onClick:ct=>{He(ct),R(t)},children:v.jsx(Y6e,{size:18,muted:!k})}),N&&j&&(!F||!ot.overflow)?v.jsx(Xo,{label:oe.ptz,enabled:lt,onClick:ct=>{He(ct),j(t)},children:v.jsx(nLe,{size:18})}):null,F?ot.inline.map(ct=>v.jsx(Xo,{label:ct==="devices"?oe.linkedDevices:oe.viewOptions,enabled:lt,onClick:Ut=>{He(Ut),F(t,ct)},children:ct==="devices"?v.jsx(J6e,{size:18}):v.jsx(eLe,{size:18})},ct)):null,F&&ot.overflow?v.jsx(Xo,{label:oe.moreActions,enabled:lt,onClick:ct=>{He(ct),F(t,"actions")},children:v.jsx(tLe,{size:18})}):null]}),v.jsx("div",{style:{position:"absolute",right:8,bottom:8,pointerEvents:"none"},children:v.jsx(Xo,{label:oe.open,enabled:lt,onClick:ct=>{He(ct),T(t)},children:v.jsx(X6e,{size:18})})}),fn&&we?v.jsx("div",{style:{position:"absolute",right:8,top:8,pointerEvents:"none"},children:v.jsx(Xo,{label:oe.removeFromView,enabled:lt,onClick:ct=>{He(ct),we(t)},children:v.jsx(aLe,{size:18})})}):null,fn&&Ee?v.jsxs(v.Fragment,{children:[v.jsx(d_,{axis:"x",label:oe.resizeWidth,enabled:lt,track:Kt,span:st,onSpan:ct=>{Fe(),Ee(t,ct,Lt)}}),v.jsx(d_,{axis:"y",label:oe.resizeHeight,enabled:lt,track:qa,span:Lt,onSpan:ct=>{Fe(),Ee(t,st,ct)}})]}):null]})]})}function d_({axis:e,label:t,enabled:a,track:r,span:c,onSpan:m}){const d=P.useRef(null),h=f=>e==="x"?f.clientX:f.clientY;return v.jsx("div",{className:"cs-glass cs-grip",role:"separator","aria-label":t,"aria-orientation":e==="x"?"vertical":"horizontal",onPointerDown:f=>{f.stopPropagation(),f.currentTarget.setPointerCapture(f.pointerId),d.current={origin:h(f),base:c}},onPointerMove:f=>{if(d.current===null||!(r>0))return;f.stopPropagation();const k=Math.round((h(f)-d.current.origin)/r),x=Math.max(1,d.current.base+k);x!==c&&m(x)},onPointerUp:f=>{d.current=null,f.currentTarget.hasPointerCapture(f.pointerId)&&f.currentTarget.releasePointerCapture(f.pointerId)},onPointerCancel:()=>{d.current=null},style:{position:"absolute",...e==="x"?{right:0,top:"50%",width:14,height:48,transform:"translateY(-50%)"}:{bottom:0,left:"50%",width:48,height:14,transform:"translateX(-50%)"},borderRadius:7,cursor:e==="x"?"ew-resize":"ns-resize",touchAction:"none",pointerEvents:a?"auto":"none"}})}function Xo({children:e,label:t,onClick:a,big:r=!1,active:c=!1,enabled:m=!0}){const d=r?52:40;return v.jsx("button",{type:"button","aria-label":t,onClick:a,className:"cs-glass cs-glass-btn","data-active":c,style:{width:d,height:d,borderRadius:d/2,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,WebkitTapHighlightColor:"transparent",pointerEvents:m?"auto":"none"},children:e})}const Ss={fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};function u_({size:e}){return v.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",children:v.jsx("polygon",{points:"6 4 20 12 6 20 6 4",fill:"currentColor"})})}function G6e({size:e}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",children:[v.jsx("rect",{x:"6",y:"4",width:"4",height:"16",fill:"currentColor"}),v.jsx("rect",{x:"14",y:"4",width:"4",height:"16",fill:"currentColor"})]})}function W6e({size:e}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",...Ss,children:[v.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),v.jsx("path",{d:"M19.07 4.93a10 10 0 010 14.14M15.54 8.46a5 5 0 010 7.07"})]})}function Z6e({size:e}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",...Ss,children:[v.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),v.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),v.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})}function Y6e({size:e,muted:t}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",...Ss,children:[v.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),v.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2M12 19v4"}),t&&v.jsx("line",{x1:"3",y1:"3",x2:"21",y2:"21"})]})}function X6e({size:e}){return v.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",...Ss,children:v.jsx("path",{d:"M15 3h6v6M21 3l-9 9M21 14v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5"})})}function J6e({size:e}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",...Ss,children:[v.jsx("path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5A5.5 5.5 0 1 0 7.5 11.5c.8.8 1.3 1.5 1.5 2.5"}),v.jsx("path",{d:"M9 18h6M10 22h4"})]})}function eLe({size:e}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",...Ss,children:[v.jsx("path",{d:"M3 6h18M3 12h18M3 18h18"}),v.jsx("circle",{cx:"8",cy:"6",r:"2"}),v.jsx("circle",{cx:"16",cy:"12",r:"2"}),v.jsx("circle",{cx:"10",cy:"18",r:"2"})]})}function tLe({size:e}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",children:[v.jsx("circle",{cx:"5",cy:"12",r:"2",fill:"currentColor"}),v.jsx("circle",{cx:"12",cy:"12",r:"2",fill:"currentColor"}),v.jsx("circle",{cx:"19",cy:"12",r:"2",fill:"currentColor"})]})}function aLe({size:e}){return v.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",...Ss,children:v.jsx("path",{d:"M18 6L6 18M6 6l12 12"})})}function nLe({size:e}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",...Ss,children:[v.jsx("path",{d:"M12 2v20M2 12h20"}),v.jsx("path",{d:"M12 2l-3 3M12 2l3 3M12 22l-3-3M12 22l3-3M2 12l3-3M2 12l3 3M22 12l-3-3M22 12l-3 3"})]})}function iLe({wall:e,renderTile:t}){return v.jsx("div",{style:{position:"relative",width:e.wallW,height:e.wallH},children:e.placements.map(a=>v.jsx("div",{"data-device-id":a.deviceId,style:{position:"absolute",left:a.x,top:a.y,width:a.w,height:a.h},children:t(a.deviceId,a.w,a.h)},a.deviceId))})}function rLe(e){return{box:e,hostOwned:!1}}function oLe(e,t){return{box:t,hostOwned:!0}}function sLe(e,t){return e.hostOwned||!(t.w>0&&t.h>0)||t.w===e.box.w&&t.h===e.box.h?e:{box:t,hostOwned:!1}}function m_(){return{w:window.innerWidth,h:window.innerHeight}}function Ux(){const[e,t]=P.useState(()=>rLe(m_()));P.useEffect(()=>{const r=()=>t(c=>sLe(c,m_()));return window.addEventListener("resize",r),r(),()=>window.removeEventListener("resize",r)},[]);const a=P.useCallback((r,c)=>{t(m=>oLe(m,{w:r,h:c}))},[]);return{box:e.box,fit:a}}function p_({message:e}){return P.useEffect(()=>vr(R7("error",e)),[e]),v.jsxs("div",{style:{position:"fixed",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:Yt.dark.mediaBlack,color:Yt.dark.danger,fontFamily:"system-ui, sans-serif",fontSize:13,padding:16,textAlign:"center"},children:["Grid embed config error: ",e]})}const lLe=["setDevices","setSpans"];function cLe(e,t){return e.length===t.length&&e.every((a,r)=>a===t[r])}function dLe({system:e,config:t}){const[a,r]=P.useState(t.devices),[c,m]=P.useState(()=>new Set(t.audioOnIds??[])),d=E7(),h=P.useRef(d.setActiveMic);h.current=d.setActiveMic;const[f,k]=P.useState(()=>new Set(t.pausedIds??[])),[x,E]=P.useState(t.highlight),[R,T]=P.useState(t.activeOnly??!1),[N,j]=P.useState(t.showBoxes??!1),[q,B]=P.useState(()=>t.overlays??{}),[F,U]=P.useState(()=>t.spans??{}),H=xqe(a,x),Q=P.useMemo(()=>R?a.filter(ee=>H.has(ee)):a,[R,a,H]),[te,K]=P.useState(t.quality),[W,oe]=P.useState(t.layout),[he,Ae]=P.useState(t.showName),[we,Ee]=P.useState(0),Ie=P.useMemo(()=>Xze(t.labels),[t.labels]),[Me,Y]=P.useState(()=>t.snapshots??{}),de=P.useMemo(()=>new Set(t.ptzIds??[]),[t.ptzIds]),{box:Re,fit:Qe}=Ux(),re=Ie.camera,[V,ie]=P.useState({});P.useEffect(()=>{let ee=!1;return e.trpcClient.deviceManager.listAll.query({deviceIds:[...a],projection:"slim"}).then(Se=>{if(ee)return;const _e={};for(const Be of Se)_e[Be.id]={name:Be.name??`${re} ${Be.id}`,online:Be.online??!1};ie(_e)}).catch(()=>{}),()=>{ee=!0}},[e,a,re]),P.useEffect(()=>(window.__camstackGrid={setAudioOn:ee=>m(new Set(ee)),setMutedAll:ee=>{ee&&m(new Set)},setActiveMic:ee=>h.current(ee),setHighlight:ee=>E(ee),setActiveOnly:ee=>T(ee),setShowBoxes:ee=>j(ee),setOverlays:ee=>B(ee),setPaused:ee=>k(new Set(ee)),setDevices:ee=>r(Se=>cLe(Se,ee)?Se:[...ee]),setSpans:ee=>U(ee),setQuality:ee=>K(ee),setLayout:ee=>oe(ee),setShowName:Ae,setShowBadges:()=>{},setSnapshots:ee=>Y(ee),fit:Qe,reconnect:()=>Ee(ee=>ee+1)},vr(R7("ready",void 0,lLe)),()=>{window.__camstackGrid&&delete window.__camstackGrid}),[Qe]),P.useEffect(()=>Gm(ee=>{const Se=window.__camstackGrid;if(!Se)return;switch(ee.kind){case"setAudioOn":Se.setAudioOn(ee.value);break;case"setMutedAll":Se.setMutedAll(ee.value);break;case"setActiveMic":Se.setActiveMic(ee.value);break;case"setHighlight":Se.setHighlight(ee.value);break;case"setActiveOnly":Se.setActiveOnly(ee.value);break;case"setShowBoxes":Se.setShowBoxes(ee.value===!0);break;case"setOverlays":Se.setOverlays(ee.value);break;case"setPaused":Se.setPaused(ee.value);break;case"setDevices":Se.setDevices(ee.value);break;case"setSpans":Se.setSpans(ee.value);break;case"setQuality":Se.setQuality(w7.parse(ee.value));break;case"setLayout":Se.setLayout(ee.value);break;case"setShowName":Se.setShowName(ee.value);break;case"setShowBadges":Se.setShowBadges(ee.value);break;case"setSnapshots":Se.setSnapshots(ee.value);break;case"fit":Se.fit(ee.w,ee.h);break;case"reconnect":Se.reconnect();break}}),[]);const fe=P.useMemo(()=>kqe(Q,Re.w,Re.h,W,F),[Q,Re.w,Re.h,W,F]),be=P.useRef(null);return P.useEffect(()=>{const ee=be.current;if(!ee)return;const Se=[];ee.querySelectorAll("[data-device-id]").forEach(_e=>{const Be=Number(_e.dataset.deviceId),Ge=_e.getBoundingClientRect();Se.push({deviceId:Be,rect:{x:Ge.x,y:Ge.y,w:Ge.width,h:Ge.height}})}),Se.length&&vr(_qe(Se))},[fe,Q]),v.jsxs("div",{ref:be,style:{position:"fixed",inset:0,background:Yt.dark.mediaBlack,display:"flex",alignItems:"center",justifyContent:"center"},children:[R&&Q.length===0&&v.jsx("div",{style:{color:Yt.dark.eventsMuted,fontFamily:"system-ui, sans-serif",fontSize:14,padding:24,textAlign:"center"},children:Ie.noActiveCameras}),v.jsx(iLe,{wall:fe,renderTile:(ee,Se,_e)=>v.jsx(K6e,{system:e,probeAuthToken:t.token,deviceId:ee,name:V[ee]?.name??`${Ie.camera} ${ee}`,online:V[ee]?.online??!1,quality:te,muted:!c.has(ee),paused:f.has(ee),showName:he,audioActive:c.has(ee),micActive:d.activeMicId===ee,onTogglePause:Be=>vr(Aqe(Be)),onToggleAudio:Be=>vr(Cqe(Be)),onToggleMic:d.toggleMic,onOpen:Be=>vr(Mqe(Be)),ptzSupported:de.has(ee),onPtz:Be=>vr(Iqe(Be)),cellW:Se,cellH:_e,onCellPanel:t.cellPanels===!1?void 0:(Be,Ge)=>vr(Eqe(Be,Ge)),highlight:x,showBoxes:N,overlay:q[String(ee)],reconnectSignal:we,posterUrl:Me[String(ee)],editable:t.editable===!0,span:F[String(ee)],onRemove:Be=>vr(Rqe(Be)),onResize:(Be,Ge,Ft)=>vr(Tqe(Be,Ge,Ft)),labels:Ie})})]})}function uLe(){const e=Wm("grid",()=>window.__CAMSTACK_GRID__,M7,mqe),t=P.useMemo(()=>{if(e===null||!e.ok)return null;const a=xm({serverUrl:e.config.serverUrl,token:e.config.token}),r=new uq({defaultOptions:{queries:{retry:!1,refetchOnWindowFocus:!1}}});return{system:a,queryClient:r}},[e]);return P.useEffect(()=>{if(t)return()=>t.system.close()},[t]),e===null?null:e.ok?t?v.jsx(Zq,{system:t.system,children:v.jsx(pq,{client:t.queryClient,children:v.jsxs(S.Provider,{client:t.system.trpcClient,queryClient:t.queryClient,children:[v.jsx(Wg,{system:t.system}),v.jsx(dLe,{system:t.system,config:e.config})]})})}):v.jsx(p_,{message:"Failed to initialise the grid embed"}):v.jsx(p_,{message:e.error})}const Hx=qe([o({kind:_("adaptive")}),o({kind:_("profile"),profile:wn})]),mLe=o({deviceId:i().int().nonnegative(),target:Hx.optional(),muted:w().optional(),stats:w().optional(),snapshot:n().optional(),atMs:i().int().positive().optional()});function pLe(e){const t=mLe.safeParse(e);return t.success?t.data:null}const hLe=["live","loading","playing","paused","gap","ended","error"];function fLe(e){return typeof e=="string"&&hLe.includes(e)}const gLe=["not-negotiated","not-offered","no-audio-track","unsupported-codec","codec-mismatch","stream-failed","rate"],vLe=["stream-short","stream-empty"],Zs="low",h_=5e3;class yLe{constructor(t){this.deps=t,this.deps.channel.addEventListener("message",this.onMessage)}deps;begun=!1;disposed=!1;lastSentProfile=null;degradedRequest=null;positionsSeen=0;firstFrameAnnounced=!1;rvfcHandle=null;lastPushSeq=null;retargets=0;renders=0;acks=0;lastCursorMs=null;lastState=null;playIntentAt=null;playIntentKind=null;playIntentDragId=void 0;pendingUpgrade=null;upgradeTimer=null;upgradeWarmTimer=null;clipId=null;onMessage=t=>{if(this.disposed||typeof t.data!="string")return;let a;try{a=JSON.parse(t.data)}catch{return}if(typeof a!="object"||a===null)return;const r=a;if(r.t==="liveProfile"&&(r.profile==="high"||r.profile==="mid"||r.profile==="low")){this.deps.onLiveProfile?.(r.profile);return}if(r.t==="servedProfile"&&(r.profile==="high"||r.profile==="mid"||r.profile==="low")&&typeof r.requested=="string"){const c=r.requested;this.lastSentProfile=r.profile,this.degradedRequest=r.profile===c?null:c,this.degradedRequest!==null&&this.pendingUpgrade?.desiredProfile===this.degradedRequest&&(this.deps.onLog?.("scrub:playback-upgrade-vetoed",{to:this.degradedRequest}),this.cancelPlaybackUpgrade()),this.deps.onServedProfile?.({profile:r.profile,requested:c});return}if(r.t==="clipDuration"){const c=r;typeof c.clipId=="string"&&typeof c.durationMs=="number"&&Number.isFinite(c.durationMs)&&c.durationMs>0&&this.deps.onClipDuration?.({clipId:c.clipId,durationMs:c.durationMs});return}if(r.t==="clipAudio"){const c=r;if(typeof c.clipId!="string"||c.clipId.length===0||typeof c.carried!="boolean")return;const m=c.codec==="opus"||c.codec==="pcmu"?c.codec:void 0,d=gLe.find(k=>k===c.reason),h=typeof c.rate=="number"&&Number.isFinite(c.rate)&&c.rate>0?c.rate:void 0,f=d==="rate"&&h===void 0?void 0:d;this.deps.onClipAudio?.({clipId:c.clipId,carried:c.carried,...m===void 0?{}:{codec:m},...f===void 0?{}:{reason:f},...f==="rate"&&h!==void 0?{rate:h}:{}});return}if(r.t==="clipIncomplete"){const c=r;if(typeof c.clipId!="string"||c.clipId.length===0)return;const m=vLe.find(d=>d===c.code);if(m===void 0||typeof c.reason!="string"||c.reason.trim().length===0)return;this.deps.onClipIncomplete?.({clipId:c.clipId,code:m,reason:c.reason});return}if(r.t==="state"&&fLe(r.state)){this.lastState=r.state,r.state==="playing"||r.state==="paused"?(this.maybeArmPlaybackUpgrade(),this.playIntentAt!==null&&(this.deps.onLog?.("playback:ready",{kind:this.playIntentKind,state:r.state,waitMs:Math.round(performance.now()-this.playIntentAt),dragId:this.playIntentDragId}),this.playIntentAt=null,this.playIntentKind=null,this.playIntentDragId=void 0)):(r.state==="live"||r.state==="gap"||r.state==="ended"||r.state==="error")&&this.cancelPlaybackUpgrade(),this.deps.onState?.(r.state);return}r.t!=="position"||typeof r.epochMs!="number"||(this.lastCursorMs=r.epochMs,this.deps.onPosition?.(r.epochMs),typeof r.seq=="number"&&(this.lastPushSeq=r.seq),this.begun&&(this.positionsSeen+=1,this.rvfcCapable()||(this.acks+=1,this.sendAck())))};sendAck(){this.send(this.lastPushSeq===null?{t:"scrubAck"}:{t:"scrubAck",seq:this.lastPushSeq})}rvfcCapable(){return typeof this.deps.video()?.requestVideoFrameCallback=="function"}send(t){return this.disposed||this.deps.channel.readyState!=="open"?!1:(this.deps.channel.send(JSON.stringify(t)),!0)}sendPlayRecorded(t,a,r,c,m){const d=this.send({t:"playRecorded",deviceId:t,epoch:a,profile:r});return d&&(this.lastSentProfile=r,this.playIntentAt=performance.now(),this.playIntentKind=c,this.playIntentDragId=m,this.deps.onLog?.("playback:intent",{kind:c,deviceId:t,epochMs:a,profile:r,dragId:m})),d}maybeArmPlaybackUpgrade(){if(this.pendingUpgrade===null||this.upgradeTimer!==null||this.disposed)return;this.upgradeTimer=setTimeout(()=>this.firePlaybackUpgrade(),h_);const t=this.pendingUpgrade;this.upgradeWarmTimer=setTimeout(()=>{if(this.upgradeWarmTimer=null,this.pendingUpgrade===null||this.disposed)return;const a=this.lastCursorMs??t.landEpochMs;this.warm(a,t.desiredProfile)},Math.max(0,h_-1500))}firePlaybackUpgrade(){this.upgradeTimer=null;const t=this.pendingUpgrade;if(this.pendingUpgrade=null,!t||this.disposed)return;const a=this.lastCursorMs??t.landEpochMs;this.sendPlayRecorded(t.deviceId,a,t.desiredProfile,"upgrade"),this.deps.onLog?.("scrub:playback-upgrade",{from:Zs,to:t.desiredProfile,epochMs:a})}cancelPlaybackUpgrade(){this.upgradeTimer!==null&&(clearTimeout(this.upgradeTimer),this.upgradeTimer=null),this.upgradeWarmTimer!==null&&(clearTimeout(this.upgradeWarmTimer),this.upgradeWarmTimer=null),this.pendingUpgrade=null}playRecorded(t,a,r){return this.cancelPlaybackUpgrade(),this.clipId=null,this.sendPlayRecorded(t,a,r,"play")}holdsClip(){return this.clipId!==null}playClip(t,a,r,c,m){this.cancelPlaybackUpgrade();const d=this.send({t:"playClip",deviceId:t,clipId:a,provider:r,offsetMs:Math.max(0,Math.round(c)),...m===void 0?{}:{profile:m}});return d&&(this.clipId=a),d}upgradePlayback(t,a,r){return r===this.lastSentProfile?!0:this.clipId!==null?(this.deps.onLog?.("clip:playback-upgrade-refused",{clipId:this.clipId,to:r}),!0):(this.cancelPlaybackUpgrade(),this.warm(a,r),this.sendPlayRecorded(t,a,r,"upgrade"))}landFromScrub(t,a,r,c){if(this.end(),this.cancelPlaybackUpgrade(),this.clipId!==null){const d=this.commit(a,c);return d&&(this.lastCursorMs=a,this.deps.onLog?.("playback:intent",{kind:"clip-commit",deviceId:t,epochMs:a,dragId:c})),d}return this.sendPlayRecorded(t,a,Zs,"land",c)?(this.lastCursorMs=a,r===this.degradedRequest?this.deps.onLog?.("scrub:playback-upgrade-vetoed",{to:r,epochMs:a}):r!==Zs&&(this.pendingUpgrade={deviceId:t,desiredProfile:r,landEpochMs:a},this.warm(a,r),(this.lastState==="playing"||this.lastState==="paused")&&this.maybeArmPlaybackUpgrade()),!0):!1}seek(t){this.cancelPlaybackUpgrade();const a=this.send({t:"seek",epoch:t});return a&&(this.playIntentAt=performance.now(),this.playIntentKind="seek",this.playIntentDragId=void 0,this.deps.onLog?.("playback:intent",{kind:"seek",epochMs:t})),a}warm(t,a=Zs){return this.send({t:"warm",epoch:t,profile:a})}setRate(t){return this.send({t:"setRate",rate:t})}stepFrame(t){return this.send({t:"stepFrame",dir:t})}commit(t,a){return this.end(),this.send(a!==void 0?{t:"scrubCommit",epoch:t,dragId:a}:{t:"scrubCommit",epoch:t})}goLive(){this.cancelPlaybackUpgrade();const t=this.send({t:"goLive"});return t&&(this.deps.onLog?.("scrub:push-golive",{clipId:this.clipId}),this.clipId=null),this.end(),t}isActive(){return this.begun&&!this.disposed&&this.deps.channel.readyState==="open"}isOpen(){return!this.disposed&&this.deps.channel.readyState==="open"}begin(t){return this.disposed||this.deps.channel.readyState!=="open"?!1:(this.begun||(this.begun=!0,this.positionsSeen=0,this.firstFrameAnnounced=!1,this.retargets=0,this.renders=0,this.acks=0,this.cancelPlaybackUpgrade(),this.lastSentProfile!==Zs&&(this.lastSentProfile=Zs,this.send({t:"setProfile",profile:Zs})),this.send(t!==void 0?{t:"scrubStart",dragId:t}:{t:"scrubStart"}),this.armRenderAck(),this.deps.onLog?.("scrub:push-begin",{rvfc:this.rvfcCapable(),dragId:t})),!0)}retarget(t,a){this.isActive()&&(this.retargets+=1,this.send(a?{t:"scrubTo",epoch:t,m:a.mode,v:Math.round(a.velocityPxPerS)}:{t:"scrubTo",epoch:t}))}end(){this.begun&&this.deps.onLog?.("scrub:push-drag-end",{retargets:this.retargets,positions:this.positionsSeen,renders:this.renders,acks:this.acks}),this.begun=!1,this.cancelRenderAck()}dispose(){this.cancelPlaybackUpgrade(),this.end(),this.disposed=!0,this.deps.channel.removeEventListener("message",this.onMessage)}armRenderAck(){const t=this.deps.video();t?.requestVideoFrameCallback&&(this.rvfcHandle=t.requestVideoFrameCallback(()=>{this.rvfcHandle=null,!(!this.begun||this.disposed)&&(this.positionsSeen>0&&(this.renders+=1,this.acks+=1,this.sendAck(),this.firstFrameAnnounced||(this.firstFrameAnnounced=!0,this.deps.onFirstFrame?.()),this.deps.onLog?.("scrub:drawn",{depth:"push"})),this.armRenderAck())}))}cancelRenderAck(){this.rvfcHandle!==null&&(this.deps.video()?.cancelVideoFrameCallback?.(this.rvfcHandle),this.rvfcHandle=null)}}function bLe(e,t,a,r){return e?.isOpen()?(e.warm(a),e.playRecorded(t,a,r)):!1}const kLe=24e4;function SLe(e,t=kLe){if(t<=0)return[e];const a=[];for(let r=0;r<e.length;r+=t)a.push(e.slice(r,r+t));return a.length===0?[""]:a}const wLe=["video/mp4;codecs=avc1.42E01E,mp4a.40.2","video/webm;codecs=vp8,opus","video/webm;codecs=vp9,opus"],f_=["video/mp4;codecs=avc1.42E01E","video/mp4","video/webm;codecs=vp8","video/webm"];function xLe(e=a=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(a),t){const a=t?.audio?[...wLe,...f_]:f_;for(const r of a)try{if(e(r))return r}catch{}return""}function MLe(e,t){const a=[...e.getVideoTracks()],r=t?.getAudioTracks()??[],c=r.length>0?r.map(m=>{const d=m.clone();return"enabled"in d&&(d.enabled=!0),d}):[...e.getAudioTracks()];return[...a,...c]}function CLe(e,t=30){const a=e;try{if(typeof a.captureStream=="function"){const r=a.captureStream(t);if(r.getVideoTracks().length>0)return r}}catch{}try{if(typeof a.mozCaptureStream=="function"){const r=a.mozCaptureStream(t);if(r.getVideoTracks().length>0)return r}}catch{}return ALe(e,t)}function ALe(e,t){if(e.videoWidth<2||e.videoHeight<2||typeof document>"u")return null;const a=document.createElement("canvas");a.width=e.videoWidth,a.height=e.videoHeight;const r=a.getContext("2d");if(!r||typeof a.captureStream!="function")return null;let c=!0;const m=()=>{if(c){try{r.drawImage(e,0,0,a.width,a.height)}catch{}requestAnimationFrame(m)}};m();const d=a.captureStream(t),h=d.getVideoTracks()[0];if(h){const f=h.stop.bind(h);h.stop=()=>{c=!1,f()}}return d}function ILe(e){return new Promise((t,a)=>{const r=new FileReader;r.onload=()=>{const c=String(r.result??""),m=c.indexOf(",");t(m>=0?c.slice(m+1):c)},r.onerror=()=>a(r.error??new Error("read failed")),r.readAsDataURL(e)})}function ELe(){return`c${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}function RLe(e){let t=null,a=[],r=null,c="",m=!1;const d=()=>{if(t=null,a=[],m=!1,r){for(const f of r.getTracks())try{f.stop()}catch{}r=null}},h=f=>{d(),e.emit({type:"liveCaptureError",message:f})};return{start(){if(t)return;const f=e.getVideo();if(!f){h("no video");return}if(typeof MediaRecorder>"u"){h("MediaRecorder missing");return}const k=CLe(f);if(!k){h("no video");return}const x=f.srcObject instanceof MediaStream?f.srcObject:null,E=MLe(k,x);if(x&&x.getAudioTracks().length>0)for(const j of k.getAudioTracks())try{j.stop()}catch{}const R=new MediaStream(E);r=R;const T=E.some(j=>j.kind==="audio"),N=xLe(void 0,{audio:T});try{t=N?new MediaRecorder(R,{mimeType:N,videoBitsPerSecond:25e5,...T?{audioBitsPerSecond:128e3}:{}}):new MediaRecorder(R)}catch(j){h(j instanceof Error?j.message:"MediaRecorder missing");return}a=[],c=ELe(),m=!1,t.ondataavailable=j=>{j.data&&j.data.size>0&&a.push(j.data)},t.onerror=()=>h("MediaRecorder missing");try{t.start(1e3)}catch(j){h(j instanceof Error?j.message:"MediaRecorder missing")}},stop(){const f=t;if(!f||m){f||h("no video");return}m=!0;const k=c,x=f.mimeType||"video/mp4";f.onstop=()=>{const E=new Blob(a,{type:x});if(d(),E.size===0){e.emit({type:"liveCaptureError",message:"empty capture"});return}ILe(E).then(R=>{e.emit({type:"liveCaptureStart",id:k,mime:x});const T=SLe(R),N=T.length;T.forEach((j,q)=>{e.emit({type:"liveCaptureChunk",id:k,index:q,total:N,data:j})}),e.emit({type:"liveCaptureDone",id:k})}).catch(R=>{e.emit({type:"liveCaptureError",message:R instanceof Error?R.message:"encode failed"})})};try{typeof f.requestData=="function"&&f.requestData(),f.stop()}catch(E){h(E instanceof Error?E.message:"stop failed")}},abort(){if(t&&t.state!=="inactive")try{t.stop()}catch{}d()}}}const g_=2560,TLe=.9;function _Le(e,t){const a=Math.max(e,t);if(a<=g_)return{width:e,height:t};const r=g_/a;return{width:Math.round(e*r),height:Math.round(t*r)}}function PLe(e){const t=e.indexOf(",");return e.startsWith("data:")&&t>=0?e.slice(t+1):null}function NLe(e){if(e.videoWidth<2||e.videoHeight<2||typeof document>"u")return null;const{width:t,height:a}=_Le(e.videoWidth,e.videoHeight),r=document.createElement("canvas");r.width=t,r.height=a;const c=r.getContext("2d");if(!c)return null;try{c.drawImage(e,0,0,t,a);const m=PLe(r.toDataURL("image/jpeg",TLe));return m===null||m.length===0?null:{base64:m,width:t,height:a}}catch{return null}}function OLe(e,t){const a=e.getVideo(),r=a===null?null:NLe(a);if(r===null){e.emit({type:"snapshotError",id:t,message:"no frame"});return}e.emit({type:"snapshot",id:t,base64:r.base64,width:r.width,height:r.height})}const DLe=8,jLe=2.5;function zLe(e){return e>=DLe?"high":e>=jLe?"mid":"low"}function qLe(e,t){return e.kind==="profile"?e.profile:"low"}function LLe(e,t){return e.kind==="profile"?e.profile:zLe(t)}const BLe=o({serverUrl:n().min(1),token:n().min(1),deviceId:i().int().nonnegative(),target:Hx,muted:w(),stats:w().optional(),highlight:x7.optional(),snapshot:n().optional(),initialSeekMs:i().positive().optional(),initialClipId:n().min(1).optional(),initialClipProvider:n().min(1).optional(),initialClipProfile:n().min(1).optional()}),v_=["setDevice","setDevice.atMs","setToken"];function bw(e,t){qt(t!==void 0?{type:"state",state:e,message:t,caps:v_}:{type:"state",state:e,caps:v_})}function FLe(e){switch(e){case"playing":return"playing";case"error":return"error";case"connecting":case"disconnected":case"idle":return"connecting"}}function y_(e,t){return qLe(e)}async function $Le(){if(typeof window>"u")return null;const e=window.location.origin.replace(/\/+$/,""),t=new AbortController,a=window.setTimeout(()=>t.abort(),2500),r=performance.now();try{const c=await fetch(`${e}/adaptive-probe`,{signal:t.signal});if(!c.ok)return null;const m=await c.arrayBuffer(),d=Math.max(1,performance.now()-r);return m.byteLength<1024?null:m.byteLength*8/d/1e3}catch{return null}finally{window.clearTimeout(a)}}function b_(e,t,a,r){r.kind==="adaptive"&&$Le().then(c=>{if(c===null)return;const m=LLe(r,c);e.upgradePlayback(t,a,m)})}function ULe(e){return e.kind==="adaptive"?{kind:"adaptive"}:{kind:"profile",profile:e.profile}}function HLe(e){return e.kind==="adaptive"?"embed:adaptive":`embed:profile:${e.profile}`}function QLe(e){const t=BLe.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(a=>`${a.path.join(".")||"(root)"}: ${a.message}`).join("; ")}}function k_({message:e}){return P.useEffect(()=>{bw("error",e)},[e]),v.jsxs("div",{style:{position:"fixed",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:Yt.dark.mediaBlack,color:Yt.dark.danger,fontFamily:"system-ui, sans-serif",fontSize:13,padding:16,textAlign:"center"},children:["Embed config error: ",e]})}function VLe({system:e,deviceId:t,initialTarget:a,initialMuted:r,initialStats:c,initialHighlight:m,initialSnapshot:d,initialSeekMs:h,initialClipId:f,initialClipProvider:k,initialClipProfile:x,probeAuthToken:E}){const[R,T]=P.useState(a),N=pd();P.useEffect(()=>d7(t),[t]);const j=P.useRef(R);j.current=R;const[q,B]=P.useState(r),[F,U]=P.useState(c),[H,Q]=P.useState(m),[te,K]=P.useState(d),[W,oe]=P.useState(0),[he,Ae]=P.useState("idle"),{box:we,fit:Ee}=Ux(),Ie=N7(e,t,H),Me=E7(),Y=P.useRef(Me.setActiveMic);Y.current=Me.setActiveMic;const{handleOffer:de,getIceServers:Re,addIceCandidate:Qe,getIceCandidates:re,closeSession:V,getSessionState:ie,getSessionDebug:fe,applyDownlinkProbe:be}=IL(e.trpcClient,t),ee=P.useMemo(()=>ULe(R),[R]),Se=P.useMemo(()=>(ve,Fe,Le)=>de(ee,ve,Fe,Le),[de,ee]),_e=P.useMemo(()=>(ve,Fe,Le,ot)=>de(Le,Fe,ve,ot),[de]),Be=P.useRef(null),Ge=P.useRef(null),Ft=P.useRef(null);P7({containerRef:Ft,playing:he==="playing",onRecover:()=>{oe(ve=>ve+1),qt({type:"log",scope:"stream-debug",msg:"stall-recovery",data:{reason:"no presented frame while playing"}})}});const Ot=P.useRef("low"),wt=P.useRef(!1),sa=P.useRef(null),nt=P.useRef(null),za=P.useRef(null),ft=()=>{const ve=nt.current;if(ve===null)return;const Fe=Ot.current,Le=`${ve.phase}|${ve.viewportWidth??"-"}x${ve.viewportHeight??"-"}|${ve.devicePixelRatio??"-"}|${ve.downlinkMbps??"-"}|${ve.prefersTier??"-"}|${ve.probeOrigin??"unreachable"}|${Fe}`;Le!==za.current&&(za.current=Le,qt({type:"log",scope:"adaptive",msg:"tier decision",data:{deviceId:t,requested:R.kind==="adaptive"?"adaptive":`pinned:${R.kind}`,phase:ve.phase,viewportWidth:ve.viewportWidth??null,viewportHeight:ve.viewportHeight??null,devicePixelRatio:ve.devicePixelRatio??null,downlinkMbps:ve.downlinkMbps??null,prefersTier:ve.prefersTier??null,probeOrigin:ve.probeOrigin,liveProfile:Fe}}))},lt=P.useRef(h??null),Dt=P.useRef(f===void 0||k===void 0?null:{clipId:f,provider:k,...x===void 0?{}:{profile:x}});P.useEffect(()=>{if(!q){let Fe=0;for(const Le of Array.from(document.querySelectorAll("video"))){const ot=Le.srcObject;if(ot instanceof MediaStream)for(const He of ot.getAudioTracks())He.enabled||(He.enabled=!0,Fe++)}Fe>0&&qt({type:"log",scope:"live-audio",msg:"un-muted",data:{restored:Fe}});return}const ve=setInterval(()=>{let Fe=0;for(const Le of Array.from(document.querySelectorAll("video"))){Le.muted||(Le.muted=!0,Fe++);const ot=Le.srcObject;if(ot instanceof MediaStream)for(const He of ot.getAudioTracks())He.enabled&&(He.enabled=!1,Fe++)}Fe>0&&qt({type:"log",scope:"live-audio",msg:"re-muted",data:{corrected:Fe}})},1e3);return()=>clearInterval(ve)},[q]),P.useEffect(()=>()=>Be.current?.dispose(),[]),P.useEffect(()=>{const ve=()=>{const ze=Be.current;return ze?.isOpen()?ze:null},Fe=()=>y_(j.current,Ot.current),Le=(ze,st)=>{b_(ze,t,st,j.current)},ot=ze=>{wt.current||(wt.current=!0,qt({type:"log",scope:"recorded:session",msg:"pointer move with no open session",data:{what:ze}}),qt({type:"recState",state:"error"}))},He=(ze,st)=>{const Lt=ve();return!Lt||!st(Lt)?(ot(ze),!1):(wt.current=!1,!0)},ea=(ze,st)=>{He("scrubCommit",Lt=>{const Kt=Lt.landFromScrub(t,ze,Fe(),st);return Kt&&Le(Lt,ze),Kt})},$t=RLe({emit:qt,getVideo:()=>Ge.current});return window.__camstackEmbed={setMuted:ze=>B(ze),setTarget:ze=>{const st=Hx.safeParse(ze);st.success&&T(st.data)},setStats:ze=>U(ze),setHighlight:ze=>Q(ze),setSnapshot:ze=>K(ze),setMic:ze=>Y.current(ze?t:null),fit:Ee,reconnect:()=>oe(ze=>ze+1),playRecorded:(ze,st,Lt)=>{Number.isFinite(st)&&He("playRecorded",Kt=>Kt.playRecorded(ze,st,Lt))},playClip:(ze,st,Lt,Kt,qa)=>{if(!Number.isFinite(Kt)||typeof st!="string"||st.length===0||typeof Lt!="string"||Lt.length===0){qt({type:"log",scope:"clip:play",msg:"playClip REFUSED — the command is malformed",data:{deviceId:ze,clipId:String(st).slice(0,120),provider:Lt,offsetMs:Kt}});return}qt({type:"log",scope:"clip:play",msg:"playClip arrived",data:{deviceId:ze,clipId:st.slice(0,120),provider:Lt,offsetMs:Kt,profile:qa??null}});const fn=He("playClip",ct=>ct.playClip(ze,st,Lt,Kt,qa));sa.current=fn?null:{deviceId:ze,clipId:st,provider:Lt,offsetMs:Kt,...qa!==void 0?{profile:qa}:{}},qt({type:"log",scope:"clip:play",msg:fn?"playClip sent to the broker":"playClip HELD — no open session yet",data:{deviceId:ze,sent:fn}})},seek:ze=>{Number.isFinite(ze)&&He("seek",st=>{if(st.holdsClip())return st.seek(ze);const Lt=st.playRecorded(t,ze,Fe());return Lt&&Le(st,ze),Lt})},scrubCommit:(ze,st)=>{Number.isFinite(ze)&&ea(ze,st)},scrubStart:ze=>{qt({type:"log",scope:"recorded:scrub",msg:"scrubStart",data:{dragId:ze}}),He("scrubStart",st=>st.begin(ze))},scrubTo:(ze,st,Lt)=>{if(!Number.isFinite(ze))return;const Kt=(st==="fine"||st==="coarse")&&Number.isFinite(Lt)?{mode:st,velocityPxPerS:Lt}:void 0;He("scrubTo",qa=>qa.isActive()?(qa.retarget(ze,Kt),!0):!1)},timelineWarm:ze=>{Number.isFinite(ze)&&ve()?.warm(ze)},scrubEnd:ze=>{Number.isFinite(ze)&&ea(ze)},setRate:ze=>{Number.isFinite(ze)&&He("setRate",st=>st.setRate(ze))},stepFrame:ze=>{ze!==1&&ze!==-1||He("stepFrame",st=>st.stepFrame(ze))},goLive:()=>{sa.current=null,He("goLive",ze=>ze.goLive())&&qt({type:"recState",state:"live"})},startLiveCapture:()=>$t.start(),stopLiveCapture:()=>$t.stop(),snapshot:ze=>OLe({emit:qt,getVideo:()=>Ge.current},ze)},()=>{$t.abort(),window.__camstackEmbed&&delete window.__camstackEmbed}},[t,Ee]),P.useEffect(()=>{qt({type:"micState",state:Me.micState})},[Me.micState]),P.useEffect(()=>Gm(ve=>{const Fe=window.__camstackEmbed;if(!Fe)return;switch(ve.kind){case"setMuted":Fe.setMuted(ve.value);break;case"setTarget":Fe.setTarget(ve.value);break;case"setStats":Fe.setStats(ve.value);break;case"setHighlight":Fe.setHighlight(ve.value);break;case"setSnapshot":Fe.setSnapshot(ve.value);break;case"setMic":Fe.setMic(ve.value);break;case"fit":Fe.fit(ve.w,ve.h);break;case"reconnect":Fe.reconnect();break;case"playRecorded":Fe.playRecorded(ve.deviceId,ve.epochMs,ve.profile);break;case"seek":Fe.seek(ve.epochMs??ve.value);break;case"scrubCommit":Fe.scrubCommit(ve.epochMs??ve.value,ve.dragId);break;case"scrubStart":Fe.scrubStart(ve.dragId);break;case"scrubTo":Fe.scrubTo(ve.epochMs??ve.value,ve.m,ve.v);break;case"scrubEnd":Fe.scrubEnd(ve.epochMs??ve.value);break;case"timelineWarm":Fe.timelineWarm(ve.epochMs??ve.value);break;case"setRate":Fe.setRate(ve.rate??ve.value);break;case"stepFrame":{const ot=ve.dir;(ot===1||ot===-1)&&Fe.stepFrame(ot);break}case"goLive":Fe.goLive();break;case"startLiveCapture":Fe.startLiveCapture();break;case"stopLiveCapture":Fe.stopLiveCapture();break;case"snapshot":typeof ve.id=="string"&&Fe.snapshot(ve.id);break}}),[]);const bt=HLe(R);return v.jsxs("div",{ref:Ft,style:{position:"fixed",left:0,top:0,width:we.w,height:we.h,background:Yt.dark.mediaBlack},children:[v.jsx(AL,{serverUrl:e.serverUrl,applyDownlinkProbe:be,streamKey:bt,autoPlay:!0,muted:q,showControls:!1,showStats:F,onDebugStats:ve=>qt({type:"log",scope:"stream-debug",msg:"sample",data:ve}),onPlaybackStats:ve=>qt({type:"log",scope:"playback",msg:"stats",data:ve}),onConnectTiming:ve=>qt({type:"log",scope:"webrtc-timing",msg:"connect",data:ve}),onClientNetworkSample:R.kind==="adaptive"?ve=>{e.trpcClient.networkQuality.reportClientStats.mutate({deviceId:t,...ve}).catch(()=>{})}:void 0,probeAuthToken:E,className:"w-full h-full",onAdaptiveHints:ve=>{nt.current=ve,ft()},handleOffer:Se,reoffer:_e,getSessionState:ie,getSessionDebug:fe,getIceServers:Re,addIceCandidate:Qe,getIceCandidates:re,closeSession:V,reconnectSignal:W,posterUrl:te,onStateChange:ve=>{Ae(ve),bw(FLe(ve))},onError:ve=>bw("error",ve),onReconnectAttempt:ve=>qt({type:"log",scope:"live:retry",msg:ve.kind==="retry"?"auto-retry scheduled":"auto-retry exhausted",data:ve}),onControlChannel:ve=>{Be.current?.dispose(),wt.current=!1,Be.current=new yLe({channel:ve,video:()=>Ge.current,onState:Le=>qt({type:"recState",state:Le}),onPosition:Le=>qt({type:"position",positionMs:Le}),onServedProfile:Le=>qt({type:"servedProfile",profile:Le.profile,requested:Le.requested}),onClipDuration:Le=>qt({type:"clipDuration",clipId:Le.clipId,durationMs:Le.durationMs}),onClipAudio:Le=>qt({type:"clipAudio",...Le}),onClipIncomplete:Le=>qt({type:"clipIncomplete",...Le}),onLiveProfile:Le=>{Ot.current=Le,ft()},onFirstFrame:()=>qt({type:"scrubDrawn"}),onLog:(Le,ot)=>qt({type:"log",scope:Le.startsWith("playback:")?"playback":"scrub",msg:Le,data:ot})});const Fe=()=>{const Le=Be.current;if(Le===null)return;const ot=Dt.current;if(ot!==null){const $t=Le.playClip(t,ot.clipId,ot.provider,0,ot.profile);qt({type:"log",scope:"clip:play",msg:$t?"initial clip opened":"initial clip still waiting for the channel",data:{deviceId:t,clipId:ot.clipId.slice(0,120),sent:$t}}),$t&&(Dt.current=null);return}const He=sa.current;if(He===null)return;const ea=Le.playClip(He.deviceId,He.clipId,He.provider,He.offsetMs,He.profile);qt({type:"log",scope:"clip:play",msg:ea?"held clip asserted on the open channel":"held clip still waiting",data:{deviceId:He.deviceId,clipId:He.clipId.slice(0,120),sent:ea}}),ea&&(sa.current=null)};if(ve.addEventListener("open",Fe),Fe(),lt.current!==null){const Le=()=>{const ot=lt.current;if(ot===null)return;const He=y_(j.current,Ot.current);bLe(Be.current,t,ot,He)&&(lt.current=null,Be.current&&b_(Be.current,t,ot,j.current),qt({type:"log",scope:"recorded:initial-seek",msg:"config-carried seek fired",data:{epochMs:ot,profile:He}}))};ve.readyState==="open"?Le():ve.addEventListener("open",Le,{once:!0})}},onVideoElement:ve=>{Ge.current=ve}}),Ie&&(()=>{const ve=H?.appearance,Fe=Ie==="motion"?ve?.motionColor??Lc("motion",N):Ie==="audio"?ve?.audioColor??Lc("audio",N):ve?.detectionColor??Lc("detection",N),Le=ve?.thickness??3;return v.jsx("div",{style:{position:"absolute",inset:0,border:`${Le}px solid ${Fe}`,boxShadow:`inset 0 0 12px ${Fe}`,pointerEvents:"none",transform:"translateZ(0)"}})})()]})}function KLe(){const e=Wm("player",()=>window.__CAMSTACK_EMBED__,QLe),[t,a]=P.useState(null),[r,c]=P.useState(null),m=P.useRef(null),d=P.useRef(null);d.current=r;const h=j=>{if(typeof j!="string"||j.length===0||d.current===j)return;const q=m.current;q!==null&&(q.setToken(j),q.reconnect(),c(j))};P.useEffect(()=>{const j=B=>{const F=pLe(B);F&&a(F)};window.__camstackEmbedPage={setDevice:j,setToken:h};const q=Gm(B=>{if(B.kind==="setDevice"){j(B.value);return}B.kind==="setToken"&&h(B.value)});return()=>{window.__camstackEmbedPage&&delete window.__camstackEmbedPage,q()}},[]);const f=P.useMemo(()=>{if(e===null||!e.ok)return null;const j=xm({serverUrl:e.config.serverUrl,token:e.config.token}),q=new uq({defaultOptions:{queries:{retry:!1,refetchOnWindowFocus:!1}}});return{system:j,queryClient:q}},[e]);if(P.useEffect(()=>{if(!f){m.current=null;return}return m.current=f.system,e!==null&&e.ok&&c(e.config.token),()=>{f.system.close(),m.current=null}},[f,e]),e===null)return null;if(!e.ok)return v.jsx(k_,{message:e.error});if(!f)return v.jsx(k_,{message:"Failed to initialise the embed player"});const k=t?.deviceId??e.config.deviceId,x=t?.target??e.config.target,E=t?.muted??e.config.muted,R=t?.stats??e.config.stats??!1,T=t!==null?t.snapshot:e.config.snapshot,N=r??e.config.token;return v.jsx(Zq,{system:f.system,children:v.jsx(pq,{client:f.queryClient,children:v.jsxs(S.Provider,{client:f.system.trpcClient,queryClient:f.queryClient,children:[v.jsx(Wg,{system:f.system}),v.jsx(VLe,{system:f.system,probeAuthToken:N,deviceId:k,initialTarget:x,initialMuted:E,initialStats:R,initialHighlight:e.config.highlight,initialSnapshot:T,initialSeekMs:t===null?e.config.initialSeekMs:t.atMs},k)]})})})}const GLe="recorder",WLe=o({serverUrl:n().min(1),token:n().min(1),deviceId:i().int().nonnegative(),startMs:i().int().nonnegative().optional(),provider:n().min(1).optional()});function ZLe(e){if(e==null)return{ok:!1,error:"config is required"};const t=WLe.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(a=>`${a.path.join(".")||"(root)"}: ${a.message}`).join("; ")}}function YLe(e,t){const a=(e-t)/1e3;return Number.isFinite(a)&&a>0?a:0}const S_=360*60*1e3,XLe="scrub unavailable: no open RecordedTrackSession";function Ri(e){qt(e)}function Pa(e,t,a){try{qt({type:"log",scope:e,msg:t,data:a})}catch{}try{console.debug(`[rec-embed:${e}] ${t}`,a??"")}catch{}}function JLe({system:e,config:t}){P.useEffect(()=>d7(t.deviceId),[t.deviceId]);const a=P.useRef(null),r=P.useRef(0),c=P.useRef(0),m=P.useRef(0),{box:d,fit:h}=Ux(),f=P.useMemo(()=>async k=>{const x=a.current;if(!x)return;const E=++m.current;c.current=performance.now(),Pa("loadAt","start",{epochMs:k,window:S_}),Ri({type:"state",state:"loading"});try{const R=await e.trpcClient.recording.getPlayback.query({deviceId:t.deviceId,provider:t.provider??GLe,fromMs:k,toMs:k+S_});if(E!==m.current){Pa("loadAt","superseded",{epochMs:k});return}if(R?.kind!=="hls"){const j=R?.kind==="clip"?"this source serves clips, not a playable HLS window":R?.reason??"no footage";Pa("loadAt","not-playable-here",{kind:R?.kind??null,why:j}),Ri({type:"state",state:"error",message:j});return}const T=R.manifest;if(Pa("loadAt","manifest",{playbackUrl:T?.playbackUrl??null,endpoints:T?.playbackEndpoints?.length??0,localMaster:!!T?.localMasterPath}),!T?.playbackUrl){Ri({type:"state",state:"error",message:"no footage"});return}x.src=T.playbackUrl;const N=()=>{if(E!==m.current)return;const j=typeof x.getStartDate=="function"?x.getStartDate():null,q=j instanceof Date&&!Number.isNaN(j.getTime())?j.getTime():k;r.current=q;const B=YLe(k,q);if(B>0)try{x.currentTime=B}catch(F){Pa("loadAt","seek-failed",{msg:String(F)})}x.play().catch(F=>{Pa("loadAt","play-rejected",{msg:String(F)})}),Pa("loadAt","seek",{epochMs:k,media0Ms:q,offsetSec:B})};x.readyState>=HTMLMediaElement.HAVE_METADATA?N():x.addEventListener("loadedmetadata",N,{once:!0}),Pa("loadAt","src-set",{src:T.playbackUrl})}catch(R){Pa("loadAt","error",{msg:R instanceof Error?R.message:String(R)}),Ri({type:"state",state:"error",message:R instanceof Error?R.message:String(R)})}},[e,t.deviceId]);return P.useEffect(()=>{Pa("init","mounted",{deviceId:t.deviceId,startMs:t.startMs??null,ua:navigator.userAgent});const k=(x,E)=>{Pa("scrub","unavailable",{command:x,...E===void 0?{}:{epochMs:E}}),Ri({type:"state",state:"error",message:XLe})};return window.__camstackRecording={seekTo:x=>{Pa("cmd","seekTo",{epochMs:x}),f(x)},play:()=>{Pa("cmd","play"),a.current?.play().catch(()=>{})},pause:()=>{Pa("cmd","pause"),a.current?.pause()},setRate:x=>{Pa("cmd","setRate",{rate:x}),a.current&&(a.current.playbackRate=x)},fit:(x,E)=>{Pa("cmd","fit",{w:x,h:E}),h(x,E)},scrubStart:()=>{Pa("cmd","scrubStart"),k("scrubStart")},scrubTo:x=>{Pa("cmd","scrubTo",{epochMs:x}),k("scrubTo",x)},scrubEnd:x=>{Pa("cmd","scrubEnd",{epochMs:x}),k("scrubEnd",x)}},t.startMs&&t.startMs>0&&f(t.startMs),()=>{window.__camstackRecording&&delete window.__camstackRecording}},[f,t.startMs,t.deviceId,h]),P.useEffect(()=>Gm(k=>{const x=window.__camstackRecording;if(!x)return;switch(k.kind){case"seekTo":x.seekTo(k.value);break;case"play":x.play();break;case"pause":x.pause();break;case"setRate":x.setRate(k.value);break;case"scrubStart":x.scrubStart();break;case"scrubTo":x.scrubTo(k.value);break;case"scrubEnd":x.scrubEnd(k.value);break;case"fit":x.fit(k.w,k.h);break}}),[]),v.jsx("div",{style:{position:"fixed",left:0,top:0,width:d.w,height:d.h,background:"#000"},children:v.jsx("video",{ref:a,playsInline:!0,controls:!1,style:{width:"100%",height:"100%",objectFit:"contain",background:"#000"},onLoadedMetadata:k=>Pa("video","loadedmetadata",{w:k.currentTarget.videoWidth,h:k.currentTarget.videoHeight,dur:k.currentTarget.duration}),onPlaying:()=>{Pa("video","playing",{vodStartMs:Math.round(performance.now()-c.current)}),Ri({type:"state",state:"playing"})},onPause:()=>Ri({type:"state",state:"paused"}),onEnded:()=>Ri({type:"state",state:"ended"}),onError:k=>{const x=k.currentTarget.error;Pa("video","error",{code:x?.code??null,message:x?.message??null}),Ri({type:"state",state:"error",message:x?.message||"video error"})},onTimeUpdate:k=>Ri({type:"position",positionMs:r.current+k.currentTarget.currentTime*1e3})})})}function e8e(){const e=Wm("recording",()=>window.__CAMSTACK_RECORDING__,ZLe),t=P.useMemo(()=>e===null||!e.ok?null:(document.cookie=`camstack_session=${e.config.token}; path=/; SameSite=Lax`,xm({serverUrl:e.config.serverUrl,token:e.config.token})),[e]);return P.useEffect(()=>()=>t?.close(),[t]),e===null?null:e.ok?t?v.jsx(JLe,{system:t,config:e.config}):(Ri({type:"state",state:"error",message:"init failed"}),null):(Ri({type:"state",state:"error",message:e.error}),null)}function t8e(e){return e.replace(/\/+$/,"")}function a8e(e,t){const a=e.includes("?")?"&":"?",r=`&size=${Math.round(t)}`;return`${e}${a}variant=thumb${r}`}function n8e(e,t){if(t===void 0||t.length===0)return null;if(t.startsWith("data:")||/^https?:\/\//i.test(t))return t;if(e===null||e.length===0)return null;const a=t8e(e);return t.startsWith("/")?`${a}${t}`:`${a}/${t}`}function i8e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function r8e(e){if(!Array.isArray(e))return[];const t=[];for(const a of e){if(!i8e(a))continue;const r=typeof a.mediaId=="number"?a.mediaId:null,c=typeof a.kind=="string"&&a.kind.length>0?a.kind:null;r===null||c===null||t.push({mediaId:r,kind:c,timestamp:typeof a.timestamp=="number"?a.timestamp:0,...typeof a.url=="string"&&a.url.length>0?{url:a.url}:{},...typeof a.sizeBytes=="number"?{sizeBytes:a.sizeBytes}:{}})}return t}function o8e(e){const t=new URLSearchParams(e),a=t.get("id")?.trim()??"";if(a.length===0)return null;const r=t.get("device")??t.get("deviceId"),c=r!==null&&/^\d+$/.test(r)?Number(r):null,m=t.get("best")??t.get("bestEventId");return{trackId:a,deviceId:c,bestEventId:m!==null&&m.length>0?m:null}}function s8e(e){return/clip|video/i.test(e)}const l8e=240;function c8e(e,t){const a=r8e(e),r=[];let c=null;for(const m of a){const d=n8e(t,m.url);if(d===null)continue;const h=`${m.kind}:${m.mediaId??r.length}`;if(s8e(m.kind)){c===null&&(c={key:h,kind:m.kind,url:d});continue}r.push({key:h,kind:m.kind,url:a8e(d,l8e)})}return{stills:r,clip:c}}function d8e(e,t){const a=Math.max(0,Math.round((t-e)/1e3));if(a<60)return`${a} s`;const r=Math.floor(a/60),c=a%60;return c===0?`${r} min`:`${r} min ${c} s`}const u8e={camera:"Camera",zone:"Zone",time:"Time",loading:"Loading",noCamera:"The track link names no camera (device=)",notFound:"Track not found",loadFailed:"Failed to load the track",noTrack:"The track link names no track (id=)",configError:"Track embed config error"},m8e={camera:"Camera",zone:"Zona",time:"Ora",loading:"Caricamento",noCamera:"Il link della traccia non indica la camera (device=)",notFound:"Traccia non trovata",loadFailed:"Impossibile caricare la traccia",noTrack:"Il link non indica nessuna traccia (id=)",configError:"Errore di configurazione dell’embed traccia"};function Qx(e){return e==="it"?m8e:u8e}const w_=320;async function p8e(e,t,a,r,c){if(t.deviceId===null)return{status:"error",message:c.noCamera};const m=new Map(a!==void 0?[[t.deviceId,a]]:[]),[d,h]=await Promise.all([e.trpcClient.pipelineAnalytics.getTrack.query({deviceId:t.deviceId,trackId:t.trackId}),e.trpcClient.pipelineAnalytics.listTrackMedia.query({deviceId:t.deviceId,trackId:t.trackId}).catch(()=>[])]),f=W8(d,m);return f===null?{status:"error",message:c.notFound}:{status:"ready",row:f,media:c8e(h,r)}}function x_({url:e,token:t,palette:a,style:r,alt:c}){const m=p7(e,t),d={background:a.skeleton,border:`1px solid ${a.border}`,borderRadius:10,overflow:"hidden",boxSizing:"border-box",...r};return m.status!=="ready"?v.jsx("div",{style:d,role:"img","aria-label":c}):v.jsx("div",{style:d,children:v.jsx("img",{src:m.src,alt:c,style:{width:"100%",height:"100%",objectFit:"contain",display:"block"}})})}function O7(e){return Bx(e.locale,typeof navigator>"u"?void 0:navigator.language)}function h8e({row:e,media:t,config:a,palette:r}){const c=pd(),m=O7(a),d=Qx(m),h=P.useMemo(()=>B8(a.labels,m),[a.labels,m]),f=P.useMemo(()=>Object.keys(a.kindLabels).length>0?H8(a.kindLabels):Kg,[a.kindLabels]),k=Z8(e,f),x=sw(e.className,ig(e),c),E=jS(U8(e.className,new Map,ig(e))),[R,T]=P.useState(null),N=t.stills.find(F=>F.key===R)?.url.replace(/&size=\d+/,`&size=${w_}`)??Nx(a.serverUrl,e.trackId,w_),j=e.zoneNames.length>0?e.zoneNames:[],q=[];e.active&&q.push(h.active),e.favourited===!0&&q.push(h.favourite),e.debug===!0&&q.push(h.debug),e.markForTrain===!0&&q.push(h.train);const B={background:r.chip,color:r.text,borderRadius:999,padding:"2px 10px",fontSize:12,lineHeight:"18px"};return v.jsxs("main",{"data-testid":"track-detail",style:{minHeight:"100%",boxSizing:"border-box",background:r.background,color:r.text,fontFamily:"system-ui, sans-serif",padding:12,display:"flex",flexDirection:"column",gap:12,maxWidth:720,margin:"0 auto"},children:[v.jsx(x_,{url:N,token:a.token,palette:r,alt:k.text,style:{width:"100%",aspectRatio:"4 / 3"}}),t.clip!==null&&a.token===void 0&&v.jsx("video",{"data-testid":"track-clip",src:t.clip.url,controls:!0,preload:"none",style:{width:"100%",borderRadius:10,background:r.skeleton}}),t.stills.length>1&&v.jsx("div",{"data-testid":"track-strip",style:{display:"flex",gap:8,overflowX:"auto",paddingBottom:2},children:t.stills.map(F=>v.jsx("button",{type:"button",onClick:()=>T(F.key),"aria-label":F.kind,style:{all:"unset",cursor:"pointer",flex:"0 0 auto",outline:F.key===R?`2px solid ${x}`:"none",borderRadius:10},children:v.jsx(x_,{url:F.url,token:a.token,palette:r,alt:F.kind,style:{width:84,height:84}})},F.key))}),v.jsxs("section",{style:{display:"flex",flexDirection:"column",gap:8},children:[v.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[v.jsx(E,{size:20,color:x,"aria-hidden":!0}),v.jsx("h1",{style:{fontSize:18,lineHeight:"24px",margin:0,fontWeight:600},children:k.fullText??k.text})]}),q.length>0&&v.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:q.map(F=>v.jsx("span",{style:B,children:F},F))}),v.jsxs("dl",{style:{margin:0,display:"grid",gridTemplateColumns:"auto 1fr",gap:"4px 12px",fontSize:13},children:[v.jsx("dt",{style:{color:r.textMuted},children:d.camera}),v.jsx("dd",{style:{margin:0},children:e.cameraName}),j.length>0&&v.jsxs(v.Fragment,{children:[v.jsx("dt",{style:{color:r.textMuted},children:d.zone}),v.jsx("dd",{style:{margin:0},children:j.join(", ")})]}),v.jsx("dt",{style:{color:r.textMuted},children:d.time}),v.jsxs("dd",{style:{margin:0},children:[cDe(e.lastSeen,Date.now(),m)," · ",d8e(e.firstSeen,e.lastSeen)]})]})]})]})}function lg({message:e,palette:t}){return v.jsx("div",{role:"status",style:{position:"fixed",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:t.background,color:t.textMuted,fontFamily:"system-ui, sans-serif",fontSize:13,padding:16,textAlign:"center"},children:e})}function f8e({config:e,query:t,palette:a}){const r=P.useMemo(()=>xm({serverUrl:e.serverUrl,token:e.token}),[e.serverUrl,e.token]);P.useEffect(()=>()=>r.close(),[r]);const[c,m]=P.useState({status:"loading"}),d=Qx(O7(e));return P.useEffect(()=>{let h=!0;return p8e(r,t,e.deviceNames[String(t.deviceId)],e.serverUrl,d).then(f=>h&&m(f)).catch(f=>h&&m({status:"error",message:f instanceof Error?f.message:d.loadFailed})),()=>{h=!1}},[r,t,e.deviceNames,e.serverUrl,d]),v.jsxs(v.Fragment,{children:[v.jsx(Wg,{system:r}),c.status==="loading"&&v.jsx(lg,{message:d.loading,palette:a}),c.status==="error"&&v.jsx(lg,{message:c.message,palette:a}),c.status==="ready"&&v.jsx(h8e,{row:c.row,media:c.media,config:e,palette:a})]})}function g8e(){const e=Wm("events",()=>window.__CAMSTACK_EVENTS__,Fx,y7,{urlFirst:!0}),t=P.useMemo(()=>o8e(location.search),[]),a=Ox(e!==null&&e.ok?e.config.theme:"auto",window.matchMedia?.("(prefers-color-scheme: dark)").matches??!0);if(e===null)return null;const r=Qx(Bx(e.ok?e.config.locale:void 0,typeof navigator>"u"?void 0:navigator.language));return e.ok?t===null?v.jsx(lg,{message:r.noTrack,palette:a}):v.jsx(f8e,{config:e.config,query:t,palette:a}):v.jsx(lg,{message:`${r.configError}: ${e.error}`,palette:a})}function v8e(){const e=window.__CAMSTACK_EMBED_MODE__??new URLSearchParams(location.search).get("mode")??new URLSearchParams(location.hash.replace(/^#/,"")).get("mode")??"grid";return e==="player"?v.jsx(KLe,{}):e==="recording"?v.jsx(e8e,{}):e==="events"?v.jsx(Wze,{}):e==="track"?v.jsx(g8e,{}):v.jsx(uLe,{})}const M_=document.getElementById("root");M_&&KB.createRoot(M_).render(v.jsx(v8e,{}));export{U3e as C,Nq as E,C8e as G,Dq as I,A8e as M,SIe as R,Hm as S,N8e as T,E8e as W,GIe as a,q8e as b,X as c,zIe as d,cs as e,R8e as f,z8e as g,j8e as h,T8e as i,v as j,O8e as k,R1 as l,I8e as m,kw as n,$B as o,qB as p,Xa as q,P as r,D8e as s,Vm as u,ff as v};