@camstack/addon-pipeline-orchestrator 1.2.161 → 1.2.162

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./MotionZonesSettings-DNdnFHso-2_mSC4yb.js","./MaskShapeCanvas-DI4BY7W2-MTA0w1Gf.js","./PrivacyMaskSettings-DNSLc6ww-BjMyK6YA.js","./SceneMonitorEditor-d_A4kO-M-B7egu1hV.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./MotionZonesSettings-DNdnFHso-P9zbA9fe.js","./MaskShapeCanvas-DI4BY7W2-D2YOCxqL.js","./PrivacyMaskSettings-DNSLc6ww-DRxNCXl7.js","./SceneMonitorEditor-d_A4kO-M-DMBYwDxO.js"])))=>i.map(i=>d[i]);
2
2
  function _j(e,t){for(var n=0;n<t.length;n++){const a=t[n];if(typeof a!="string"&&!Array.isArray(a)){for(const o in a)if(o!=="default"&&!(o in e)){const p=Object.getOwnPropertyDescriptor(a,o);p&&Object.defineProperty(e,o,p.get?p:{enumerable:!0,get:()=>a[o]})}}}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 o of document.querySelectorAll('link[rel="modulepreload"]'))a(o);new MutationObserver(o=>{for(const p of o)if(p.type==="childList")for(const f of p.addedNodes)f.tagName==="LINK"&&f.rel==="modulepreload"&&a(f)}).observe(document,{childList:!0,subtree:!0});function n(o){const p={};return o.integrity&&(p.integrity=o.integrity),o.referrerPolicy&&(p.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?p.credentials="include":o.crossOrigin==="anonymous"?p.credentials="omit":p.credentials="same-origin",p}function a(o){if(o.ep)return;o.ep=!0;const p=n(o);fetch(o.href,p)}})();function Tj(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Dh={exports:{}},ic={};var lk;function Ij(){if(lk)return ic;lk=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(a,o,p){var f=null;if(p!==void 0&&(f=""+p),o.key!==void 0&&(f=""+o.key),"key"in o){p={};for(var m in o)m!=="key"&&(p[m]=o[m])}else p=o;return o=p.ref,{$$typeof:e,type:a,key:f,ref:o!==void 0?o:null,props:p}}return ic.Fragment=t,ic.jsx=n,ic.jsxs=n,ic}var ck;function Nj(){return ck||(ck=1,Dh.exports=Ij()),Dh.exports}var v=Nj(),zh={exports:{}},rc={},Lh={exports:{}},qh={};var uk;function Oj(){return uk||(uk=1,(function(e){function t(F,ue){var ke=F.length;F.push(ue);e:for(;0<ke;){var Ee=ke-1>>>1,fe=F[Ee];if(0<o(fe,ue))F[Ee]=ue,F[ke]=fe,ke=Ee;else break e}}function n(F){return F.length===0?null:F[0]}function a(F){if(F.length===0)return null;var ue=F[0],ke=F.pop();if(ke!==ue){F[0]=ke;e:for(var Ee=0,fe=F.length,L=fe>>>1;Ee<L;){var ee=2*(Ee+1)-1,me=F[ee],be=ee+1,X=F[be];if(0>o(me,ke))be<fe&&0>o(X,me)?(F[Ee]=X,F[be]=ke,Ee=be):(F[Ee]=me,F[ee]=ke,Ee=ee);else if(be<fe&&0>o(X,ke))F[Ee]=X,F[be]=ke,Ee=be;else break e}}return ue}function o(F,ue){var ke=F.sortIndex-ue.sortIndex;return ke!==0?ke:F.id-ue.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var p=performance;e.unstable_now=function(){return p.now()}}else{var f=Date,m=f.now();e.unstable_now=function(){return f.now()-m}}var h=[],u=[],x=1,w=null,C=3,A=!1,R=!1,I=!1,O=!1,D=typeof setTimeout=="function"?setTimeout:null,z=typeof clearTimeout=="function"?clearTimeout:null,B=typeof setImmediate<"u"?setImmediate:null;function q(F){for(var ue=n(u);ue!==null;){if(ue.callback===null)a(u);else if(ue.startTime<=F)a(u),ue.sortIndex=ue.expirationTime,t(h,ue);else break;ue=n(u)}}function G(F){if(I=!1,q(F),!R)if(n(h)!==null)R=!0,ae||(ae=!0,Ae());else{var ue=n(u);ue!==null&&Te(G,ue.startTime-F)}}var ae=!1,Q=-1,H=5,oe=-1;function we(){return O?!0:!(e.unstable_now()-oe<H)}function Me(){if(O=!1,ae){var F=e.unstable_now();oe=F;var ue=!0;try{e:{R=!1,I&&(I=!1,z(Q),Q=-1),A=!0;var ke=C;try{t:{for(q(F),w=n(h);w!==null&&!(w.expirationTime>F&&we());){var Ee=w.callback;if(typeof Ee=="function"){w.callback=null,C=w.priorityLevel;var fe=Ee(w.expirationTime<=F);if(F=e.unstable_now(),typeof fe=="function"){w.callback=fe,q(F),ue=!0;break t}w===n(h)&&a(h),q(F)}else a(h);w=n(h)}if(w!==null)ue=!0;else{var L=n(u);L!==null&&Te(G,L.startTime-F),ue=!1}}break e}finally{w=null,C=ke,A=!1}ue=void 0}}finally{ue?Ae():ae=!1}}}var Ae;if(typeof B=="function")Ae=function(){B(Me)};else if(typeof MessageChannel<"u"){var Ce=new MessageChannel,re=Ce.port2;Ce.port1.onmessage=Me,Ae=function(){re.postMessage(null)}}else Ae=function(){D(Me,0)};function Te(F,ue){Q=D(function(){F(e.unstable_now())},ue)}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(F){F.callback=null},e.unstable_forceFrameRate=function(F){0>F||125<F?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<F?Math.floor(1e3/F):5},e.unstable_getCurrentPriorityLevel=function(){return C},e.unstable_next=function(F){switch(C){case 1:case 2:case 3:var ue=3;break;default:ue=C}var ke=C;C=ue;try{return F()}finally{C=ke}},e.unstable_requestPaint=function(){O=!0},e.unstable_runWithPriority=function(F,ue){switch(F){case 1:case 2:case 3:case 4:case 5:break;default:F=3}var ke=C;C=F;try{return ue()}finally{C=ke}},e.unstable_scheduleCallback=function(F,ue,ke){var Ee=e.unstable_now();switch(typeof ke=="object"&&ke!==null?(ke=ke.delay,ke=typeof ke=="number"&&0<ke?Ee+ke:Ee):ke=Ee,F){case 1:var fe=-1;break;case 2:fe=250;break;case 5:fe=1073741823;break;case 4:fe=1e4;break;default:fe=5e3}return fe=ke+fe,F={id:x++,callback:ue,priorityLevel:F,startTime:ke,expirationTime:fe,sortIndex:-1},ke>Ee?(F.sortIndex=ke,t(u,F),n(h)===null&&F===n(u)&&(I?(z(Q),Q=-1):I=!0,Te(G,ke-Ee))):(F.sortIndex=fe,t(h,F),R||A||(R=!0,ae||(ae=!0,Ae()))),F},e.unstable_shouldYield=we,e.unstable_wrapCallback=function(F){var ue=C;return function(){var ke=C;C=ue;try{return F.apply(this,arguments)}finally{C=ke}}}})(qh)),qh}var dk;function jj(){return dk||(dk=1,Lh.exports=Oj()),Lh.exports}var Bh={exports:{}},et={};var pk;function Pj(){if(pk)return et;pk=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),a=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),p=Symbol.for("react.consumer"),f=Symbol.for("react.context"),m=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),u=Symbol.for("react.memo"),x=Symbol.for("react.lazy"),w=Symbol.for("react.activity"),C=Symbol.iterator;function A(L){return L===null||typeof L!="object"?null:(L=C&&L[C]||L["@@iterator"],typeof L=="function"?L:null)}var R={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},I=Object.assign,O={};function D(L,ee,me){this.props=L,this.context=ee,this.refs=O,this.updater=me||R}D.prototype.isReactComponent={},D.prototype.setState=function(L,ee){if(typeof L!="object"&&typeof L!="function"&&L!=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,L,ee,"setState")},D.prototype.forceUpdate=function(L){this.updater.enqueueForceUpdate(this,L,"forceUpdate")};function z(){}z.prototype=D.prototype;function B(L,ee,me){this.props=L,this.context=ee,this.refs=O,this.updater=me||R}var q=B.prototype=new z;q.constructor=B,I(q,D.prototype),q.isPureReactComponent=!0;var G=Array.isArray;function ae(){}var Q={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function oe(L,ee,me){var be=me.ref;return{$$typeof:e,type:L,key:ee,ref:be!==void 0?be:null,props:me}}function we(L,ee){return oe(L.type,ee,L.props)}function Me(L){return typeof L=="object"&&L!==null&&L.$$typeof===e}function Ae(L){var ee={"=":"=0",":":"=2"};return"$"+L.replace(/[=:]/g,function(me){return ee[me]})}var Ce=/\/+/g;function re(L,ee){return typeof L=="object"&&L!==null&&L.key!=null?Ae(""+L.key):ee.toString(36)}function Te(L){switch(L.status){case"fulfilled":return L.value;case"rejected":throw L.reason;default:switch(typeof L.status=="string"?L.then(ae,ae):(L.status="pending",L.then(function(ee){L.status==="pending"&&(L.status="fulfilled",L.value=ee)},function(ee){L.status==="pending"&&(L.status="rejected",L.reason=ee)})),L.status){case"fulfilled":return L.value;case"rejected":throw L.reason}}throw L}function F(L,ee,me,be,X){var xe=typeof L;(xe==="undefined"||xe==="boolean")&&(L=null);var Oe=!1;if(L===null)Oe=!0;else switch(xe){case"bigint":case"string":case"number":Oe=!0;break;case"object":switch(L.$$typeof){case e:case t:Oe=!0;break;case x:return Oe=L._init,F(Oe(L._payload),ee,me,be,X)}}if(Oe)return X=X(L),Oe=be===""?"."+re(L,0):be,G(X)?(me="",Oe!=null&&(me=Oe.replace(Ce,"$&/")+"/"),F(X,ee,me,"",function(Be){return Be})):X!=null&&(Me(X)&&(X=we(X,me+(X.key==null||L&&L.key===X.key?"":(""+X.key).replace(Ce,"$&/")+"/")+Oe)),ee.push(X)),1;Oe=0;var le=be===""?".":be+":";if(G(L))for(var ye=0;ye<L.length;ye++)be=L[ye],xe=le+re(be,ye),Oe+=F(be,ee,me,xe,X);else if(ye=A(L),typeof ye=="function")for(L=ye.call(L),ye=0;!(be=L.next()).done;)be=be.value,xe=le+re(be,ye++),Oe+=F(be,ee,me,xe,X);else if(xe==="object"){if(typeof L.then=="function")return F(Te(L),ee,me,be,X);throw ee=String(L),Error("Objects are not valid as a React child (found: "+(ee==="[object Object]"?"object with keys {"+Object.keys(L).join(", ")+"}":ee)+"). If you meant to render a collection of children, use an array instead.")}return Oe}function ue(L,ee,me){if(L==null)return L;var be=[],X=0;return F(L,be,"","",function(xe){return ee.call(me,xe,X++)}),be}function ke(L){if(L._status===-1){var ee=L._result;ee=ee(),ee.then(function(me){(L._status===0||L._status===-1)&&(L._status=1,L._result=me)},function(me){(L._status===0||L._status===-1)&&(L._status=2,L._result=me)}),L._status===-1&&(L._status=0,L._result=ee)}if(L._status===1)return L._result.default;throw L._result}var Ee=typeof reportError=="function"?reportError:function(L){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var ee=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof L=="object"&&L!==null&&typeof L.message=="string"?String(L.message):String(L),error:L});if(!window.dispatchEvent(ee))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",L);return}console.error(L)},fe={map:ue,forEach:function(L,ee,me){ue(L,function(){ee.apply(this,arguments)},me)},count:function(L){var ee=0;return ue(L,function(){ee++}),ee},toArray:function(L){return ue(L,function(ee){return ee})||[]},only:function(L){if(!Me(L))throw Error("React.Children.only expected to receive a single React element child.");return L}};return et.Activity=w,et.Children=fe,et.Component=D,et.Fragment=n,et.Profiler=o,et.PureComponent=B,et.StrictMode=a,et.Suspense=h,et.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=Q,et.__COMPILER_RUNTIME={__proto__:null,c:function(L){return Q.H.useMemoCache(L)}},et.cache=function(L){return function(){return L.apply(null,arguments)}},et.cacheSignal=function(){return null},et.cloneElement=function(L,ee,me){if(L==null)throw Error("The argument must be a React element, but you passed "+L+".");var be=I({},L.props),X=L.key;if(ee!=null)for(xe in ee.key!==void 0&&(X=""+ee.key),ee)!H.call(ee,xe)||xe==="key"||xe==="__self"||xe==="__source"||xe==="ref"&&ee.ref===void 0||(be[xe]=ee[xe]);var xe=arguments.length-2;if(xe===1)be.children=me;else if(1<xe){for(var Oe=Array(xe),le=0;le<xe;le++)Oe[le]=arguments[le+2];be.children=Oe}return oe(L.type,X,be)},et.createContext=function(L){return L={$$typeof:f,_currentValue:L,_currentValue2:L,_threadCount:0,Provider:null,Consumer:null},L.Provider=L,L.Consumer={$$typeof:p,_context:L},L},et.createElement=function(L,ee,me){var be,X={},xe=null;if(ee!=null)for(be in ee.key!==void 0&&(xe=""+ee.key),ee)H.call(ee,be)&&be!=="key"&&be!=="__self"&&be!=="__source"&&(X[be]=ee[be]);var Oe=arguments.length-2;if(Oe===1)X.children=me;else if(1<Oe){for(var le=Array(Oe),ye=0;ye<Oe;ye++)le[ye]=arguments[ye+2];X.children=le}if(L&&L.defaultProps)for(be in Oe=L.defaultProps,Oe)X[be]===void 0&&(X[be]=Oe[be]);return oe(L,xe,X)},et.createRef=function(){return{current:null}},et.forwardRef=function(L){return{$$typeof:m,render:L}},et.isValidElement=Me,et.lazy=function(L){return{$$typeof:x,_payload:{_status:-1,_result:L},_init:ke}},et.memo=function(L,ee){return{$$typeof:u,type:L,compare:ee===void 0?null:ee}},et.startTransition=function(L){var ee=Q.T,me={};Q.T=me;try{var be=L(),X=Q.S;X!==null&&X(me,be),typeof be=="object"&&be!==null&&typeof be.then=="function"&&be.then(ae,Ee)}catch(xe){Ee(xe)}finally{ee!==null&&me.types!==null&&(ee.types=me.types),Q.T=ee}},et.unstable_useCacheRefresh=function(){return Q.H.useCacheRefresh()},et.use=function(L){return Q.H.use(L)},et.useActionState=function(L,ee,me){return Q.H.useActionState(L,ee,me)},et.useCallback=function(L,ee){return Q.H.useCallback(L,ee)},et.useContext=function(L){return Q.H.useContext(L)},et.useDebugValue=function(){},et.useDeferredValue=function(L,ee){return Q.H.useDeferredValue(L,ee)},et.useEffect=function(L,ee){return Q.H.useEffect(L,ee)},et.useEffectEvent=function(L){return Q.H.useEffectEvent(L)},et.useId=function(){return Q.H.useId()},et.useImperativeHandle=function(L,ee,me){return Q.H.useImperativeHandle(L,ee,me)},et.useInsertionEffect=function(L,ee){return Q.H.useInsertionEffect(L,ee)},et.useLayoutEffect=function(L,ee){return Q.H.useLayoutEffect(L,ee)},et.useMemo=function(L,ee){return Q.H.useMemo(L,ee)},et.useOptimistic=function(L,ee){return Q.H.useOptimistic(L,ee)},et.useReducer=function(L,ee,me){return Q.H.useReducer(L,ee,me)},et.useRef=function(L){return Q.H.useRef(L)},et.useState=function(L){return Q.H.useState(L)},et.useSyncExternalStore=function(L,ee,me){return Q.H.useSyncExternalStore(L,ee,me)},et.useTransition=function(){return Q.H.useTransition()},et.version="19.2.3",et}var mk;function Yy(){return mk||(mk=1,Bh.exports=Pj()),Bh.exports}var Uh={exports:{}},qn={};var fk;function Dj(){if(fk)return qn;fk=1;var e=Yy();function t(h){var u="https://react.dev/errors/"+h;if(1<arguments.length){u+="?args[]="+encodeURIComponent(arguments[1]);for(var x=2;x<arguments.length;x++)u+="&args[]="+encodeURIComponent(arguments[x])}return"Minified React error #"+h+"; visit "+u+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function n(){}var a={d:{f:n,r:function(){throw Error(t(522))},D:n,C:n,L:n,m:n,X:n,S:n,M:n},p:0,findDOMNode:null},o=Symbol.for("react.portal");function p(h,u,x){var w=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:o,key:w==null?null:""+w,children:h,containerInfo:u,implementation:x}}var f=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function m(h,u){if(h==="font")return"";if(typeof u=="string")return u==="use-credentials"?u:""}return qn.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=a,qn.createPortal=function(h,u){var x=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!u||u.nodeType!==1&&u.nodeType!==9&&u.nodeType!==11)throw Error(t(299));return p(h,u,null,x)},qn.flushSync=function(h){var u=f.T,x=a.p;try{if(f.T=null,a.p=2,h)return h()}finally{f.T=u,a.p=x,a.d.f()}},qn.preconnect=function(h,u){typeof h=="string"&&(u?(u=u.crossOrigin,u=typeof u=="string"?u==="use-credentials"?u:"":void 0):u=null,a.d.C(h,u))},qn.prefetchDNS=function(h){typeof h=="string"&&a.d.D(h)},qn.preinit=function(h,u){if(typeof h=="string"&&u&&typeof u.as=="string"){var x=u.as,w=m(x,u.crossOrigin),C=typeof u.integrity=="string"?u.integrity:void 0,A=typeof u.fetchPriority=="string"?u.fetchPriority:void 0;x==="style"?a.d.S(h,typeof u.precedence=="string"?u.precedence:void 0,{crossOrigin:w,integrity:C,fetchPriority:A}):x==="script"&&a.d.X(h,{crossOrigin:w,integrity:C,fetchPriority:A,nonce:typeof u.nonce=="string"?u.nonce:void 0})}},qn.preinitModule=function(h,u){if(typeof h=="string")if(typeof u=="object"&&u!==null){if(u.as==null||u.as==="script"){var x=m(u.as,u.crossOrigin);a.d.M(h,{crossOrigin:x,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0})}}else u==null&&a.d.M(h)},qn.preload=function(h,u){if(typeof h=="string"&&typeof u=="object"&&u!==null&&typeof u.as=="string"){var x=u.as,w=m(x,u.crossOrigin);a.d.L(h,x,{crossOrigin:w,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0,type:typeof u.type=="string"?u.type:void 0,fetchPriority:typeof u.fetchPriority=="string"?u.fetchPriority:void 0,referrerPolicy:typeof u.referrerPolicy=="string"?u.referrerPolicy:void 0,imageSrcSet:typeof u.imageSrcSet=="string"?u.imageSrcSet:void 0,imageSizes:typeof u.imageSizes=="string"?u.imageSizes:void 0,media:typeof u.media=="string"?u.media:void 0})}},qn.preloadModule=function(h,u){if(typeof h=="string")if(u){var x=m(u.as,u.crossOrigin);a.d.m(h,{as:typeof u.as=="string"&&u.as!=="script"?u.as:void 0,crossOrigin:x,integrity:typeof u.integrity=="string"?u.integrity:void 0})}else a.d.m(h)},qn.requestFormReset=function(h){a.d.r(h)},qn.unstable_batchedUpdates=function(h,u){return h(u)},qn.useFormState=function(h,u,x){return f.H.useFormState(h,u,x)},qn.useFormStatus=function(){return f.H.useHostTransitionStatus()},qn.version="19.2.3",qn}var hk;function OA(){if(hk)return Uh.exports;hk=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(),Uh.exports=Dj(),Uh.exports}var gk;function zj(){if(gk)return rc;gk=1;var e=jj(),t=Yy(),n=OA();function a(i){var r="https://react.dev/errors/"+i;if(1<arguments.length){r+="?args[]="+encodeURIComponent(arguments[1]);for(var c=2;c<arguments.length;c++)r+="&args[]="+encodeURIComponent(arguments[c])}return"Minified React error #"+i+"; visit "+r+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function o(i){return!(!i||i.nodeType!==1&&i.nodeType!==9&&i.nodeType!==11)}function p(i){var r=i,c=i;if(i.alternate)for(;r.return;)r=r.return;else{i=r;do r=i,(r.flags&4098)!==0&&(c=r.return),i=r.return;while(i)}return r.tag===3?c:null}function f(i){if(i.tag===13){var r=i.memoizedState;if(r===null&&(i=i.alternate,i!==null&&(r=i.memoizedState)),r!==null)return r.dehydrated}return null}function m(i){if(i.tag===31){var r=i.memoizedState;if(r===null&&(i=i.alternate,i!==null&&(r=i.memoizedState)),r!==null)return r.dehydrated}return null}function h(i){if(p(i)!==i)throw Error(a(188))}function u(i){var r=i.alternate;if(!r){if(r=p(i),r===null)throw Error(a(188));return r!==i?null:i}for(var c=i,g=r;;){var b=c.return;if(b===null)break;var k=b.alternate;if(k===null){if(g=b.return,g!==null){c=g;continue}break}if(b.child===k.child){for(k=b.child;k;){if(k===c)return h(b),i;if(k===g)return h(b),r;k=k.sibling}throw Error(a(188))}if(c.return!==g.return)c=b,g=k;else{for(var _=!1,P=b.child;P;){if(P===c){_=!0,c=b,g=k;break}if(P===g){_=!0,g=b,c=k;break}P=P.sibling}if(!_){for(P=k.child;P;){if(P===c){_=!0,c=k,g=b;break}if(P===g){_=!0,g=k,c=b;break}P=P.sibling}if(!_)throw Error(a(189))}}if(c.alternate!==g)throw Error(a(190))}if(c.tag!==3)throw Error(a(188));return c.stateNode.current===c?i:r}function x(i){var r=i.tag;if(r===5||r===26||r===27||r===6)return i;for(i=i.child;i!==null;){if(r=x(i),r!==null)return r;i=i.sibling}return null}var w=Object.assign,C=Symbol.for("react.element"),A=Symbol.for("react.transitional.element"),R=Symbol.for("react.portal"),I=Symbol.for("react.fragment"),O=Symbol.for("react.strict_mode"),D=Symbol.for("react.profiler"),z=Symbol.for("react.consumer"),B=Symbol.for("react.context"),q=Symbol.for("react.forward_ref"),G=Symbol.for("react.suspense"),ae=Symbol.for("react.suspense_list"),Q=Symbol.for("react.memo"),H=Symbol.for("react.lazy"),oe=Symbol.for("react.activity"),we=Symbol.for("react.memo_cache_sentinel"),Me=Symbol.iterator;function Ae(i){return i===null||typeof i!="object"?null:(i=Me&&i[Me]||i["@@iterator"],typeof i=="function"?i:null)}var Ce=Symbol.for("react.client.reference");function re(i){if(i==null)return null;if(typeof i=="function")return i.$$typeof===Ce?null:i.displayName||i.name||null;if(typeof i=="string")return i;switch(i){case I:return"Fragment";case D:return"Profiler";case O:return"StrictMode";case G:return"Suspense";case ae:return"SuspenseList";case oe:return"Activity"}if(typeof i=="object")switch(i.$$typeof){case R:return"Portal";case B:return i.displayName||"Context";case z:return(i._context.displayName||"Context")+".Consumer";case q:var r=i.render;return i=i.displayName,i||(i=r.displayName||r.name||"",i=i!==""?"ForwardRef("+i+")":"ForwardRef"),i;case Q:return r=i.displayName||null,r!==null?r:re(i.type)||"Memo";case H:r=i._payload,i=i._init;try{return re(i(r))}catch{}}return null}var Te=Array.isArray,F=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ue=n.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ke={pending:!1,data:null,method:null,action:null},Ee=[],fe=-1;function L(i){return{current:i}}function ee(i){0>fe||(i.current=Ee[fe],Ee[fe]=null,fe--)}function me(i,r){fe++,Ee[fe]=i.current,i.current=r}var be=L(null),X=L(null),xe=L(null),Oe=L(null);function le(i,r){switch(me(xe,r),me(X,i),me(be,null),r.nodeType){case 9:case 11:i=(i=r.documentElement)&&(i=i.namespaceURI)?Ix(i):0;break;default:if(i=r.tagName,r=r.namespaceURI)r=Ix(r),i=Nx(r,i);else switch(i){case"svg":i=1;break;case"math":i=2;break;default:i=0}}ee(be),me(be,i)}function ye(){ee(be),ee(X),ee(xe)}function Be(i){i.memoizedState!==null&&me(Oe,i);var r=be.current,c=Nx(r,i.type);r!==c&&(me(X,i),me(be,c))}function ot(i){X.current===i&&(ee(be),ee(X)),Oe.current===i&&(ee(Oe),ec._currentValue=ke)}var Ve,Ie;function bt(i){if(Ve===void 0)try{throw Error()}catch(c){var r=c.stack.trim().match(/\n( *(at )?)/);Ve=r&&r[1]||"",Ie=-1<c.stack.indexOf(`
3
3
  at`)?" (<anonymous>)":-1<c.stack.indexOf("@")?"@unknown:0:0":""}return`
4
4
  `+Ve+i+Ie}var Re=!1;function Le(i,r){if(!i||Re)return"";Re=!0;var c=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var g={DetermineComponentFrameRoot:function(){try{if(r){var Se=function(){throw Error()};if(Object.defineProperty(Se.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Se,[])}catch(de){var ie=de}Reflect.construct(i,[],Se)}else{try{Se.call()}catch(de){ie=de}i.call(Se.prototype)}}else{try{throw Error()}catch(de){ie=de}(Se=i())&&typeof Se.catch=="function"&&Se.catch(function(){})}}catch(de){if(de&&ie&&typeof de.stack=="string")return[de.stack,ie.stack]}return[null,null]}};g.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var b=Object.getOwnPropertyDescriptor(g.DetermineComponentFrameRoot,"name");b&&b.configurable&&Object.defineProperty(g.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var k=g.DetermineComponentFrameRoot(),_=k[0],P=k[1];if(_&&P){var U=_.split(`
@@ -78,7 +78,7 @@ ${n.slice(0,5).join(`
78
78
  })`,{filename:R,importModuleDynamically:w.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER??Ps});let O;O=(await Ps("node:module")).createRequire(h.protocol==="file:"||h.protocol==="node:"?h.href:x.join(process.cwd(),"__mf_require_base__.js")),I.runInThisContext()(C.exports,C.module,O,A,R);const D=C.module.exports||C.exports;if(n&&D&&n.globalName){t(void 0,D[n.globalName]||D);return}t(void 0,D)}catch(u){t(u instanceof Error?u:new Error(`Script execution error: ${u}`))}};p().then(async m=>{if(n?.type==="esm"||n?.type==="module")return My(o.href,{fetch:m,vm:await Ps("vm")}).then(async h=>{await h.evaluate(),t(void 0,h.namespace)}).catch(h=>{t(h instanceof Error?h:new Error(`Script execution error: ${h}`))});f(m,o)}).catch(m=>{t(m)})}:(e,t,n,a)=>{t(new Error("createScriptNode is disabled in non-Node.js environment"))},ene=typeof ENV_TARGET>"u"||ENV_TARGET!=="web"?(e,t)=>new Promise((n,a)=>{Jte(e,(o,p)=>{if(o)a(o);else{const f=t?.attrs?.globalName||`__FEDERATION_${t?.attrs?.name}:custom__`;n(globalThis[f]=p)}},t.attrs,t.loaderHook)}):(e,t)=>{throw new Error("loadScriptNode is disabled in non-Node.js environment")},Ig=new Map;async function My(e,t){if(Ig.has(e))return Ig.get(e);const{fetch:n,vm:a}=t,o=await(await n(e)).text(),p=new a.SourceTextModule(o,{importModuleDynamically:async(f,m)=>{const h=new URL(f,e).href;return My(h,t)}});return Ig.set(e,p),await p.link(async f=>{const m=new URL(f,e).href;return await My(m,t)}),p}var tne=e=>`View the docs to see how to solve: https://module-federation.io/guide/troubleshooting/${e.split("-")[0].toLowerCase()}#${e.toLowerCase()}`,SI=(e,t,n,a)=>{const o=[`${[t[e]]} #${e}`];return n&&o.push(`args: ${JSON.stringify(n)}`),o.push(tne(e)),a&&o.push(`Original Error Message:
79
79
  ${a}`),o.join(`
80
80
  `)};function nne(e,t,n,a,o,p){return a(SI(e,t,n,o))}var Mo="[ Federation Runtime ]",Cy=Zte(Mo);function Zi(e,t,n,a,o){e||Xt(t)}function Xt(e,t,n,a,o){if(t!==void 0)return nne(e,t,n??{},f=>{throw new Error(`${Mo}: ${f}`)},a);const p=e;throw p instanceof Error?(p.message.startsWith(Mo)||(p.message=`${Mo}: ${p.message}`),p):new Error(`${Mo}: ${p}`)}function $c(e){e instanceof Error&&(e.message.startsWith(Mo)||(e.message=`${Mo}: ${e.message}`)),Cy.warn(e)}function ane(e,t){return e.findIndex(n=>n===t)===-1&&e.push(t),e}function Kp(e){return"version"in e&&e.version?`${e.name}:${e.version}`:"entry"in e&&e.entry?`${e.name}:${e.entry}`:`${e.name}`}function i0(e){return typeof e.entry<"u"}function xI(e){return!e.entry.includes(".json")}function r0(e){return e&&typeof e=="object"}var ine=Object.prototype.toString;function rne(e){return ine.call(e)==="[object Object]"}function kI(e){return Array.isArray(e)?e:[e]}function wI(e){const t={url:"",type:"global",globalName:""};return Vr||dI()||!("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 one=(e,t)=>{let n;return e.endsWith("/")?n=e.slice(0,-1):n=e,t.startsWith(".")&&(t=t.slice(1)),n=n+t,n},Dn=typeof globalThis=="object"?globalThis:window,Va=(()=>{try{return document.defaultView}catch{return Dn}})(),Qc=Va;function hp(e,t,n){Object.defineProperty(e,t,{value:n,configurable:!1,writable:!0})}function gp(e,t){return Object.hasOwnProperty.call(e,t)}gp(Dn,"__GLOBAL_LOADING_REMOTE_ENTRY__")||hp(Dn,"__GLOBAL_LOADING_REMOTE_ENTRY__",{});var Hs=Dn.__GLOBAL_LOADING_REMOTE_ENTRY__;function MI(e){gp(e,"__VMOK__")&&!gp(e,"__FEDERATION__")&&hp(e,"__FEDERATION__",e.__VMOK__),gp(e,"__FEDERATION__")||(hp(e,"__FEDERATION__",{__GLOBAL_PLUGIN__:[],__INSTANCES__:[],moduleInfo:{},__SHARE__:{},__MANIFEST_LOADING__:{},__PRELOADED_MAP__:new Map}),hp(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}MI(Dn);MI(Va);function sne(e,t=xy()){t&&(Dn.__FEDERATION__.__DEBUG_CONSTRUCTOR__=e,Dn.__FEDERATION__.__DEBUG_CONSTRUCTOR_VERSION__="2.5.1")}function ol(e,t){if(typeof t=="string"){if(e[t])return{value:e[t],key:t};{const n=Object.keys(e);for(const a of n){const[o,p]=a.split(":"),f=`${o}:${t}`,m=e[f];if(m)return{value:m,key:f}}return{value:void 0,key:t}}}else Xt(`getInfoWithoutType: "key" must be a string, got ${typeof t} (${JSON.stringify(t)}).`)}var H2=()=>Va.__FEDERATION__.moduleInfo,lne=(e,t)=>{const n=ol(t,Kp(e)).value;if(n&&!n.version&&"version"in e&&e.version&&(n.version=e.version),n)return n;if("version"in e&&e.version){const{version:a,...o}=e,p=Kp(o),f=ol(Va.__FEDERATION__.moduleInfo,p).value;if(f?.version===a)return f}},vp=e=>lne(e,Va.__FEDERATION__.moduleInfo),$2=(e,t)=>{const n=Kp(e);return Va.__FEDERATION__.moduleInfo[n]=t,Va.__FEDERATION__.moduleInfo},cne=e=>(Va.__FEDERATION__.moduleInfo={...Va.__FEDERATION__.moduleInfo,...e},()=>{const t=Object.keys(e);for(const n of t)delete Va.__FEDERATION__.moduleInfo[n]}),o0=(e,t)=>{const n=t||`__FEDERATION_${e}:custom__`;return{remoteEntryKey:n,entryExports:Dn[n]}},une=()=>Va.__FEDERATION__.__GLOBAL_PLUGIN__,dne=e=>Dn.__FEDERATION__.__PRELOADED_MAP__.get(e),pne=e=>Dn.__FEDERATION__.__PRELOADED_MAP__.set(e,!0),Q2="[0-9A-Za-z-]+",s0=`(?:\\+(${Q2}(?:\\.${Q2})*))`,Rc="0|[1-9]\\d*",yp="[0-9]+",CI="\\d*[a-zA-Z-][a-zA-Z0-9-]*",V2=`(?:${yp}|${CI})`,mne=`(?:-?(${V2}(?:\\.${V2})*))`,G2=`(?:${Rc}|${CI})`,AI=`(?:-(${G2}(?:\\.${G2})*))`,Ng=`${Rc}|x|X|\\*`,sl=`[v=\\s]*(${Ng})(?:\\.(${Ng})(?:\\.(${Ng})(?:${AI})?${s0}?)?)?`,fne=`^\\s*(${sl})\\s+-\\s+(${sl})\\s*$`,hne=`[v=\\s]*${`(${yp})\\.(${yp})\\.(${yp})`}${mne}?${s0}?`,l0="((?:<|>)?=?)",gne=`(\\s*)${l0}\\s*(${hne}|${sl})`,EI="(?:~>?)",vne=`(\\s*)${EI}\\s+`,RI="(?:\\^)",yne=`(\\s*)${RI}\\s+`,bne="(<|>)?=?\\s*\\*",Sne=`^${RI}${sl}$`,xne=`v?${`(${Rc})\\.(${Rc})\\.(${Rc})`}${AI}?${s0}?`,kne=`^${EI}${sl}$`,wne=`^${l0}\\s*${sl}$`,Mne=`^${l0}\\s*(${xne})$|^$`,Cne="^\\s*>=\\s*0.0.0\\s*$";function vi(e){return new RegExp(e)}function Gn(e){return!e||e.toLowerCase()==="x"||e==="*"}function _I(...e){return t=>e.reduce((n,a)=>a(n),t)}function Z2(e){return e.match(vi(Mne))}function K2(e,t,n,a){const o=`${e}.${t}.${n}`;return a?`${o}-${a}`:o}function Ane(e){return e.replace(vi(fne),(t,n,a,o,p,f,m,h,u,x,w,C)=>(Gn(a)?n="":Gn(o)?n=`>=${a}.0.0`:Gn(p)?n=`>=${a}.${o}.0`:n=`>=${n}`,Gn(u)?h="":Gn(x)?h=`<${Number(u)+1}.0.0-0`:Gn(w)?h=`<${u}.${Number(x)+1}.0-0`:C?h=`<=${u}.${x}.${w}-${C}`:h=`<=${h}`,`${n} ${h}`.trim()))}function Ene(e){return e.replace(vi(gne),"$1$2$3")}function Rne(e){return e.replace(vi(vne),"$1~")}function _ne(e){return e.replace(vi(yne),"$1^")}function Tne(e){return e.trim().split(/\s+/).map(t=>t.replace(vi(Sne),(n,a,o,p,f)=>Gn(a)?"":Gn(o)?`>=${a}.0.0 <${Number(a)+1}.0.0-0`:Gn(p)?a==="0"?`>=${a}.${o}.0 <${a}.${Number(o)+1}.0-0`:`>=${a}.${o}.0 <${Number(a)+1}.0.0-0`:f?a==="0"?o==="0"?`>=${a}.${o}.${p}-${f} <${a}.${o}.${Number(p)+1}-0`:`>=${a}.${o}.${p}-${f} <${a}.${Number(o)+1}.0-0`:`>=${a}.${o}.${p}-${f} <${Number(a)+1}.0.0-0`:a==="0"?o==="0"?`>=${a}.${o}.${p} <${a}.${o}.${Number(p)+1}-0`:`>=${a}.${o}.${p} <${a}.${Number(o)+1}.0-0`:`>=${a}.${o}.${p} <${Number(a)+1}.0.0-0`)).join(" ")}function Ine(e){return e.trim().split(/\s+/).map(t=>t.replace(vi(kne),(n,a,o,p,f)=>Gn(a)?"":Gn(o)?`>=${a}.0.0 <${Number(a)+1}.0.0-0`:Gn(p)?`>=${a}.${o}.0 <${a}.${Number(o)+1}.0-0`:f?`>=${a}.${o}.${p}-${f} <${a}.${Number(o)+1}.0-0`:`>=${a}.${o}.${p} <${a}.${Number(o)+1}.0-0`)).join(" ")}function Nne(e){return e.split(/\s+/).map(t=>t.trim().replace(vi(wne),(n,a,o,p,f,m)=>{const h=Gn(o),u=h||Gn(p),x=u||Gn(f);return a==="="&&x&&(a=""),m="",h?a===">"||a==="<"?"<0.0.0-0":"*":a&&x?(u&&(p=0),f=0,a===">"?(a=">=",u?(o=Number(o)+1,p=0,f=0):(p=Number(p)+1,f=0)):a==="<="&&(a="<",u?o=Number(o)+1:p=Number(p)+1),a==="<"&&(m="-0"),`${a+o}.${p}.${f}${m}`):u?`>=${o}.0.0${m} <${Number(o)+1}.0.0-0`:x?`>=${o}.${p}.0${m} <${o}.${Number(p)+1}.0-0`:n})).join(" ")}function One(e){return e.trim().replace(vi(bne),"")}function jne(e){return e.trim().replace(vi(Cne),"")}function bp(e,t){return e=Number(e)||e,t=Number(t)||t,e>t?1:e===t?0:-1}function Pne(e,t){const{preRelease:n}=e,{preRelease:a}=t;if(n===void 0&&a)return 1;if(n&&a===void 0)return-1;if(n===void 0&&a===void 0)return 0;for(let o=0,p=n.length;o<=p;o++){const f=n[o],m=a[o];if(f!==m)return f===void 0&&m===void 0?0:f?m?bp(f,m):-1:1}return 0}function Hd(e,t){return bp(e.major,t.major)||bp(e.minor,t.minor)||bp(e.patch,t.patch)||Pne(e,t)}function Og(e,t){return e.version===t.version}function Dne(e,t){switch(e.operator){case"":case"=":return Og(e,t);case">":return Hd(e,t)<0;case">=":return Og(e,t)||Hd(e,t)<0;case"<":return Hd(e,t)>0;case"<=":return Og(e,t)||Hd(e,t)>0;case void 0:return!0;default:return!1}}function zne(e){return _I(Tne,Ine,Nne,One)(e)}function Lne(e){return _I(Ane,Ene,Rne,_ne)(e.trim()).split(/\s+/).join(" ")}function wc(e,t){if(!e)return!1;const n=Z2(e);if(!n)return!1;const[,a,,o,p,f,m]=n,h={operator:a,version:K2(o,p,f,m),major:o,minor:p,patch:f,preRelease:m?.split(".")},u=t.split("||");for(const x of u){const w=x.trim();if(!w||w==="*"||w==="x")return!0;try{const C=Lne(w);if(!C.trim())return!0;const A=C.split(" ").map(O=>zne(O)).join(" ");if(!A.trim())return!0;const R=A.split(/\s+/).map(O=>jne(O)).filter(Boolean);if(R.length===0)continue;let I=!0;for(const O of R){const D=Z2(O);if(!D){I=!1;break}const[,z,,B,q,G,ae]=D;if(!Dne({operator:z,version:K2(B,q,G,ae),major:B,minor:q,patch:G,preRelease:ae?.split(".")},h)){I=!1;break}}if(I)return!0}catch(C){console.error(`[semver] Error processing range part "${w}":`,C);continue}}return!1}var Am="default",qne="global";function Bne(e,t,n,a){let o;return"get"in e?o=e.get:"lib"in e?o=()=>Promise.resolve(e.lib):o=()=>Promise.resolve(()=>{Xt(`Cannot get shared "${n}" from "${t}": neither "get" nor "lib" is provided in the share config.`)}),e.shareConfig?.eager&&e.treeShaking?.mode&&Xt(`Invalid shared config for "${n}" 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:o,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??a)||"version-first",treeShaking:e.treeShaking?{...e.treeShaking,mode:e.treeShaking.mode??"server-calc",status:e.treeShaking.status??Sy.UNKNOWN,useIn:[]}:void 0}}function TI(e,t){const n=t.shared||{},a=t.name,o=Object.keys(n).reduce((f,m)=>{const h=kI(n[m]);return f[m]=f[m]||[],h.forEach(u=>{f[m].push(Bne(u,a,m,t.shareStrategy))}),f},{}),p={...e.shared};return Object.keys(o).forEach(f=>{p[f]?o[f].forEach(m=>{p[f].find(h=>h.version===m.version)||p[f].push(m)}):p[f]=o[f]}),{allShareInfos:p,newShareInfos:o}}function Vc(e,t){if(!e)return!1;const{status:n,mode:a}=e;return n===Sy.NO_USE?!1:n===Sy.CALCULATED?!0:a==="runtime-infer"?t?Fne(e,t):!0:!1}function Ro(e,t){const n=a=>{if(!Number.isNaN(Number(a))){const o=a.split(".");let p=a;for(let f=0;f<3-o.length;f++)p+=".0";return p}return a};return!!wc(n(e),`<=${n(t)}`)}var Gc=(e,t)=>{const n=t||function(a,o){return Ro(a,o)};return Object.keys(e).reduce((a,o)=>!a||n(a,o)||a==="0"?o:a,0)},Wp=e=>!!e.loaded||typeof e.lib=="function",Une=e=>!!e.loading,Fne=(e,t)=>{if(!e||!t)return!1;const{usedExports:n}=e;return n?!!t.every(a=>n.includes(a)):!1};function Hne(e,t,n,a){const o=e[t][n];let p="",f=Vc(a);const m=function(h,u){return f?o[h].treeShaking?o[u].treeShaking?!Wp(o[h].treeShaking)&&Ro(h,u):!1:!0:!Wp(o[h])&&Ro(h,u)};if(f){if(p=Gc(e[t][n],m),p)return{version:p,useTreesShaking:f};f=!1}return{version:Gc(e[t][n],m),useTreesShaking:f}}var _s=e=>Wp(e)||Une(e);function $ne(e,t,n,a){const o=e[t][n];let p="",f=Vc(a);const m=function(h,u){if(f){if(!o[h].treeShaking)return!0;if(!o[u].treeShaking)return!1;if(_s(o[u].treeShaking))return _s(o[h].treeShaking)?!!Ro(h,u):!0;if(_s(o[h].treeShaking))return!1}return _s(o[u])?_s(o[h])?!!Ro(h,u):!0:_s(o[h])?!1:Ro(h,u)};if(f){if(p=Gc(e[t][n],m),p)return{version:p,useTreesShaking:f};f=!1}return{version:Gc(e[t][n],m),useTreesShaking:f}}function Qne(e){return e==="loaded-first"?$ne:Hne}function Sp(e,t,n,a){if(!e)return;const{shareConfig:o,scope:p=Am,strategy:f,treeShaking:m}=n,h=Array.isArray(p)?p:[p];for(const u of h)if(o&&e[u]&&e[u][t]){const{requiredVersion:x}=o,{version:w,useTreesShaking:C}=Qne(f)(e,u,t,m),A=()=>{const I=e[u][t][w];if(o.singleton){if(typeof x=="string"&&!wc(w,x)){const O=`Version ${w} from ${w&&I.from} of shared singleton module ${t} does not satisfy the requirement of ${n.from} which needs ${x})`;o.strictVersion?Xt(O):$c(O)}return{shared:I,useTreesShaking:C}}else{if(x===!1||x==="*")return{shared:I,useTreesShaking:C};if(wc(w,x))return{shared:I,useTreesShaking:C};const O=Vc(m);if(O){for(const[D,z]of Object.entries(e[u][t]))if(Vc(z.treeShaking,m?.usedExports)&&wc(D,x))return{shared:z,useTreesShaking:O}}for(const[D,z]of Object.entries(e[u][t]))if(wc(D,x))return{shared:z,useTreesShaking:!1}}},R={shareScopeMap:e,scope:u,pkgName:t,version:w,GlobalFederation:Qc.__FEDERATION__,shareInfo:n,resolver:A};return(a.emit(R)||R).resolver()}}function II(){return Qc.__FEDERATION__.__SHARE__}function W2(e){const{pkgName:t,extraOptions:n,shareInfos:a}=e,o=h=>{if(!h)return;const u={};return h.forEach(w=>{u[w.version]=w}),u[Gc(u,function(w,C){return!Wp(u[w])&&Ro(w,C)})]},p=n?.resolver??o,f=h=>h!==null&&typeof h=="object"&&!Array.isArray(h),m=(...h)=>{const u={};for(const x of h)if(x)for(const[w,C]of Object.entries(x)){const A=u[w];f(A)&&f(C)?u[w]=m(A,C):C!==void 0&&(u[w]=C)}return u};return m(p(a[t]),n?.customShareInfo)}var Ts=(e,t)=>{e.useIn||(e.useIn=[]),ane(e.useIn,t)};function $d(e,t){return t&&e.treeShaking?e.treeShaking:e}function c0(e,t){return!t||t==="."?e:`${e}/${t.replace(/^\.\//,"")}`}function Y2(e,t){for(const n of e){const a=t.startsWith(n.name);let o=t.replace(n.name,"");if(a){if(o.startsWith("/")){const m=n.name;return o=`.${o}`,{pkgNameOrAlias:m,expose:o,remote:n}}else if(o==="")return{pkgNameOrAlias:n.name,expose:".",remote:n}}const p=n.alias&&t.startsWith(n.alias);let f=n.alias&&t.replace(n.alias,"");if(n.alias&&p){if(f&&f.startsWith("/")){const m=n.alias;return f=`.${f}`,{pkgNameOrAlias:m,expose:f,remote:n}}else if(f==="")return{pkgNameOrAlias:n.alias,expose:".",remote:n}}}}function Vne(e,t){for(const n of e)if(t===n.name||n.alias&&t===n.alias)return n}var NI="RUNTIME-001",OI="RUNTIME-002",jI="RUNTIME-003",PI="RUNTIME-004",DI="RUNTIME-005",Ay="RUNTIME-006",zI="RUNTIME-007",LI="RUNTIME-008",Gne="RUNTIME-009",qI="RUNTIME-010",BI="RUNTIME-011",Zne="RUNTIME-012",UI="RUNTIME-013",FI="RUNTIME-014",HI="RUNTIME-015",ca={[NI]:"Failed to get remoteEntry exports.",[OI]:'The remote entry interface does not contain "init"',[jI]:"Failed to get manifest.",[PI]:"Failed to locate remote.",[DI]:"Invalid loadShareSync function call from bundler runtime",[Ay]:"Invalid loadShareSync function call from runtime",[zI]:"Failed to get remote snapshot.",[LI]:"Failed to load script resources.",[Gne]:"Please call createInstance first.",[qI]:'The name option cannot be changed after initialization. If you want to create a new instance with a different name, please use "createInstance" api.',[BI]:"The remoteEntry URL is missing from the remote snapshot.",[Zne]:'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.',[UI]:"The manifest is not a valid Module Federation manifest.",[FI]:"The remote does not expose the requested module.",[HI]:"Remote container initialization failed."};({...ca});var $I=".then(callbacks[0]).catch(callbacks[1])";async function Kne({entry:e,remoteEntryExports:t}){return new Promise((n,a)=>{try{t?n(t):typeof FEDERATION_ALLOW_NEW_FUNCTION<"u"?new Function("callbacks",`import("${e}")${$I}`)([n,a]):import(e).then(n).catch(a)}catch(o){Xt(`Failed to load ESM entry from "${e}". ${o instanceof Error?o.message:String(o)}`)}})}async function Wne({entry:e,remoteEntryExports:t}){return new Promise((n,a)=>{try{t?n(t):typeof __system_context__>"u"?System.import(e).then(n).catch(a):new Function("callbacks",`System.import("${e}")${$I}`)([n,a])}catch(o){Xt(`Failed to load SystemJS entry from "${e}". ${o instanceof Error?o.message:String(o)}`)}})}function QI(e,t,n){const{remoteEntryKey:a,entryExports:o}=o0(e,t);return o||Xt(NI,ca,{remoteName:e,remoteEntryUrl:n,remoteEntryKey:a}),o}async function Yne({name:e,globalName:t,entry:n,remoteInfo:a,loaderHook:o,getEntryUrl:p,resourceContext:f}){const{entryExports:m}=o0(e,t);if(m)return m;const h=p?p(n):n;return Yte(h,{attrs:{},createScriptHook:(u,x)=>{const w=o.lifecycle.createScript.emit({url:u,attrs:x,remoteInfo:a,resourceContext:f?{...f,url:u}:void 0});if(w&&(w instanceof HTMLScriptElement||"script"in w||"timeout"in w))return w}}).then(()=>QI(e,t,n),u=>{const x=u instanceof Error?u.message:String(u);Xt(LI,ca,{remoteName:e,resourceUrl:h},x)})}async function Xne({remoteInfo:e,remoteEntryExports:t,loaderHook:n,getEntryUrl:a,resourceContext:o}){const{entry:p,entryGlobalName:f,name:m,type:h}=e;switch(h){case"esm":case"module":return Kne({entry:p,remoteEntryExports:t});case"system":return Wne({entry:p,remoteEntryExports:t});default:return Yne({entry:p,globalName:f,name:m,remoteInfo:e,loaderHook:n,getEntryUrl:a,resourceContext:o})}}async function Jne({remoteInfo:e,loaderHook:t,resourceContext:n}){const{entry:a,entryGlobalName:o,name:p,type:f}=e,{entryExports:m}=o0(p,o);return m||ene(a,{attrs:{name:p,globalName:o,type:f},loaderHook:{createScriptHook:(h,u={})=>{const x=t.lifecycle.createScript.emit({url:h,attrs:u,remoteInfo:e,resourceContext:n?{...n,url:h}:void 0});if(x&&"url"in x)return x}}}).then(()=>QI(p,o,a)).catch(h=>{Xt(`Failed to load Node.js entry for remote "${p}" from "${a}". ${h instanceof Error?h.message:String(h)}`)})}function Ey(e){const{entry:t,name:n}=e;return pI(n,t)}async function u0(e){const{origin:t,remoteEntryExports:n,remoteInfo:a,getEntryUrl:o,resourceContext:p,_inErrorHandling:f=!1}=e,m=Ey(a);if(n)return n;if(!Hs[m]){const h=t.remoteHandler.hooks.lifecycle.loadEntry,u=t.loaderHook;Hs[m]=h.emit({origin:t,loaderHook:u,remoteInfo:a,remoteEntryExports:n}).then(x=>x||((typeof ENV_TARGET<"u"?ENV_TARGET==="web":Vr)?Xne({remoteInfo:a,remoteEntryExports:n,loaderHook:u,getEntryUrl:o,resourceContext:p}):Jne({remoteInfo:a,loaderHook:u,resourceContext:p}))).then(async x=>(await t.loaderHook.lifecycle.afterLoadEntry.emit({origin:t,remoteInfo:a,remoteEntryExports:x}),x)).catch(async x=>{const w=Ey(a),C=x instanceof Error&&x.message.includes("ScriptExecutionError");if(x instanceof Error&&x.message.includes("RUNTIME-008")&&!C&&!f){const A=I=>u0({...I,_inErrorHandling:!0}),R=await t.loaderHook.lifecycle.loadEntryError.emit({getRemoteEntry:A,origin:t,remoteInfo:a,remoteEntryExports:n,globalLoading:Hs,uniqueKey:w});if(R)return await t.loaderHook.lifecycle.afterLoadEntry.emit({origin:t,remoteInfo:a,remoteEntryExports:R,recovered:!0}),R}throw await t.loaderHook.lifecycle.afterLoadEntry.emit({origin:t,remoteInfo:a,error:x}),x})}return Hs[m]}function $s(e){return{...e,entry:"entry"in e?e.entry:"",type:e.type||"global",entryGlobalName:e.entryGlobalName||e.name,shareScope:e.shareScope||"default"}}function eae(){return typeof FEDERATION_BUILD_IDENTIFIER<"u"?FEDERATION_BUILD_IDENTIFIER:""}function tae(e,t){const n=une(),a=[t.hooks,t.remoteHandler.hooks,t.sharedHandler.hooks,t.snapshotHandler.hooks,t.loaderHook,t.bridgeHook];return n.length>0&&n.forEach(o=>{e?.find(p=>p.name!==o.name)&&e.push(o)}),e&&e.length>0&&e.forEach(o=>{a.forEach(p=>{p.applyPlugin(o,t)})}),e}function nae(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 Wi(e){const t={};for(const[n,a]of Object.entries(e.shared)){const o=a[0];o&&(t[n]={version:o.version,singleton:o.shareConfig?.singleton,requiredVersion:o.shareConfig?.requiredVersion===!1?!1:o.shareConfig?.requiredVersion,eager:o.eager,strictVersion:o.shareConfig?.strictVersion})}return{project:{name:e.name,mfRole:e.remotes?.length>0?"host":"unknown"},mfConfig:{name:e.name,remotes:e.remotes?.map(nae)??[],shared:t}}}function VI(e){return{resourceCategory:"sync",share:!0,depsRemote:!0,...e}}function aae(e,t){return t.map(n=>{const a=Vne(e,n.nameOrAlias);return Zi(a,`Unable to preload ${n.nameOrAlias} as it is not included in ${!a&&fI({remoteInfo:a,remotes:e})}`),{remote:a,preloadConfig:VI(n)}})}function iae(e){return e?e.map(t=>t==="."?t:t.startsWith("./")?t.replace("./",""):t):[]}function d0(e){return e instanceof Error?e.message.includes("timed out")||e.name.includes("Timeout"):!1}function _o(e,t,n,a){return{url:t,status:n,resourceType:e.resourceType,initiator:e.initiator,id:e.id,error:a}}async function rae(e,t,n,a){const o=e.moduleCache.get(n.name),p=n.entry;if(o?.remoteEntryExports)return _o(a,p,"cached");try{if(!await u0({origin:e,remoteInfo:n,remoteEntryExports:o?.remoteEntryExports,resourceContext:{...a,url:p}}))throw new Error(`Failed to load remoteEntry "${p}".`);return _o(a,p,"success")}catch(f){return _o(a,p,d0(f)?"timeout":"error",f)}}function jg({host:e,remoteInfo:t,url:n,attrs:a,context:o,needDeleteLink:p}){return new Promise(f=>{const{link:m,needAttach:h}=Wte({url:n,cb:()=>{f(_o(o,n,h?"success":"cached"))},onErrorCallback:u=>{f(_o(o,n,d0(u)?"timeout":"error",u))},attrs:a,createLinkHook:(u,x)=>{const w=e.loaderHook.lifecycle.createLink.emit({url:u,attrs:x,remoteInfo:t,resourceContext:{...o,url:u}});return w instanceof HTMLLinkElement,w},needDeleteLink:p});h&&document.head.appendChild(m)})}function oae({host:e,remoteInfo:t,url:n,attrs:a,context:o}){return new Promise(p=>{const{script:f,needAttach:m}=yI({url:n,cb:()=>{p(_o(o,n,m?"success":"cached"))},onErrorCallback:h=>{p(_o(o,n,d0(h)?"timeout":"error",h))},attrs:a,createScriptHook:(h,u)=>{const x=e.loaderHook.lifecycle.createScript.emit({url:h,attrs:u,remoteInfo:t,resourceContext:{...o,url:h}});return x instanceof HTMLScriptElement,x},needDeleteScript:!0});m&&document.head.appendChild(f)})}function mc(e,t){return{...e,resourceType:t}}function GI(e,t,n,a=!0,o={initiator:"preloadRemote",id:e.name}){const{cssAssets:p,jsAssetsWithoutEntry:f,entryAssets:m}=n,h=[];if(t.options.inBrowser){if(m.forEach(u=>{const{moduleInfo:x}=u;h.push(rae(t,e,x,mc(o,"remoteEntry")))}),a){const u={rel:"preload",as:"style"};p.forEach(x=>{h.push(jg({host:t,remoteInfo:e,url:x,attrs:u,context:mc(o,"css")}))})}else{const u={rel:"stylesheet",type:"text/css"};p.forEach(x=>{h.push(jg({host:t,remoteInfo:e,url:x,attrs:u,needDeleteLink:!1,context:mc(o,"css")}))})}if(a){const u={rel:"preload",as:"script"};f.forEach(x=>{h.push(jg({host:t,remoteInfo:e,url:x,attrs:u,context:mc(o,"js")}))})}else{const u={fetchpriority:"high",type:e?.type==="module"?"module":"text/javascript"};f.forEach(x=>{h.push(oae({host:t,remoteInfo:e,url:x,attrs:u,context:mc(o,"js")}))})}}return Promise.all(h)}function sae(e){if(!e||!("modules"in e)||!Array.isArray(e.modules))return;const t=e.modules.map(n=>n.moduleName).filter(Boolean);return t.length?t.join(","):void 0}function lae(e,t,n){const a=t,o=Array.isArray(e.shareScope)?e.shareScope:[e.shareScope];o.length||o.push("default"),o.forEach(f=>{a[f]||(a[f]={})});const p={version:e.version||"",shareScopeKeys:Array.isArray(e.shareScope)?o:e.shareScope||"default"};return Object.defineProperty(p,"shareScopeMap",{value:a,enumerable:!1}),{remoteEntryInitOptions:p,shareScope:a[o[0]],initScope:n??[]}}var ZI=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 u0({origin:this.host,remoteInfo:this.remoteInfo,remoteEntryExports:this.remoteEntryExports,resourceContext:{initiator:"loadRemote",id:c0(this.remoteInfo.name,e),resourceType:"remoteEntry"}});return Zi(t,`remoteEntryExports is undefined
81
- ${fI(this.remoteInfo)}`),this.remoteEntryExports=t,this.remoteEntryExports}async init(e,t,n,a){const o=await this.getEntry(a);if(this.inited)return await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:o,cached:!0,origin:this.host}),o;if(this.initPromise){try{await this.initPromise,await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:o,cached:!0,origin:this.host})}catch(p){throw await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:o,error:p,cached:!0,origin:this.host}),p}return o}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:p,shareScope:f,initScope:m}=lae(this.remoteInfo,this.host.shareScopeMap,n),h=await this.host.hooks.lifecycle.beforeInitContainer.emit({shareScope:f,remoteEntryInitOptions:p,initScope:m,remoteInfo:this.remoteInfo,origin:this.host});typeof o?.init>"u"&&Xt(OI,ca,{hostName:this.host.name,remoteName:this.remoteInfo.name,remoteEntryUrl:this.remoteInfo.entry,remoteEntryKey:this.remoteInfo.entryGlobalName},void 0,Wi(this.host.options));try{await o.init(h.shareScope,h.initScope,h.remoteEntryInitOptions)}catch(u){Xt(HI,ca,{hostName:this.host.name,remoteName:this.remoteInfo.name,remoteEntryUrl:this.remoteInfo.entry,remoteEntryKey:this.remoteInfo.entryGlobalName,shareScope:this.remoteInfo.shareScope},`${u}`,Wi(this.host.options))}await this.host.hooks.lifecycle.initContainer.emit({...h,id:e,remoteSnapshot:t,remoteEntryExports:o}),this.inited=!0})();try{await this.initPromise,await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:o,origin:this.host})}catch(p){throw await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:o,error:p,origin:this.host}),p}finally{this.initing=!1,this.initPromise=void 0}return o}async get(e,t,n,a){const{loadFactory:o=!0}=n||{loadFactory:!0},p=await this.init(e,a,void 0,t);this.lib=p,await this.host.loaderHook.lifecycle.beforeGetExpose.emit({id:e,expose:t,moduleInfo:this.remoteInfo,remoteEntryExports:p,origin:this.host});let f;try{const u=await this.host.loaderHook.lifecycle.getModuleFactory.emit({remoteEntryExports:p,expose:t,moduleInfo:this.remoteInfo});f=typeof u=="function"?u:void 0,f||(f=await p.get(t)),f||Xt(FI,ca,{hostName:this.host.name,remoteName:this.remoteInfo.name,remoteEntryUrl:this.remoteInfo.entry,expose:t,requestId:e,availableExposes:sae(a)},void 0,Wi(this.host.options)),await this.host.loaderHook.lifecycle.afterGetExpose.emit({id:e,expose:t,moduleInfo:this.remoteInfo,remoteEntryExports:p,moduleFactory:f,origin:this.host})}catch(u){throw await this.host.loaderHook.lifecycle.afterGetExpose.emit({id:e,expose:t,moduleInfo:this.remoteInfo,remoteEntryExports:p,error:u,origin:this.host}),u}const m=one(this.remoteInfo.name,t),h=this.wraperFactory(f,m);if(!o)return h;await this.host.loaderHook.lifecycle.beforeExecuteFactory.emit({id:e,expose:t,moduleInfo:this.remoteInfo,loadFactory:o,origin:this.host});try{const u=await h();return await this.host.loaderHook.lifecycle.afterExecuteFactory.emit({id:e,expose:t,moduleInfo:this.remoteInfo,loadFactory:o,exposeModule:u,origin:this.host}),u}catch(u){throw await this.host.loaderHook.lifecycle.afterExecuteFactory.emit({id:e,expose:t,moduleInfo:this.remoteInfo,loadFactory:o,error:u,origin:this.host}),u}}wraperFactory(e,t){function n(a,o){a&&typeof a=="object"&&Object.isExtensible(a)&&!Object.getOwnPropertyDescriptor(a,Symbol.for("mf_module_id"))&&Object.defineProperty(a,Symbol.for("mf_module_id"),{value:o,enumerable:!1})}return()=>{const a=e();return a instanceof Promise?a.then(o=>(n(o,t),o)):(n(a,t),a)}}},sa=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 n(...a){return t.remove(n),e.apply(null,a)})}emit(...e){let t;return this.listeners.size>0&&this.listeners.forEach(n=>{const a=n(...e);a!==void 0&&(t=a)}),t}remove(e){this.listeners.delete(e)}removeAll(){this.listeners.clear()}},wn=class extends sa{emit(...e){let t;const n=Array.from(this.listeners);if(n.length>0){let a=0;const o=p=>p===!1?!1:a<n.length?Promise.resolve(n[a++].apply(null,e)).then(f=>f===void 0||e.length===1&&f===e[0]?o(p):o(f)):p;t=o()}return Promise.resolve(t)}};function KI(e,t){if(!r0(t))return!1;if(e!==t){for(const n in e)if(!(n in t))return!1}return!0}var Zs=class extends sa{constructor(e){super(),this.onerror=Xt,this.type=e}emit(e){r0(e)||Xt(`The data for the "${this.type}" hook should be an object.`);for(const t of this.listeners)try{const n=t(e);if(n===void 0)continue;if(KI(e,n))e=n;else{this.onerror(`A plugin returned an unacceptable value for the "${this.type}" type.`);break}}catch(n){$c(n),this.onerror(n)}return e}},Lr=class extends sa{constructor(e){super(),this.onerror=Xt,this.type=e}emit(e){r0(e)||Xt(`The response data for the "${this.type}" hook must be an object.`);const t=Array.from(this.listeners);if(t.length>0){let n=0;const a=p=>($c(p),this.onerror(p),e),o=p=>{if(p!==void 0&&KI(e,p))e=p;else if(p!==void 0)return this.onerror(`A plugin returned an incorrect value for the "${this.type}" type.`),e;if(n<t.length)try{return Promise.resolve(t[n++](e)).then(o,a)}catch(f){return a(f)}return e};return Promise.resolve(o(e))}return Promise.resolve(e)}},Ks=class{constructor(e){this.registerPlugins={},this.lifecycle=e,this.lifecycleKeys=Object.keys(e)}applyPlugin(e,t){Zi(rne(e),"Plugin configuration is invalid.");const n=e.name;Zi(n,"A name must be provided by the plugin."),this.registerPlugins[n]||(this.registerPlugins[n]=e,e.apply?.(t),Object.keys(this.lifecycle).forEach(a=>{const o=e[a];o&&this.lifecycle[a].on(o)}))}removePlugin(e){Zi(e,"A name is required.");const t=this.registerPlugins[e];Zi(t,`The plugin "${e}" is not registered.`),Object.keys(t).forEach(n=>{n!=="name"&&this.lifecycle[n].remove(t[n])})}};function WI(e,t){const n=wI(t);n.url||Xt(BI,ca,{remoteName:e.name});let a=ky(t,n.url);!Vr&&!a.startsWith("http")&&(a=`https:${a}`),e.type=n.type,e.entryGlobalName=n.globalName,e.entry=a,e.version=t.version,e.buildVersion=t.buildVersion}function cae(){return{name:"snapshot-plugin",async afterResolve(e){const{remote:t,pkgNameOrAlias:n,expose:a,origin:o,remoteInfo:p,id:f}=e;if(!i0(t)||!xI(t)){const{remoteSnapshot:m,globalSnapshot:h}=await o.snapshotHandler.loadRemoteSnapshotInfo({moduleInfo:t,id:c0(t.name,a)});WI(p,m);const u={remote:t,preloadConfig:{nameOrAlias:n,exposes:[a],resourceCategory:"sync",share:!1,depsRemote:!1}},x=await o.remoteHandler.hooks.lifecycle.generatePreloadAssets.emit({origin:o,preloadOptions:u,remoteInfo:p,remote:t,remoteSnapshot:m,globalSnapshot:h});return x&&GI(p,o,x,!1,{initiator:"loadRemote",id:f}).catch(()=>{}),{...e,remoteSnapshot:m}}return e}}}function uae(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 YI(e,t,n,a,o={},p){const{value:f}=ol(e,Kp(t)),m=p||f;if(m&&!hI(m)&&(n(m,t,a),m.remotesInfo)){const h=Object.keys(m.remotesInfo);for(const u of h){if(o[u])continue;o[u]=!0;const x=uae(u),w=m.remotesInfo[u];YI(e,{name:x.name,version:w.matchedVersion},n,!1,o,void 0)}}}var Pg=(e,t)=>document.querySelector(`${e}[${e==="link"?"href":"src"}="${t}"]`);function dae(e,t,n,a,o){const p=[],f=[],m=[],h=new Set,u=new Set,{options:x}=e,{preloadConfig:w}=t,{depsRemote:C}=w;if(YI(a,n,(R,I,O)=>{let D;if(O)D=w;else if(Array.isArray(C)){const ae=C.find(Q=>Q.nameOrAlias===I.name||Q.nameOrAlias===I.alias);if(!ae)return;D=VI(ae)}else if(C===!0)D=w;else return;const z=ky(R,wI(R).url);z&&m.push({name:I.name,moduleInfo:{name:I.name,entry:z,type:"remoteEntryType"in R?R.remoteEntryType:"global",entryGlobalName:"globalName"in R?R.globalName:I.name,shareScope:"",version:"version"in R?R.version:void 0},url:z});let B="modules"in R?R.modules:[];const q=iae(D.exposes);q.length&&"modules"in R&&(B=R?.modules?.reduce((ae,Q)=>(q?.indexOf(Q.moduleName)!==-1&&ae.push(Q),ae),[]));function G(ae){const Q=ae.map(H=>ky(R,H));return D.filter?Q.filter(D.filter):Q}if(B){const ae=B.length;for(let Q=0;Q<ae;Q++){const H=B[Q],oe=`${I.name}/${H.moduleName}`;e.remoteHandler.hooks.lifecycle.handlePreloadModule.emit({id:H.moduleName==="."?I.name:oe,name:I.name,remoteSnapshot:R,preloadConfig:D,remote:I,origin:e}),!dne(oe)&&(D.resourceCategory==="all"?(p.push(...G(H.assets.css.async)),p.push(...G(H.assets.css.sync)),f.push(...G(H.assets.js.async)),f.push(...G(H.assets.js.sync))):D.resourceCategory==="sync"&&(p.push(...G(H.assets.css.sync)),f.push(...G(H.assets.js.sync))),pne(oe))}}},!0,{},o),o.shared&&o.shared.length>0){const R=(I,O)=>{const{shared:D}=Sp(e.shareScopeMap,O.sharedName,I,e.sharedHandler.hooks.lifecycle.resolveShare)||{};D&&typeof D.lib=="function"&&(O.assets.js.sync.forEach(z=>{h.add(z)}),O.assets.css.sync.forEach(z=>{u.add(z)}))};o.shared.forEach(I=>{const O=x.shared?.[I.sharedName];if(!O)return;const D=I.version?O.find(z=>z.version===I.version):O;D&&kI(D).forEach(z=>{R(z,I)})})}const A=f.filter(R=>!h.has(R)&&!Pg("script",R));return{cssAssets:p.filter(R=>!u.has(R)&&!Pg("link",R)),jsAssetsWithoutEntry:A,entryAssets:m.filter(R=>!Pg("script",R.url))}}var pae=function(){return{name:"generate-preload-assets-plugin",async generatePreloadAssets(e){const{origin:t,preloadOptions:n,remoteInfo:a,remote:o,globalSnapshot:p,remoteSnapshot:f}=e;return Vr?i0(o)&&xI(o)?{cssAssets:[],jsAssetsWithoutEntry:[],entryAssets:[{name:o.name,url:o.entry,moduleInfo:{name:a.name,entry:o.entry,type:a.type||"global",entryGlobalName:"",shareScope:""}}]}:(WI(a,f),dae(t,n,a,p,f)):{cssAssets:[],jsAssetsWithoutEntry:[],entryAssets:[]}}}};function XI(e,t){const n=vp({name:t.name,version:t.options.version}),a=n&&"remotesInfo"in n&&n.remotesInfo&&ol(n.remotesInfo,e.name).value;return a&&a.matchedVersion?{hostGlobalSnapshot:n,globalSnapshot:H2(),remoteSnapshot:vp({name:e.name,version:a.matchedVersion})}:{hostGlobalSnapshot:void 0,globalSnapshot:H2(),remoteSnapshot:vp({name:e.name,version:"version"in e?e.version:void 0})}}var mae=class{constructor(e){this.loadingHostSnapshot=null,this.manifestCache=new Map,this.hooks=new Ks({beforeLoadRemoteSnapshot:new wn("beforeLoadRemoteSnapshot"),loadSnapshot:new Lr("loadGlobalSnapshot"),loadRemoteSnapshot:new Lr("loadRemoteSnapshot"),afterLoadSnapshot:new Lr("afterLoadSnapshot")}),this.manifestLoading=Qc.__FEDERATION__.__MANIFEST_LOADING__,this.HostInstance=e,this.loaderHook=e.loaderHook}async loadRemoteSnapshotInfo({moduleInfo:e,id:t,initiator:n="loadRemote"}){const{options:a}=this.HostInstance;await this.hooks.lifecycle.beforeLoadRemoteSnapshot.emit({options:a,moduleInfo:e,origin:this.HostInstance});let o=vp({name:this.HostInstance.options.name,version:this.HostInstance.options.version});o||(o={version:this.HostInstance.options.version||"",remoteEntry:"",remotesInfo:{}},cne({[this.HostInstance.options.name]:o})),o&&"remotesInfo"in o&&!ol(o.remotesInfo,e.name).value&&("version"in e||"entry"in e)&&(o.remotesInfo={...o?.remotesInfo,[e.name]:{matchedVersion:"version"in e?e.version:e.entry}});const{hostGlobalSnapshot:p,remoteSnapshot:f,globalSnapshot:m}=this.getGlobalRemoteInfo(e),{remoteSnapshot:h,globalSnapshot:u}=await this.hooks.lifecycle.loadSnapshot.emit({options:a,moduleInfo:e,hostGlobalSnapshot:p,remoteSnapshot:f,globalSnapshot:m});let x,w;if(h)if(hI(h)){const C=Vr?h.remoteEntry:h.ssrRemoteEntry||h.remoteEntry||"",A=await this.loadManifestSnapshot(C,e,{},{initiator:n,id:t||e.name}),R=$2({...e,entry:C},A);x=A,w=R}else{const{remoteSnapshot:C}=await this.hooks.lifecycle.loadRemoteSnapshot.emit({options:this.HostInstance.options,moduleInfo:e,remoteSnapshot:h,from:"global"});x=C,w=u}else if(i0(e)){const C=await this.loadManifestSnapshot(e.entry,e,{},{initiator:n,id:t||e.name}),A=$2(e,C);x=C,w=A}else Xt(zI,ca,{remoteName:e.name,remoteVersion:e.version,hostName:this.HostInstance.options.name,globalSnapshot:JSON.stringify(u)},void 0,Wi(this.HostInstance.options));return await this.hooks.lifecycle.afterLoadSnapshot.emit({id:t,host:this.HostInstance,options:a,moduleInfo:e,remoteSnapshot:x}),{remoteSnapshot:x,globalSnapshot:w}}getGlobalRemoteInfo(e){return XI(e,this.HostInstance)}async getManifestJson(e,t,n,a){return(async()=>{const p=$s(t);let f=this.manifestCache.get(e);if(f)return f;try{let h=await this.loaderHook.lifecycle.fetch.emit(e,{},p,a?{...a,url:e,resourceType:"manifest"}:void 0);(!h||!(h instanceof Response))&&(h=await fetch(e,{})),f=await h.json()}catch(h){f=await this.HostInstance.remoteHandler.hooks.lifecycle.errorLoadRemote.emit({id:e,error:h,from:"runtime",lifecycle:"afterResolve",remote:p,origin:this.HostInstance}),f||(delete this.manifestLoading[e],Xt(jI,ca,{manifestUrl:e,moduleName:t.name,hostName:this.HostInstance.options.name},`${h}`,Wi(this.HostInstance.options)))}const m=[!f.metaData&&"metaData",!f.exposes&&"exposes",!f.shared&&"shared"].filter(Boolean);return m.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: ${m.join(", ")}.`),from:"runtime",lifecycle:"afterResolve",remote:p,origin:this.HostInstance}),m.length>0&&Xt(UI,ca,{manifestUrl:e,moduleName:t.name,hostName:this.HostInstance.options.name,missingFields:m.join(",")},void 0,Wi(this.HostInstance.options)),this.manifestCache.set(e,f),f})()}async loadManifestSnapshot(e,t,n,a){const o=async()=>{const p=await this.getManifestJson(e,t,n,a),f=$te(p,{version:e}),{remoteSnapshot:m}=await this.hooks.lifecycle.loadRemoteSnapshot.emit({options:this.HostInstance.options,moduleInfo:t,manifestJson:p,remoteSnapshot:f,manifestUrl:e,from:"manifest"});return m};return this.manifestLoading[e]||(this.manifestLoading[e]=o().then(p=>p)),this.manifestLoading[e]}},fae=class{constructor(e){this.hooks=new Ks({beforeRegisterShare:new Zs("beforeRegisterShare"),afterResolve:new Lr("afterResolve"),beforeLoadShare:new Lr("beforeLoadShare"),loadShare:new wn,afterLoadShare:new sa("afterLoadShare"),errorLoadShare:new sa("errorLoadShare"),resolveShare:new Zs("resolveShare"),initContainerShareScopeMap:new Zs("initContainerShareScopeMap")}),this.host=e,this.shareScopeMap={},this.initTokens={},this._setGlobalShareScopeMap(e.options)}emitAfterLoadShare({lifecycle:e,pkgName:t,shareInfo:n,selectedShared:a}){try{this.hooks.lifecycle.afterLoadShare.emit({pkgName:t,shareInfo:n,selectedShared:a,shared:this.host.options.shared,shareScopeMap:this.shareScopeMap,lifecycle:e,origin:this.host})}catch(o){$c(o)}}emitErrorLoadShare({lifecycle:e,pkgName:t,shareInfo:n,error:a,recovered:o}){try{this.hooks.lifecycle.errorLoadShare.emit({pkgName:t,shareInfo:n,shared:this.host.options.shared,shareScopeMap:this.shareScopeMap,lifecycle:e,origin:this.host,error:a,recovered:o})}catch(p){$c(p)}}registerShared(e,t){const{newShareInfos:n,allShareInfos:a}=TI(e,t);return Object.keys(n).forEach(o=>{n[o].forEach(p=>{p.scope.forEach(f=>{this.hooks.lifecycle.beforeRegisterShare.emit({origin:this.host,pkgName:o,shared:p}),this.shareScopeMap[f]?.[o]||this.setShared({pkgName:o,lib:p.lib,get:p.get,loaded:p.loaded||!!p.lib,shared:p,from:t.name})})})}),{newShareInfos:n,allShareInfos:a}}async loadShare(e,t){const{host:n}=this,a=W2({pkgName:e,extraOptions:t,shareInfos:n.options.shared});let o=a;try{a?.scope&&await Promise.all(a.scope.map(async h=>{await Promise.all(this.initializeSharing(h,{strategy:a.strategy}))})),o=(await this.hooks.lifecycle.beforeLoadShare.emit({pkgName:e,shareInfo:a,shared:n.options.shared,origin:n})).shareInfo,Zi(o,`Cannot find shared "${e}" in host "${n.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 p=o,{shared:f,useTreesShaking:m}=Sp(this.shareScopeMap,e,o,this.hooks.lifecycle.resolveShare)||{};if(f){const h=$d(f,m);if(h.lib)return Ts(h,n.options.name),this.emitAfterLoadShare({lifecycle:"loadShare",pkgName:e,shareInfo:p,selectedShared:f}),h.lib;if(h.loading&&!h.loaded){const u=await h.loading;return h.loaded=!0,h.lib||(h.lib=u),Ts(h,n.options.name),this.emitAfterLoadShare({lifecycle:"loadShare",pkgName:e,shareInfo:p,selectedShared:f}),u}else{const x=(async()=>{const C=await h.get();return Ts(h,n.options.name),h.loaded=!0,h.lib=C,C})();this.setShared({pkgName:e,loaded:!1,shared:f,from:n.options.name,lib:null,loading:x,treeShaking:m?h:void 0});const w=await x;return this.emitAfterLoadShare({lifecycle:"loadShare",pkgName:e,shareInfo:p,selectedShared:f}),w}}else{if(t?.customShareInfo)return this.emitErrorLoadShare({lifecycle:"loadShare",pkgName:e,shareInfo:p,recovered:!0}),!1;const h=Vc(p.treeShaking),u=$d(p,h),w=(async()=>{const A=await u.get();u.lib=A,u.loaded=!0,Ts(u,n.options.name);const{shared:R,useTreesShaking:I}=Sp(this.shareScopeMap,e,p,this.hooks.lifecycle.resolveShare)||{};if(R){const O=$d(R,I);O.lib=A,O.loaded=!0,R.from=p.from}return A})();this.setShared({pkgName:e,loaded:!1,shared:p,from:n.options.name,lib:null,loading:w,treeShaking:h?u:void 0});const C=await w;return this.emitAfterLoadShare({lifecycle:"loadShare",pkgName:e,shareInfo:p,selectedShared:p}),C}}catch(p){throw this.emitErrorLoadShare({lifecycle:"loadShare",pkgName:e,shareInfo:o,error:p}),p}}initializeSharing(e=Am,t){const{host:n}=this,a=t?.from,o=t?.strategy;let p=t?.initScope;const f=[];if(a!=="build"){const{initTokens:C}=this;p||(p=[]);let A=C[e];if(A||(A=C[e]={from:this.host.name}),p.indexOf(A)>=0)return f;p.push(A)}const m=this.shareScopeMap,h=n.options.name;m[e]||(m[e]={});const u=m[e],x=(C,A)=>{const{version:R,eager:I}=A;u[C]=u[C]||{};const O=u[C],D=O[R]&&$d(O[R]),z=!!(D&&("eager"in D&&D.eager||"shareConfig"in D&&D.shareConfig?.eager));(!D||D.strategy!=="loaded-first"&&!D.loaded&&(!I!=!z?I:h>O[R].from))&&(O[R]=A)},w=async C=>{const{module:A}=await n.remoteHandler.getRemoteModuleAndOptions({id:C});let R;try{R=await A.getEntry()}catch(I){if(R=await n.remoteHandler.hooks.lifecycle.errorLoadRemote.emit({id:C,error:I,from:"runtime",lifecycle:"beforeLoadShare",remote:A.remoteInfo,origin:n}),!R)return}finally{R?.init&&!A.initing&&(A.remoteEntryExports=R,await A.init(void 0,void 0,p))}};return Object.keys(n.options.shared).forEach(C=>{n.options.shared[C].forEach(A=>{A.scope.includes(e)&&x(C,A)})}),(n.options.shareStrategy==="version-first"||o==="version-first")&&n.options.remotes.forEach(C=>{C.shareScope===e&&f.push(w(C.name))}),f}loadShareSync(e,t){const{host:n}=this,a=W2({pkgName:e,extraOptions:t,shareInfos:n.options.shared});try{a?.scope&&a.scope.forEach(p=>{this.initializeSharing(p,{strategy:a.strategy})});const{shared:o}=Sp(this.shareScopeMap,e,a,this.hooks.lifecycle.resolveShare)||{};if(o){if(typeof o.lib=="function")return Ts(o,n.options.name),o.loaded||(o.loaded=!0,o.from===n.options.name&&(a.loaded=!0)),this.emitAfterLoadShare({lifecycle:"loadShareSync",pkgName:e,shareInfo:a,selectedShared:o}),o.lib;if(typeof o.get=="function"){const p=o.get();if(!(p instanceof Promise))return Ts(o,n.options.name),this.setShared({pkgName:e,loaded:!0,from:n.options.name,lib:p,shared:o}),this.emitAfterLoadShare({lifecycle:"loadShareSync",pkgName:e,shareInfo:a,selectedShared:o}),p}}if(a.lib)return a.loaded||(a.loaded=!0),this.emitAfterLoadShare({lifecycle:"loadShareSync",pkgName:e,shareInfo:a,selectedShared:a}),a.lib;if(a.get){const p=a.get();return p instanceof Promise&&Xt(t?.from==="build"?DI:Ay,ca,{hostName:n.options.name,sharedPkgName:e},void 0,Wi(n.options)),a.lib=p,this.setShared({pkgName:e,loaded:!0,from:n.options.name,lib:a.lib,shared:a}),this.emitAfterLoadShare({lifecycle:"loadShareSync",pkgName:e,shareInfo:a,selectedShared:a}),a.lib}Xt(Ay,ca,{hostName:n.options.name,sharedPkgName:e},void 0,Wi(n.options))}catch(o){throw this.emitErrorLoadShare({lifecycle:"loadShareSync",pkgName:e,shareInfo:a,error:o}),o}}initShareScopeMap(e,t,n={}){const{host:a}=this;this.shareScopeMap[e]=t,this.hooks.lifecycle.initContainerShareScopeMap.emit({shareScope:t,options:a.options,origin:a,scopeName:e,hostShareScopeMap:n.hostShareScopeMap})}setShared({pkgName:e,shared:t,from:n,lib:a,loading:o,loaded:p,get:f,treeShaking:m}){const{version:h,scope:u="default",...x}=t,w=Array.isArray(u)?u:[u],C=A=>{const R=(O,D,z)=>{z&&!O[D]&&(O[D]=z)},I=m?A.treeShaking:A;R(I,"loaded",p),R(I,"loading",o),R(I,"get",f)};w.forEach(A=>{this.shareScopeMap[A]||(this.shareScopeMap[A]={}),this.shareScopeMap[A][e]||(this.shareScopeMap[A][e]={}),this.shareScopeMap[A][e][h]||(this.shareScopeMap[A][e][h]={version:h,scope:[A],...x,lib:a});const R=this.shareScopeMap[A][e][h];C(R),n&&R.from!==n&&(R.from=n)})}_setGlobalShareScopeMap(e){const t=II(),n=e.id||e.name;n&&!t[n]&&(t[n]=this.shareScopeMap)}},hae=class{constructor(e){this.hooks=new Ks({beforeRegisterRemote:new Zs("beforeRegisterRemote"),registerRemote:new Zs("registerRemote"),beforeRequest:new Lr("beforeRequest"),afterMatchRemote:new wn("afterMatchRemote"),onLoad:new wn("onLoad"),afterLoadRemote:new wn("afterLoadRemote"),handlePreloadModule:new sa("handlePreloadModule"),errorLoadRemote:new wn("errorLoadRemote"),beforePreloadRemote:new wn("beforePreloadRemote"),generatePreloadAssets:new wn("generatePreloadAssets"),afterPreloadRemote:new wn("afterPreloadRemote"),loadEntry:new wn}),this.host=e,this.idToRemoteMap={}}formatAndRegisterRemote(e,t){return(t.remotes||[]).reduce((n,a)=>(this.registerRemote(a,n,{force:!1}),n),e.remotes)}setIdToRemoteMap(e,t){const{remote:n,expose:a}=t,{name:o,alias:p}=n;if(this.idToRemoteMap[e]={name:n.name,expose:a},p&&e.startsWith(o)){const f=e.replace(o,p);this.idToRemoteMap[f]={name:n.name,expose:a};return}if(p&&e.startsWith(p)){const f=e.replace(p,o);this.idToRemoteMap[f]={name:n.name,expose:a}}}async loadRemote(e,t){const{host:n}=this,a=Y2(n.options.remotes,e);let o=e,p=a?.expose,f=a?$s(a.remote):void 0,m;try{const{loadFactory:h=!0}=t||{loadFactory:!0},{module:u,moduleOptions:x,remoteMatchInfo:w}=await this.getRemoteModuleAndOptions({id:e}),{pkgNameOrAlias:C,remote:A,expose:R,id:I,remoteSnapshot:O}=w;o=I,p=R,f=$s(A);const D=await u.get(I,R,t,O),z=await this.hooks.lifecycle.onLoad.emit({id:I,pkgNameOrAlias:C,expose:R,exposeModule:h?D:void 0,exposeModuleFactory:h?void 0:D,remote:A,options:x,moduleInstance:u,origin:n});return this.setIdToRemoteMap(e,w),m={id:o,expose:p,remote:f,options:t,origin:n},typeof z=="function"?z:D}catch(h){const{from:u="runtime"}=t||{from:"runtime"};let x;try{x=await this.hooks.lifecycle.errorLoadRemote.emit({id:e,error:h,from:u,lifecycle:"onLoad",expose:p,remote:f,origin:n})}catch(w){throw m={id:o,expose:p,remote:f,options:t,error:w,origin:n},w}if(!x)throw m={id:o,expose:p,remote:f,options:t,error:h,origin:n},h;return m={id:o,expose:p,remote:f,options:t,error:h,origin:n,recovered:!0},x}finally{m&&await this.hooks.lifecycle.afterLoadRemote.emit(m)}}async preloadRemote(e){const{host:t}=this,n=[];await this.hooks.lifecycle.beforePreloadRemote.emit({preloadOps:e,options:t.options,origin:t});const a=aae(t.options.remotes,e),o=m=>{const{preloadConfig:h,remote:u}=m,x=h.exposes||[];return x.length?x.map(w=>({ops:{...m,preloadConfig:{...h,exposes:[w]}},id:c0(u.name,w)})):[{ops:m,id:`${u.name}/*`}]};let p;await Promise.all(a.flatMap(o).map(async m=>{const{ops:h,id:u}=m,{remote:x,preloadConfig:w}=h,C=$s(x);try{const{globalSnapshot:A,remoteSnapshot:R}=await t.snapshotHandler.loadRemoteSnapshotInfo({moduleInfo:x,id:u,initiator:"preloadRemote"}),I=await this.hooks.lifecycle.generatePreloadAssets.emit({origin:t,preloadOptions:h,remote:x,remoteInfo:C,globalSnapshot:A,remoteSnapshot:R});if(!I)return;const O=await GI(C,t,I,!0,{initiator:"preloadRemote",id:u});n.push({remote:x,remoteInfo:C,preloadConfig:w,id:u,results:O})}catch(A){n.push({remote:x,remoteInfo:C,preloadConfig:w,id:u,results:[{url:C.entry,status:"error",resourceType:/\.json(?:$|[?#])/i.test(C.entry)?"manifest":"remoteEntry",initiator:"preloadRemote",id:u,error:A}]})}}));const f=n.flatMap(m=>m.results.filter(h=>h.status==="error"||h.status==="timeout"));if(f.length>0&&(p=new Error(`preloadRemote failed to load ${f.length} resource(s).`),Object.assign(p,{results:n,failedResults:f})),await this.hooks.lifecycle.afterPreloadRemote.emit({preloadOps:e,options:t.options,origin:t,results:n,error:p}),p)throw p}registerRemotes(e,t){const{host:n}=this;e.forEach(a=>{this.registerRemote(a,n.options.remotes,{force:t?.force})})}async getRemoteModuleAndOptions(e){const{host:t}=this,{id:n}=e;let a;try{a=await this.hooks.lifecycle.beforeRequest.emit({id:n,options:t.options,origin:t})}catch(A){if(a=await this.hooks.lifecycle.errorLoadRemote.emit({id:n,options:t.options,origin:t,from:"runtime",error:A,lifecycle:"beforeRequest"}),!a)throw A}const{id:o}=a,p=Y2(t.options.remotes,o);if(!p)try{Xt(PI,ca,{hostName:t.options.name,requestId:o},void 0,Wi(t.options))}catch(A){throw await this.hooks.lifecycle.afterMatchRemote.emit({id:o,options:t.options,error:A,origin:t}),A}const{remote:f}=p,m=$s(f);await this.hooks.lifecycle.afterMatchRemote.emit({id:o,...p,options:t.options,remoteInfo:m,origin:t});const h=await t.sharedHandler.hooks.lifecycle.afterResolve.emit({id:o,...p,options:t.options,origin:t,remoteInfo:m}),{remote:u,expose:x}=h;Zi(u&&x,`The 'beforeRequest' hook was executed, but it failed to return the correct 'remote' and 'expose' values while loading ${o}.`);let w=t.moduleCache.get(u.name);const C={host:t,remoteInfo:m};return w||(w=new ZI(C),t.moduleCache.set(u.name,w)),{module:w,moduleOptions:C,remoteMatchInfo:h}}registerRemote(e,t,n){const{host:a}=this,o=()=>{if(e.alias){const f=t.find(m=>e.alias&&(m.name.startsWith(e.alias)||m.alias?.startsWith(e.alias)));Zi(!f,`The alias ${e.alias} of remote ${e.name} is not allowed to be the prefix of ${f&&f.name} name or alias`)}"entry"in e&&Vr&&typeof window<"u"&&!e.entry.startsWith("http")&&(e.entry=new URL(e.entry,window.location.origin).href),e.shareScope||(e.shareScope=Am),e.type||(e.type=qne)};this.hooks.lifecycle.beforeRegisterRemote.emit({remote:e,origin:a});const p=t.find(f=>f.name===e.name);if(!p)o(),t.push(e),this.hooks.lifecycle.registerRemote.emit({remote:e,origin:a});else{const f=[`The remote "${e.name}" is already registered.`,"Please note that overriding it may cause unexpected errors."];n?.force&&(this.removeRemote(p),o(),t.push(e),this.hooks.lifecycle.registerRemote.emit({remote:e,origin:a}),mI(f.join(" ")))}}removeRemote(e){try{const{host:t}=this,{name:n}=e,a=t.options.remotes.findIndex(p=>p.name===n);a!==-1&&t.options.remotes.splice(a,1);const o=t.moduleCache.get(e.name);if(o){const p=o.remoteInfo,f=p.entryGlobalName;Dn[f]&&(Object.getOwnPropertyDescriptor(Dn,f)?.configurable?delete Dn[f]:Dn[f]=void 0);const m=Ey(o.remoteInfo);Hs[m]&&delete Hs[m],t.snapshotHandler.manifestCache.delete(p.entry);let h=p.buildVersion?pI(p.name,p.buildVersion):p.name;const u=Dn.__FEDERATION__.__INSTANCES__.findIndex(w=>p.buildVersion?w.options.id===h:w.name===h);if(u!==-1){const w=Dn.__FEDERATION__.__INSTANCES__[u];h=w.options.id||h;const C=II();let A=!0;const R=[];Object.keys(C).forEach(I=>{const O=C[I];O&&Object.keys(O).forEach(D=>{const z=O[D];z&&Object.keys(z).forEach(B=>{const q=z[B];q&&Object.keys(q).forEach(G=>{const ae=q[G];ae&&typeof ae=="object"&&ae.from===p.name&&(ae.loaded||ae.loading?(ae.useIn=ae.useIn.filter(Q=>Q!==p.name),ae.useIn.length?A=!1:R.push([I,D,B,G])):R.push([I,D,B,G]))})})})}),A&&(w.shareScopeMap={},delete C[h]),R.forEach(([I,O,D,z])=>{delete C[I]?.[O]?.[D]?.[z]}),Dn.__FEDERATION__.__INSTANCES__.splice(u,1)}const{hostGlobalSnapshot:x}=XI(e,t);if(x){const w=x&&"remotesInfo"in x&&x.remotesInfo&&ol(x.remotesInfo,e.name).key;w&&(delete x.remotesInfo[w],Qc.__FEDERATION__.__MANIFEST_LOADING__[w]&&delete Qc.__FEDERATION__.__MANIFEST_LOADING__[w])}t.moduleCache.delete(e.name)}}catch(t){Cy.error(`removeRemote failed: ${t instanceof Error?t.message:String(t)}`)}}},gae=typeof FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN=="boolean"?!FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN:!0,vae=class{constructor(e){this.hooks=new Ks({beforeInit:new Zs("beforeInit"),init:new sa,beforeInitContainer:new Lr("beforeInitContainer"),initContainer:new Lr("initContainer")}),this.version="2.5.1",this.moduleCache=new Map,this.loaderHook=new Ks({getModuleInfo:new sa,createScript:new sa,createLink:new sa,fetch:new wn,loadEntryError:new wn,afterLoadEntry:new wn("afterLoadEntry"),beforeInitRemote:new wn("beforeInitRemote"),afterInitRemote:new wn("afterInitRemote"),beforeGetExpose:new wn("beforeGetExpose"),afterGetExpose:new wn("afterGetExpose"),beforeExecuteFactory:new wn("beforeExecuteFactory"),afterExecuteFactory:new wn("afterExecuteFactory"),getModuleFactory:new wn}),this.bridgeHook=new Ks({beforeBridgeRender:new sa,afterBridgeRender:new sa,beforeBridgeDestroy:new sa,afterBridgeDestroy:new sa});const t=gae?[cae(),pae()]:[],n={id:eae(),name:e.name,plugins:t,remotes:[],shared:{},inBrowser:Vr};this.name=e.name,this.options=n,this.snapshotHandler=new mae(this),this.sharedHandler=new fae(this),this.remoteHandler=new hae(this),this.shareScopeMap=this.sharedHandler.shareScopeMap,this.registerPlugins([...n.plugins,...e.plugins||[]]),this.options=this.formatOptions(n,e)}initOptions(e){e.name&&e.name!==this.options.name&&Xt(SI(qI,ca)),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=Am,t){return this.sharedHandler.initializeSharing(e,t)}initRawContainer(e,t,n){const a=$s({name:e,entry:t}),o=new ZI({host:this,remoteInfo:a});return o.remoteEntryExports=n,this.moduleCache.set(e,o),o}async loadRemote(e,t){return this.remoteHandler.loadRemote(e,t)}async preloadRemote(e){return this.remoteHandler.preloadRemote(e)}initShareScopeMap(e,t,n={}){this.sharedHandler.initShareScopeMap(e,t,n)}formatOptions(e,t){const{allShareInfos:n}=TI(e,t),{userOptions:a,options:o}=this.hooks.lifecycle.beforeInit.emit({origin:this,userOptions:t,options:e,shareInfo:n}),p=this.remoteHandler.formatAndRegisterRemote(o,a),{allShareInfos:f}=this.sharedHandler.registerShared(o,a),m=[...o.plugins];a.plugins&&a.plugins.forEach(u=>{m.includes(u)||m.push(u)});const h={...e,...t,plugins:m,remotes:p,shared:f,id:a.id||e.id};return this.hooks.lifecycle.init.emit({origin:this,options:h}),h}registerPlugins(e){const t=tae(e,this);this.options.plugins=this.options.plugins.reduce((n,a)=>(a&&n&&!n.find(o=>o.name===a.name)&&n.push(a),n),t||[])}registerRemotes(e,t){return this.remoteHandler.registerRemotes(e,t)}registerShared(e){this.sharedHandler.registerShared(this.options,{...this.options,shared:e})}};sne(vae);gi("camstack:widget-registry",null);function ehe({title:e,icon:t,headerRight:n,collapsible:a=!1,defaultOpen:o=!0,bodyClassName:p="p-3",children:f}){const[m,h]=T.useState(o),u=!a||m,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]}),a?m?v.jsx(zo,{className:"h-3.5 w-3.5 text-foreground-subtle"}):v.jsx(Nee,{className:"h-3.5 w-3.5 text-foreground-subtle"}):n]}),w=`px-4 py-2 flex items-center justify-between ${u?"border-b border-border":""}`;return v.jsxs("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[a?v.jsx("button",{type:"button",onClick:()=>h(C=>!C),className:`w-full text-left ${w}`,children:x}):v.jsx("div",{className:w,children:x}),u?v.jsx("div",{className:p,children:f}):null]})}var yae="capability.binding-changed";function mu(e,t){const[n,a]=T.useState(null);return T.useEffect(()=>{if(t===null){a(null);return}let o=!1;const p=async()=>{try{const m=await e.deviceManager.getBindings.query({deviceId:t});o||a(m)}catch{o||a(m=>m)}};p();const f=e.live?.onEvent.subscribe({category:yae},{onData:m=>{const h=m.data?.source;if(!h){p();return}h.type==="device"&&h.id===t&&p()}});return()=>{o=!0,f?.unsubscribe()}},[e,t]),T.useMemo(()=>n?HE(e,n):null,[e,n])}function To(e){const t=T.useCallback(a=>e?e.subscribe(()=>a()):()=>{},[e]),n=T.useCallback(()=>e?.value,[e]);return T.useSyncExternalStore(t,n,n)}function ft(e){const t=mu(e.trpc,e.deviceId),n=To(t!==null?e.slice(t):void 0),a=t!==null?e.cap(t):void 0,o=To(t!==null?t.state.deviceStatus:void 0),p=o?.online??!0,f=p?null:o?.lastChangedAt??null;return{dev:t,cap:a,slice:n,available:(e.requireFeature===void 0||(e.deviceFeatures??[]).includes(e.requireFeature))&&a!==void 0&&n!==void 0&&p,online:p,offlineSince:f}}function bae(e){if(e==null||typeof e!="object")return null;const t=Reflect.get(e,"data");if(t!=null&&typeof t=="object"){const n=Reflect.get(t,"capRouteReason");if(typeof n=="string")return n}return null}function the(e){const t=bae(e);return t!==null?t==="no-provider"||t==="node-offline":(e instanceof Error?e.message:String(e)).includes("provider not available")}function JI(e){var t,n,a="";if(typeof e=="string"||typeof e=="number")a+=e;else if(typeof e=="object")if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(n=JI(e[t]))&&(a&&(a+=" "),a+=n)}else for(n in e)e[n]&&(a&&(a+=" "),a+=n);return a}function e4(){for(var e,t,n=0,a="",o=arguments.length;n<o;n++)(e=arguments[n])&&(t=JI(e))&&(a&&(a+=" "),a+=t);return a}var Sae=(e,t)=>{const n=new Array(e.length+t.length);for(let a=0;a<e.length;a++)n[a]=e[a];for(let a=0;a<t.length;a++)n[e.length+a]=t[a];return n},xae=(e,t)=>({classGroupId:e,validator:t}),t4=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Yp="-",X2=[],kae="arbitrary..",wae=e=>{const t=Cae(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:a}=e;return{getClassGroupId:f=>{if(f.startsWith("[")&&f.endsWith("]"))return Mae(f);const m=f.split(Yp);return n4(m,m[0]===""&&m.length>1?1:0,t)},getConflictingClassGroupIds:(f,m)=>{if(m){const h=a[f],u=n[f];return h?u?Sae(u,h):h:u||X2}return n[f]||X2}}},n4=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const a=e[t],o=n.nextPart.get(a);if(o){const h=n4(e,t+1,o);if(h)return h}const p=n.validators;if(p===null)return;const f=t===0?e.join(Yp):e.slice(t).join(Yp),m=p.length;for(let h=0;h<m;h++){const u=p[h];if(u.validator(f))return u.classGroupId}},Mae=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),a=t.slice(0,n);return a?kae+a:void 0})(),Cae=e=>{const{theme:t,classGroups:n}=e;return Aae(n,t)},Aae=(e,t)=>{const n=t4();for(const a in e){const o=e[a];p0(o,n,a,t)}return n},p0=(e,t,n,a)=>{const o=e.length;for(let p=0;p<o;p++){const f=e[p];Eae(f,t,n,a)}},Eae=(e,t,n,a)=>{if(typeof e=="string"){Rae(e,t,n);return}if(typeof e=="function"){_ae(e,t,n,a);return}Tae(e,t,n,a)},Rae=(e,t,n)=>{const a=e===""?t:a4(t,e);a.classGroupId=n},_ae=(e,t,n,a)=>{if(Iae(e)){p0(e(a),t,n,a);return}t.validators===null&&(t.validators=[]),t.validators.push(xae(n,e))},Tae=(e,t,n,a)=>{const o=Object.entries(e),p=o.length;for(let f=0;f<p;f++){const[m,h]=o[f];p0(h,a4(t,m),n,a)}},a4=(e,t)=>{let n=e;const a=t.split(Yp),o=a.length;for(let p=0;p<o;p++){const f=a[p];let m=n.nextPart.get(f);m||(m=t4(),n.nextPart.set(f,m)),n=m}return n},Iae=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,Nae=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),a=Object.create(null);const o=(p,f)=>{n[p]=f,t++,t>e&&(t=0,a=n,n=Object.create(null))};return{get(p){let f=n[p];if(f!==void 0)return f;if((f=a[p])!==void 0)return o(p,f),f},set(p,f){p in n?n[p]=f:o(p,f)}}},Ry="!",J2=":",Oae=[],eC=(e,t,n,a,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:a,isExternal:o}),jae=e=>{const{prefix:t,experimentalParseClassName:n}=e;let a=o=>{const p=[];let f=0,m=0,h=0,u;const x=o.length;for(let I=0;I<x;I++){const O=o[I];if(f===0&&m===0){if(O===J2){p.push(o.slice(h,I)),h=I+1;continue}if(O==="/"){u=I;continue}}O==="["?f++:O==="]"?f--:O==="("?m++:O===")"&&m--}const w=p.length===0?o:o.slice(h);let C=w,A=!1;w.endsWith(Ry)?(C=w.slice(0,-1),A=!0):w.startsWith(Ry)&&(C=w.slice(1),A=!0);const R=u&&u>h?u-h:void 0;return eC(p,A,C,R)};if(t){const o=t+J2,p=a;a=f=>f.startsWith(o)?p(f.slice(o.length)):eC(Oae,!1,f,void 0,!0)}if(n){const o=a;a=p=>n({className:p,parseClassName:o})}return a},Pae=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,a)=>{t.set(n,1e6+a)}),n=>{const a=[];let o=[];for(let p=0;p<n.length;p++){const f=n[p],m=f[0]==="[",h=t.has(f);m||h?(o.length>0&&(o.sort(),a.push(...o),o=[]),a.push(f)):o.push(f)}return o.length>0&&(o.sort(),a.push(...o)),a}},Dae=e=>({cache:Nae(e.cacheSize),parseClassName:jae(e),sortModifiers:Pae(e),postfixLookupClassGroupIds:zae(e),...wae(e)}),zae=e=>{const t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let a=0;a<n.length;a++)t[n[a]]=!0;return t},Lae=/\s+/,qae=(e,t)=>{const{parseClassName:n,getClassGroupId:a,getConflictingClassGroupIds:o,sortModifiers:p,postfixLookupClassGroupIds:f}=t,m=[],h=e.trim().split(Lae);let u="";for(let x=h.length-1;x>=0;x-=1){const w=h[x],{isExternal:C,modifiers:A,hasImportantModifier:R,baseClassName:I,maybePostfixModifierPosition:O}=n(w);if(C){u=w+(u.length>0?" "+u:u);continue}let D=!!O,z;if(D){z=a(I.substring(0,O));const Q=z&&f[z]?a(I):void 0;Q&&Q!==z&&(z=Q,D=!1)}else z=a(I);if(!z){if(!D){u=w+(u.length>0?" "+u:u);continue}if(z=a(I),!z){u=w+(u.length>0?" "+u:u);continue}D=!1}const B=A.length===0?"":A.length===1?A[0]:p(A).join(":"),q=R?B+Ry:B,G=q+z;if(m.indexOf(G)>-1)continue;m.push(G);const ae=o(z,D);for(let Q=0;Q<ae.length;++Q){const H=ae[Q];m.push(q+H)}u=w+(u.length>0?" "+u:u)}return u},Bae=(...e)=>{let t=0,n,a,o="";for(;t<e.length;)(n=e[t++])&&(a=i4(n))&&(o&&(o+=" "),o+=a);return o},i4=e=>{if(typeof e=="string")return e;let t,n="";for(let a=0;a<e.length;a++)e[a]&&(t=i4(e[a]))&&(n&&(n+=" "),n+=t);return n},Uae=(e,...t)=>{let n,a,o,p;const f=h=>(n=Dae(t.reduce((u,x)=>x(u),e())),a=n.cache.get,o=n.cache.set,p=m,m(h)),m=h=>{const u=a(h);if(u)return u;const x=qae(h,n);return o(h,x),x};return p=f,(...h)=>p(Bae(...h))},Fae=[],En=e=>{const t=n=>n[e]||Fae;return t.isThemeGetter=!0,t},r4=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,o4=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Hae=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,$ae=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Qae=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Vae=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Gae=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Zae=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,_r=e=>Hae.test(e),ct=e=>!!e&&!Number.isNaN(Number(e)),ci=e=>!!e&&Number.isInteger(Number(e)),Dg=e=>e.endsWith("%")&&ct(e.slice(0,-1)),Hi=e=>$ae.test(e),s4=()=>!0,Kae=e=>Qae.test(e)&&!Vae.test(e),m0=()=>!1,Wae=e=>Gae.test(e),Yae=e=>Zae.test(e),Xae=e=>!je(e)&&!Pe(e),Jae=e=>e.startsWith("@container")&&(e[10]==="/"&&e[11]!==void 0||e[11]==="s"&&e[16]!==void 0&&e.startsWith("-size/",10)||e[11]==="n"&&e[18]!==void 0&&e.startsWith("-normal/",10)),eie=e=>Gr(e,u4,m0),je=e=>r4.test(e),go=e=>Gr(e,d4,Kae),tC=e=>Gr(e,lie,ct),tie=e=>Gr(e,m4,s4),nie=e=>Gr(e,p4,m0),nC=e=>Gr(e,l4,m0),aie=e=>Gr(e,c4,Yae),Qd=e=>Gr(e,f4,Wae),Pe=e=>o4.test(e),fc=e=>qo(e,d4),iie=e=>qo(e,p4),aC=e=>qo(e,l4),rie=e=>qo(e,u4),oie=e=>qo(e,c4),Vd=e=>qo(e,f4,!0),sie=e=>qo(e,m4,!0),Gr=(e,t,n)=>{const a=r4.exec(e);return a?a[1]?t(a[1]):n(a[2]):!1},qo=(e,t,n=!1)=>{const a=o4.exec(e);return a?a[1]?t(a[1]):n:!1},l4=e=>e==="position"||e==="percentage",c4=e=>e==="image"||e==="url",u4=e=>e==="length"||e==="size"||e==="bg-size",d4=e=>e==="length",lie=e=>e==="number",p4=e=>e==="family-name",m4=e=>e==="number"||e==="weight",f4=e=>e==="shadow",cie=()=>{const e=En("color"),t=En("font"),n=En("text"),a=En("font-weight"),o=En("tracking"),p=En("leading"),f=En("breakpoint"),m=En("container"),h=En("spacing"),u=En("radius"),x=En("shadow"),w=En("inset-shadow"),C=En("text-shadow"),A=En("drop-shadow"),R=En("blur"),I=En("perspective"),O=En("aspect"),D=En("ease"),z=En("animate"),B=()=>["auto","avoid","all","avoid-page","page","left","right","column"],q=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],G=()=>[...q(),Pe,je],ae=()=>["auto","hidden","clip","visible","scroll"],Q=()=>["auto","contain","none"],H=()=>[Pe,je,h],oe=()=>[_r,"full","auto",...H()],we=()=>[ci,"none","subgrid",Pe,je],Me=()=>["auto",{span:["full",ci,Pe,je]},ci,Pe,je],Ae=()=>[ci,"auto",Pe,je],Ce=()=>["auto","min","max","fr",Pe,je],re=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],Te=()=>["start","end","center","stretch","center-safe","end-safe"],F=()=>["auto",...H()],ue=()=>[_r,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...H()],ke=()=>[_r,"screen","full","dvw","lvw","svw","min","max","fit",...H()],Ee=()=>[_r,"screen","full","lh","dvh","lvh","svh","min","max","fit",...H()],fe=()=>[e,Pe,je],L=()=>[...q(),aC,nC,{position:[Pe,je]}],ee=()=>["no-repeat",{repeat:["","x","y","space","round"]}],me=()=>["auto","cover","contain",rie,eie,{size:[Pe,je]}],be=()=>[Dg,fc,go],X=()=>["","none","full",u,Pe,je],xe=()=>["",ct,fc,go],Oe=()=>["solid","dashed","dotted","double"],le=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ye=()=>[ct,Dg,aC,nC],Be=()=>["","none",R,Pe,je],ot=()=>["none",ct,Pe,je],Ve=()=>["none",ct,Pe,je],Ie=()=>[ct,Pe,je],bt=()=>[_r,"full",...H()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Hi],breakpoint:[Hi],color:[s4],container:[Hi],"drop-shadow":[Hi],ease:["in","out","in-out"],font:[Xae],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Hi],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Hi],shadow:[Hi],spacing:["px",ct],text:[Hi],"text-shadow":[Hi],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",_r,je,Pe,O]}],container:["container"],"container-type":[{"@container":["","normal","size",Pe,je]}],"container-named":[Jae],columns:[{columns:[ct,je,Pe,m]}],"break-after":[{"break-after":B()}],"break-before":[{"break-before":B()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:G()}],overflow:[{overflow:ae()}],"overflow-x":[{"overflow-x":ae()}],"overflow-y":[{"overflow-y":ae()}],overscroll:[{overscroll:Q()}],"overscroll-x":[{"overscroll-x":Q()}],"overscroll-y":[{"overscroll-y":Q()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:oe()}],"inset-x":[{"inset-x":oe()}],"inset-y":[{"inset-y":oe()}],start:[{"inset-s":oe(),start:oe()}],end:[{"inset-e":oe(),end:oe()}],"inset-bs":[{"inset-bs":oe()}],"inset-be":[{"inset-be":oe()}],top:[{top:oe()}],right:[{right:oe()}],bottom:[{bottom:oe()}],left:[{left:oe()}],visibility:["visible","invisible","collapse"],z:[{z:[ci,"auto",Pe,je]}],basis:[{basis:[_r,"full","auto",m,...H()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ct,_r,"auto","initial","none",je]}],grow:[{grow:["",ct,Pe,je]}],shrink:[{shrink:["",ct,Pe,je]}],order:[{order:[ci,"first","last","none",Pe,je]}],"grid-cols":[{"grid-cols":we()}],"col-start-end":[{col:Me()}],"col-start":[{"col-start":Ae()}],"col-end":[{"col-end":Ae()}],"grid-rows":[{"grid-rows":we()}],"row-start-end":[{row:Me()}],"row-start":[{"row-start":Ae()}],"row-end":[{"row-end":Ae()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":Ce()}],"auto-rows":[{"auto-rows":Ce()}],gap:[{gap:H()}],"gap-x":[{"gap-x":H()}],"gap-y":[{"gap-y":H()}],"justify-content":[{justify:[...re(),"normal"]}],"justify-items":[{"justify-items":[...Te(),"normal"]}],"justify-self":[{"justify-self":["auto",...Te()]}],"align-content":[{content:["normal",...re()]}],"align-items":[{items:[...Te(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...Te(),{baseline:["","last"]}]}],"place-content":[{"place-content":re()}],"place-items":[{"place-items":[...Te(),"baseline"]}],"place-self":[{"place-self":["auto",...Te()]}],p:[{p:H()}],px:[{px:H()}],py:[{py:H()}],ps:[{ps:H()}],pe:[{pe:H()}],pbs:[{pbs:H()}],pbe:[{pbe:H()}],pt:[{pt:H()}],pr:[{pr:H()}],pb:[{pb:H()}],pl:[{pl:H()}],m:[{m:F()}],mx:[{mx:F()}],my:[{my:F()}],ms:[{ms:F()}],me:[{me:F()}],mbs:[{mbs:F()}],mbe:[{mbe:F()}],mt:[{mt:F()}],mr:[{mr:F()}],mb:[{mb:F()}],ml:[{ml:F()}],"space-x":[{"space-x":H()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":H()}],"space-y-reverse":["space-y-reverse"],size:[{size:ue()}],"inline-size":[{inline:["auto",...ke()]}],"min-inline-size":[{"min-inline":["auto",...ke()]}],"max-inline-size":[{"max-inline":["none",...ke()]}],"block-size":[{block:["auto",...Ee()]}],"min-block-size":[{"min-block":["auto",...Ee()]}],"max-block-size":[{"max-block":["none",...Ee()]}],w:[{w:[m,"screen",...ue()]}],"min-w":[{"min-w":[m,"screen","none",...ue()]}],"max-w":[{"max-w":[m,"screen","none","prose",{screen:[f]},...ue()]}],h:[{h:["screen","lh",...ue()]}],"min-h":[{"min-h":["screen","lh","none",...ue()]}],"max-h":[{"max-h":["screen","lh",...ue()]}],"font-size":[{text:["base",n,fc,go]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,sie,tie]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Dg,je]}],"font-family":[{font:[iie,nie,t]}],"font-features":[{"font-features":[je]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[o,Pe,je]}],"line-clamp":[{"line-clamp":[ct,"none",Pe,tC]}],leading:[{leading:[p,...H()]}],"list-image":[{"list-image":["none",Pe,je]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Pe,je]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:fe()}],"text-color":[{text:fe()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Oe(),"wavy"]}],"text-decoration-thickness":[{decoration:[ct,"from-font","auto",Pe,go]}],"text-decoration-color":[{decoration:fe()}],"underline-offset":[{"underline-offset":[ct,"auto",Pe,je]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:H()}],"tab-size":[{tab:[ci,Pe,je]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Pe,je]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Pe,je]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:L()}],"bg-repeat":[{bg:ee()}],"bg-size":[{bg:me()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},ci,Pe,je],radial:["",Pe,je],conic:[ci,Pe,je]},oie,aie]}],"bg-color":[{bg:fe()}],"gradient-from-pos":[{from:be()}],"gradient-via-pos":[{via:be()}],"gradient-to-pos":[{to:be()}],"gradient-from":[{from:fe()}],"gradient-via":[{via:fe()}],"gradient-to":[{to:fe()}],rounded:[{rounded:X()}],"rounded-s":[{"rounded-s":X()}],"rounded-e":[{"rounded-e":X()}],"rounded-t":[{"rounded-t":X()}],"rounded-r":[{"rounded-r":X()}],"rounded-b":[{"rounded-b":X()}],"rounded-l":[{"rounded-l":X()}],"rounded-ss":[{"rounded-ss":X()}],"rounded-se":[{"rounded-se":X()}],"rounded-ee":[{"rounded-ee":X()}],"rounded-es":[{"rounded-es":X()}],"rounded-tl":[{"rounded-tl":X()}],"rounded-tr":[{"rounded-tr":X()}],"rounded-br":[{"rounded-br":X()}],"rounded-bl":[{"rounded-bl":X()}],"border-w":[{border:xe()}],"border-w-x":[{"border-x":xe()}],"border-w-y":[{"border-y":xe()}],"border-w-s":[{"border-s":xe()}],"border-w-e":[{"border-e":xe()}],"border-w-bs":[{"border-bs":xe()}],"border-w-be":[{"border-be":xe()}],"border-w-t":[{"border-t":xe()}],"border-w-r":[{"border-r":xe()}],"border-w-b":[{"border-b":xe()}],"border-w-l":[{"border-l":xe()}],"divide-x":[{"divide-x":xe()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":xe()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Oe(),"hidden","none"]}],"divide-style":[{divide:[...Oe(),"hidden","none"]}],"border-color":[{border:fe()}],"border-color-x":[{"border-x":fe()}],"border-color-y":[{"border-y":fe()}],"border-color-s":[{"border-s":fe()}],"border-color-e":[{"border-e":fe()}],"border-color-bs":[{"border-bs":fe()}],"border-color-be":[{"border-be":fe()}],"border-color-t":[{"border-t":fe()}],"border-color-r":[{"border-r":fe()}],"border-color-b":[{"border-b":fe()}],"border-color-l":[{"border-l":fe()}],"divide-color":[{divide:fe()}],"outline-style":[{outline:[...Oe(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ct,Pe,je]}],"outline-w":[{outline:["",ct,fc,go]}],"outline-color":[{outline:fe()}],shadow:[{shadow:["","none",x,Vd,Qd]}],"shadow-color":[{shadow:fe()}],"inset-shadow":[{"inset-shadow":["none",w,Vd,Qd]}],"inset-shadow-color":[{"inset-shadow":fe()}],"ring-w":[{ring:xe()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:fe()}],"ring-offset-w":[{"ring-offset":[ct,go]}],"ring-offset-color":[{"ring-offset":fe()}],"inset-ring-w":[{"inset-ring":xe()}],"inset-ring-color":[{"inset-ring":fe()}],"text-shadow":[{"text-shadow":["none",C,Vd,Qd]}],"text-shadow-color":[{"text-shadow":fe()}],opacity:[{opacity:[ct,Pe,je]}],"mix-blend":[{"mix-blend":[...le(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":le()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[ct]}],"mask-image-linear-from-pos":[{"mask-linear-from":ye()}],"mask-image-linear-to-pos":[{"mask-linear-to":ye()}],"mask-image-linear-from-color":[{"mask-linear-from":fe()}],"mask-image-linear-to-color":[{"mask-linear-to":fe()}],"mask-image-t-from-pos":[{"mask-t-from":ye()}],"mask-image-t-to-pos":[{"mask-t-to":ye()}],"mask-image-t-from-color":[{"mask-t-from":fe()}],"mask-image-t-to-color":[{"mask-t-to":fe()}],"mask-image-r-from-pos":[{"mask-r-from":ye()}],"mask-image-r-to-pos":[{"mask-r-to":ye()}],"mask-image-r-from-color":[{"mask-r-from":fe()}],"mask-image-r-to-color":[{"mask-r-to":fe()}],"mask-image-b-from-pos":[{"mask-b-from":ye()}],"mask-image-b-to-pos":[{"mask-b-to":ye()}],"mask-image-b-from-color":[{"mask-b-from":fe()}],"mask-image-b-to-color":[{"mask-b-to":fe()}],"mask-image-l-from-pos":[{"mask-l-from":ye()}],"mask-image-l-to-pos":[{"mask-l-to":ye()}],"mask-image-l-from-color":[{"mask-l-from":fe()}],"mask-image-l-to-color":[{"mask-l-to":fe()}],"mask-image-x-from-pos":[{"mask-x-from":ye()}],"mask-image-x-to-pos":[{"mask-x-to":ye()}],"mask-image-x-from-color":[{"mask-x-from":fe()}],"mask-image-x-to-color":[{"mask-x-to":fe()}],"mask-image-y-from-pos":[{"mask-y-from":ye()}],"mask-image-y-to-pos":[{"mask-y-to":ye()}],"mask-image-y-from-color":[{"mask-y-from":fe()}],"mask-image-y-to-color":[{"mask-y-to":fe()}],"mask-image-radial":[{"mask-radial":[Pe,je]}],"mask-image-radial-from-pos":[{"mask-radial-from":ye()}],"mask-image-radial-to-pos":[{"mask-radial-to":ye()}],"mask-image-radial-from-color":[{"mask-radial-from":fe()}],"mask-image-radial-to-color":[{"mask-radial-to":fe()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":q()}],"mask-image-conic-pos":[{"mask-conic":[ct]}],"mask-image-conic-from-pos":[{"mask-conic-from":ye()}],"mask-image-conic-to-pos":[{"mask-conic-to":ye()}],"mask-image-conic-from-color":[{"mask-conic-from":fe()}],"mask-image-conic-to-color":[{"mask-conic-to":fe()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:L()}],"mask-repeat":[{mask:ee()}],"mask-size":[{mask:me()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Pe,je]}],filter:[{filter:["","none",Pe,je]}],blur:[{blur:Be()}],brightness:[{brightness:[ct,Pe,je]}],contrast:[{contrast:[ct,Pe,je]}],"drop-shadow":[{"drop-shadow":["","none",A,Vd,Qd]}],"drop-shadow-color":[{"drop-shadow":fe()}],grayscale:[{grayscale:["",ct,Pe,je]}],"hue-rotate":[{"hue-rotate":[ct,Pe,je]}],invert:[{invert:["",ct,Pe,je]}],saturate:[{saturate:[ct,Pe,je]}],sepia:[{sepia:["",ct,Pe,je]}],"backdrop-filter":[{"backdrop-filter":["","none",Pe,je]}],"backdrop-blur":[{"backdrop-blur":Be()}],"backdrop-brightness":[{"backdrop-brightness":[ct,Pe,je]}],"backdrop-contrast":[{"backdrop-contrast":[ct,Pe,je]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ct,Pe,je]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ct,Pe,je]}],"backdrop-invert":[{"backdrop-invert":["",ct,Pe,je]}],"backdrop-opacity":[{"backdrop-opacity":[ct,Pe,je]}],"backdrop-saturate":[{"backdrop-saturate":[ct,Pe,je]}],"backdrop-sepia":[{"backdrop-sepia":["",ct,Pe,je]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":H()}],"border-spacing-x":[{"border-spacing-x":H()}],"border-spacing-y":[{"border-spacing-y":H()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Pe,je]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ct,"initial",Pe,je]}],ease:[{ease:["linear","initial",D,Pe,je]}],delay:[{delay:[ct,Pe,je]}],animate:[{animate:["none",z,Pe,je]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[I,Pe,je]}],"perspective-origin":[{"perspective-origin":G()}],rotate:[{rotate:ot()}],"rotate-x":[{"rotate-x":ot()}],"rotate-y":[{"rotate-y":ot()}],"rotate-z":[{"rotate-z":ot()}],scale:[{scale:Ve()}],"scale-x":[{"scale-x":Ve()}],"scale-y":[{"scale-y":Ve()}],"scale-z":[{"scale-z":Ve()}],"scale-3d":["scale-3d"],skew:[{skew:Ie()}],"skew-x":[{"skew-x":Ie()}],"skew-y":[{"skew-y":Ie()}],transform:[{transform:[Pe,je,"","none","gpu","cpu"]}],"transform-origin":[{origin:G()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:bt()}],"translate-x":[{"translate-x":bt()}],"translate-y":[{"translate-y":bt()}],"translate-z":[{"translate-z":bt()}],"translate-none":["translate-none"],zoom:[{zoom:[ci,Pe,je]}],accent:[{accent:fe()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:fe()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Pe,je]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":fe()}],"scrollbar-track-color":[{"scrollbar-track":fe()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":H()}],"scroll-mx":[{"scroll-mx":H()}],"scroll-my":[{"scroll-my":H()}],"scroll-ms":[{"scroll-ms":H()}],"scroll-me":[{"scroll-me":H()}],"scroll-mbs":[{"scroll-mbs":H()}],"scroll-mbe":[{"scroll-mbe":H()}],"scroll-mt":[{"scroll-mt":H()}],"scroll-mr":[{"scroll-mr":H()}],"scroll-mb":[{"scroll-mb":H()}],"scroll-ml":[{"scroll-ml":H()}],"scroll-p":[{"scroll-p":H()}],"scroll-px":[{"scroll-px":H()}],"scroll-py":[{"scroll-py":H()}],"scroll-ps":[{"scroll-ps":H()}],"scroll-pe":[{"scroll-pe":H()}],"scroll-pbs":[{"scroll-pbs":H()}],"scroll-pbe":[{"scroll-pbe":H()}],"scroll-pt":[{"scroll-pt":H()}],"scroll-pr":[{"scroll-pr":H()}],"scroll-pb":[{"scroll-pb":H()}],"scroll-pl":[{"scroll-pl":H()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Pe,je]}],fill:[{fill:["none",...fe()]}],"stroke-w":[{stroke:[ct,fc,go,tC]}],stroke:[{stroke:["none",...fe()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},uie=Uae(cie);function se(...e){return uie(e4(e))}gi("camstack:vod-playback",{request:null,play:()=>{},clear:()=>{}});gi("camstack:recorded-playback",{bindControlChannel:null,channelOpen:!1,mode:"live",positionMs:null,send:()=>!1});T.lazy(()=>Ys(()=>import("./MotionZonesSettings-DNdnFHso-2_mSC4yb.js"),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.MotionZonesSettings}))),T.lazy(()=>Ys(()=>import("./PrivacyMaskSettings-DNSLc6ww-BjMyK6YA.js"),__vite__mapDeps([2,1]),import.meta.url).then(e=>({default:e.PrivacyMaskSettings})));var die=Object.defineProperty,Xp=Object.getOwnPropertySymbols,h4=Object.prototype.hasOwnProperty,g4=Object.prototype.propertyIsEnumerable,iC=(e,t,n)=>t in e?die(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,_y=(e,t)=>{for(var n in t||(t={}))h4.call(t,n)&&iC(e,n,t[n]);if(Xp)for(var n of Xp(t))g4.call(t,n)&&iC(e,n,t[n]);return e},Ty=(e,t)=>{var n={};for(var a in e)h4.call(e,a)&&t.indexOf(a)<0&&(n[a]=e[a]);if(e!=null&&Xp)for(var a of Xp(e))t.indexOf(a)<0&&g4.call(e,a)&&(n[a]=e[a]);return n};var No;(e=>{const t=class mt{constructor(h,u,x,w){if(this.version=h,this.errorCorrectionLevel=u,this.modules=[],this.isFunction=[],h<mt.MIN_VERSION||h>mt.MAX_VERSION)throw new RangeError("Version value out of range");if(w<-1||w>7)throw new RangeError("Mask value out of range");this.size=h*4+17;let C=[];for(let R=0;R<this.size;R++)C.push(!1);for(let R=0;R<this.size;R++)this.modules.push(C.slice()),this.isFunction.push(C.slice());this.drawFunctionPatterns();const A=this.addEccAndInterleave(x);if(this.drawCodewords(A),w==-1){let R=1e9;for(let I=0;I<8;I++){this.applyMask(I),this.drawFormatBits(I);const O=this.getPenaltyScore();O<R&&(w=I,R=O),this.applyMask(I)}}o(0<=w&&w<=7),this.mask=w,this.applyMask(w),this.drawFormatBits(w),this.isFunction=[]}static encodeText(h,u){const x=e.QrSegment.makeSegments(h);return mt.encodeSegments(x,u)}static encodeBinary(h,u){const x=e.QrSegment.makeBytes(h);return mt.encodeSegments([x],u)}static encodeSegments(h,u,x=1,w=40,C=-1,A=!0){if(!(mt.MIN_VERSION<=x&&x<=w&&w<=mt.MAX_VERSION)||C<-1||C>7)throw new RangeError("Invalid value");let R,I;for(R=x;;R++){const B=mt.getNumDataCodewords(R,u)*8,q=f.getTotalBits(h,R);if(q<=B){I=q;break}if(R>=w)throw new RangeError("Data too long")}for(const B of[mt.Ecc.MEDIUM,mt.Ecc.QUARTILE,mt.Ecc.HIGH])A&&I<=mt.getNumDataCodewords(R,B)*8&&(u=B);let O=[];for(const B of h){n(B.mode.modeBits,4,O),n(B.numChars,B.mode.numCharCountBits(R),O);for(const q of B.getData())O.push(q)}o(O.length==I);const D=mt.getNumDataCodewords(R,u)*8;o(O.length<=D),n(0,Math.min(4,D-O.length),O),n(0,(8-O.length%8)%8,O),o(O.length%8==0);for(let B=236;O.length<D;B^=253)n(B,8,O);let z=[];for(;z.length*8<O.length;)z.push(0);return O.forEach((B,q)=>z[q>>>3]|=B<<7-(q&7)),new mt(R,u,z,C)}getModule(h,u){return 0<=h&&h<this.size&&0<=u&&u<this.size&&this.modules[u][h]}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 h=this.getAlignmentPatternPositions(),u=h.length;for(let x=0;x<u;x++)for(let w=0;w<u;w++)x==0&&w==0||x==0&&w==u-1||x==u-1&&w==0||this.drawAlignmentPattern(h[x],h[w]);this.drawFormatBits(0),this.drawVersion()}drawFormatBits(h){const u=this.errorCorrectionLevel.formatBits<<3|h;let x=u;for(let C=0;C<10;C++)x=x<<1^(x>>>9)*1335;const w=(u<<10|x)^21522;o(w>>>15==0);for(let C=0;C<=5;C++)this.setFunctionModule(8,C,a(w,C));this.setFunctionModule(8,7,a(w,6)),this.setFunctionModule(8,8,a(w,7)),this.setFunctionModule(7,8,a(w,8));for(let C=9;C<15;C++)this.setFunctionModule(14-C,8,a(w,C));for(let C=0;C<8;C++)this.setFunctionModule(this.size-1-C,8,a(w,C));for(let C=8;C<15;C++)this.setFunctionModule(8,this.size-15+C,a(w,C));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let h=this.version;for(let x=0;x<12;x++)h=h<<1^(h>>>11)*7973;const u=this.version<<12|h;o(u>>>18==0);for(let x=0;x<18;x++){const w=a(u,x),C=this.size-11+x%3,A=Math.floor(x/3);this.setFunctionModule(C,A,w),this.setFunctionModule(A,C,w)}}drawFinderPattern(h,u){for(let x=-4;x<=4;x++)for(let w=-4;w<=4;w++){const C=Math.max(Math.abs(w),Math.abs(x)),A=h+w,R=u+x;0<=A&&A<this.size&&0<=R&&R<this.size&&this.setFunctionModule(A,R,C!=2&&C!=4)}}drawAlignmentPattern(h,u){for(let x=-2;x<=2;x++)for(let w=-2;w<=2;w++)this.setFunctionModule(h+w,u+x,Math.max(Math.abs(w),Math.abs(x))!=1)}setFunctionModule(h,u,x){this.modules[u][h]=x,this.isFunction[u][h]=!0}addEccAndInterleave(h){const u=this.version,x=this.errorCorrectionLevel;if(h.length!=mt.getNumDataCodewords(u,x))throw new RangeError("Invalid argument");const w=mt.NUM_ERROR_CORRECTION_BLOCKS[x.ordinal][u],C=mt.ECC_CODEWORDS_PER_BLOCK[x.ordinal][u],A=Math.floor(mt.getNumRawDataModules(u)/8),R=w-A%w,I=Math.floor(A/w);let O=[];const D=mt.reedSolomonComputeDivisor(C);for(let B=0,q=0;B<w;B++){let G=h.slice(q,q+I-C+(B<R?0:1));q+=G.length;const ae=mt.reedSolomonComputeRemainder(G,D);B<R&&G.push(0),O.push(G.concat(ae))}let z=[];for(let B=0;B<O[0].length;B++)O.forEach((q,G)=>{(B!=I-C||G>=R)&&z.push(q[B])});return o(z.length==A),z}drawCodewords(h){if(h.length!=Math.floor(mt.getNumRawDataModules(this.version)/8))throw new RangeError("Invalid argument");let u=0;for(let x=this.size-1;x>=1;x-=2){x==6&&(x=5);for(let w=0;w<this.size;w++)for(let C=0;C<2;C++){const A=x-C,R=(x+1&2)==0?this.size-1-w:w;!this.isFunction[R][A]&&u<h.length*8&&(this.modules[R][A]=a(h[u>>>3],7-(u&7)),u++)}}o(u==h.length*8)}applyMask(h){if(h<0||h>7)throw new RangeError("Mask value out of range");for(let u=0;u<this.size;u++)for(let x=0;x<this.size;x++){let w;switch(h){case 0:w=(x+u)%2==0;break;case 1:w=u%2==0;break;case 2:w=x%3==0;break;case 3:w=(x+u)%3==0;break;case 4:w=(Math.floor(x/3)+Math.floor(u/2))%2==0;break;case 5:w=x*u%2+x*u%3==0;break;case 6:w=(x*u%2+x*u%3)%2==0;break;case 7:w=((x+u)%2+x*u%3)%2==0;break;default:throw new Error("Unreachable")}!this.isFunction[u][x]&&w&&(this.modules[u][x]=!this.modules[u][x])}}getPenaltyScore(){let h=0;for(let C=0;C<this.size;C++){let A=!1,R=0,I=[0,0,0,0,0,0,0];for(let O=0;O<this.size;O++)this.modules[C][O]==A?(R++,R==5?h+=mt.PENALTY_N1:R>5&&h++):(this.finderPenaltyAddHistory(R,I),A||(h+=this.finderPenaltyCountPatterns(I)*mt.PENALTY_N3),A=this.modules[C][O],R=1);h+=this.finderPenaltyTerminateAndCount(A,R,I)*mt.PENALTY_N3}for(let C=0;C<this.size;C++){let A=!1,R=0,I=[0,0,0,0,0,0,0];for(let O=0;O<this.size;O++)this.modules[O][C]==A?(R++,R==5?h+=mt.PENALTY_N1:R>5&&h++):(this.finderPenaltyAddHistory(R,I),A||(h+=this.finderPenaltyCountPatterns(I)*mt.PENALTY_N3),A=this.modules[O][C],R=1);h+=this.finderPenaltyTerminateAndCount(A,R,I)*mt.PENALTY_N3}for(let C=0;C<this.size-1;C++)for(let A=0;A<this.size-1;A++){const R=this.modules[C][A];R==this.modules[C][A+1]&&R==this.modules[C+1][A]&&R==this.modules[C+1][A+1]&&(h+=mt.PENALTY_N2)}let u=0;for(const C of this.modules)u=C.reduce((A,R)=>A+(R?1:0),u);const x=this.size*this.size,w=Math.ceil(Math.abs(u*20-x*10)/x)-1;return o(0<=w&&w<=9),h+=w*mt.PENALTY_N4,o(0<=h&&h<=2568888),h}getAlignmentPatternPositions(){if(this.version==1)return[];{const h=Math.floor(this.version/7)+2,u=this.version==32?26:Math.ceil((this.version*4+4)/(h*2-2))*2;let x=[6];for(let w=this.size-7;x.length<h;w-=u)x.splice(1,0,w);return x}}static getNumRawDataModules(h){if(h<mt.MIN_VERSION||h>mt.MAX_VERSION)throw new RangeError("Version number out of range");let u=(16*h+128)*h+64;if(h>=2){const x=Math.floor(h/7)+2;u-=(25*x-10)*x-55,h>=7&&(u-=36)}return o(208<=u&&u<=29648),u}static getNumDataCodewords(h,u){return Math.floor(mt.getNumRawDataModules(h)/8)-mt.ECC_CODEWORDS_PER_BLOCK[u.ordinal][h]*mt.NUM_ERROR_CORRECTION_BLOCKS[u.ordinal][h]}static reedSolomonComputeDivisor(h){if(h<1||h>255)throw new RangeError("Degree out of range");let u=[];for(let w=0;w<h-1;w++)u.push(0);u.push(1);let x=1;for(let w=0;w<h;w++){for(let C=0;C<u.length;C++)u[C]=mt.reedSolomonMultiply(u[C],x),C+1<u.length&&(u[C]^=u[C+1]);x=mt.reedSolomonMultiply(x,2)}return u}static reedSolomonComputeRemainder(h,u){let x=u.map(w=>0);for(const w of h){const C=w^x.shift();x.push(0),u.forEach((A,R)=>x[R]^=mt.reedSolomonMultiply(A,C))}return x}static reedSolomonMultiply(h,u){if(h>>>8||u>>>8)throw new RangeError("Byte out of range");let x=0;for(let w=7;w>=0;w--)x=x<<1^(x>>>7)*285,x^=(u>>>w&1)*h;return o(x>>>8==0),x}finderPenaltyCountPatterns(h){const u=h[1];o(u<=this.size*3);const x=u>0&&h[2]==u&&h[3]==u*3&&h[4]==u&&h[5]==u;return(x&&h[0]>=u*4&&h[6]>=u?1:0)+(x&&h[6]>=u*4&&h[0]>=u?1:0)}finderPenaltyTerminateAndCount(h,u,x){return h&&(this.finderPenaltyAddHistory(u,x),u=0),u+=this.size,this.finderPenaltyAddHistory(u,x),this.finderPenaltyCountPatterns(x)}finderPenaltyAddHistory(h,u){u[0]==0&&(h+=this.size),u.pop(),u.unshift(h)}};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 n(m,h,u){if(h<0||h>31||m>>>h)throw new RangeError("Value out of range");for(let x=h-1;x>=0;x--)u.push(m>>>x&1)}function a(m,h){return(m>>>h&1)!=0}function o(m){if(!m)throw new Error("Assertion error")}const p=class cn{constructor(h,u,x){if(this.mode=h,this.numChars=u,this.bitData=x,u<0)throw new RangeError("Invalid argument");this.bitData=x.slice()}static makeBytes(h){let u=[];for(const x of h)n(x,8,u);return new cn(cn.Mode.BYTE,h.length,u)}static makeNumeric(h){if(!cn.isNumeric(h))throw new RangeError("String contains non-numeric characters");let u=[];for(let x=0;x<h.length;){const w=Math.min(h.length-x,3);n(parseInt(h.substring(x,x+w),10),w*3+1,u),x+=w}return new cn(cn.Mode.NUMERIC,h.length,u)}static makeAlphanumeric(h){if(!cn.isAlphanumeric(h))throw new RangeError("String contains unencodable characters in alphanumeric mode");let u=[],x;for(x=0;x+2<=h.length;x+=2){let w=cn.ALPHANUMERIC_CHARSET.indexOf(h.charAt(x))*45;w+=cn.ALPHANUMERIC_CHARSET.indexOf(h.charAt(x+1)),n(w,11,u)}return x<h.length&&n(cn.ALPHANUMERIC_CHARSET.indexOf(h.charAt(x)),6,u),new cn(cn.Mode.ALPHANUMERIC,h.length,u)}static makeSegments(h){return h==""?[]:cn.isNumeric(h)?[cn.makeNumeric(h)]:cn.isAlphanumeric(h)?[cn.makeAlphanumeric(h)]:[cn.makeBytes(cn.toUtf8ByteArray(h))]}static makeEci(h){let u=[];if(h<0)throw new RangeError("ECI assignment value out of range");if(h<128)n(h,8,u);else if(h<16384)n(2,2,u),n(h,14,u);else if(h<1e6)n(6,3,u),n(h,21,u);else throw new RangeError("ECI assignment value out of range");return new cn(cn.Mode.ECI,0,u)}static isNumeric(h){return cn.NUMERIC_REGEX.test(h)}static isAlphanumeric(h){return cn.ALPHANUMERIC_REGEX.test(h)}getData(){return this.bitData.slice()}static getTotalBits(h,u){let x=0;for(const w of h){const C=w.mode.numCharCountBits(u);if(w.numChars>=1<<C)return 1/0;x+=4+C+w.bitData.length}return x}static toUtf8ByteArray(h){h=encodeURI(h);let u=[];for(let x=0;x<h.length;x++)h.charAt(x)!="%"?u.push(h.charCodeAt(x)):(u.push(parseInt(h.substring(x+1,x+3),16)),x+=2);return u}};p.NUMERIC_REGEX=/^[0-9]*$/,p.ALPHANUMERIC_REGEX=/^[A-Z0-9 $%*+.\/:-]*$/,p.ALPHANUMERIC_CHARSET="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";let f=p;e.QrSegment=p})(No||(No={}));(e=>{(t=>{const n=class{constructor(o,p){this.ordinal=o,this.formatBits=p}};n.LOW=new n(0,1),n.MEDIUM=new n(1,0),n.QUARTILE=new n(2,3),n.HIGH=new n(3,2),t.Ecc=n})(e.QrCode||(e.QrCode={}))})(No||(No={}));(e=>{(t=>{const n=class{constructor(o,p){this.modeBits=o,this.numBitsCharCount=p}numCharCountBits(o){return this.numBitsCharCount[Math.floor((o+7)/17)]}};n.NUMERIC=new n(1,[10,12,14]),n.ALPHANUMERIC=new n(2,[9,11,13]),n.BYTE=new n(4,[8,16,16]),n.KANJI=new n(8,[8,10,12]),n.ECI=new n(7,[0,0,0]),t.Mode=n})(e.QrSegment||(e.QrSegment={}))})(No||(No={}));var Qs=No;var pie={L:Qs.QrCode.Ecc.LOW,M:Qs.QrCode.Ecc.MEDIUM,Q:Qs.QrCode.Ecc.QUARTILE,H:Qs.QrCode.Ecc.HIGH},v4=128,y4="L",b4="#FFFFFF",S4="#000000",x4=!1,k4=1,mie=4,fie=0,hie=.1;function w4(e,t=0){const n=[];return e.forEach(function(a,o){let p=null;a.forEach(function(f,m){if(!f&&p!==null){n.push(`M${p+t} ${o+t}h${m-p}v1H${p+t}z`),p=null;return}if(m===a.length-1){if(!f)return;p===null?n.push(`M${m+t},${o+t} h1v1H${m+t}z`):n.push(`M${p+t},${o+t} h${m+1-p}v1H${p+t}z`);return}f&&p===null&&(p=m)})}),n.join("")}function M4(e,t){return e.slice().map((n,a)=>a<t.y||a>=t.y+t.h?n:n.map((o,p)=>p<t.x||p>=t.x+t.w?o:!1))}function gie(e,t,n,a){if(a==null)return null;const o=e.length+n*2,p=Math.floor(t*hie),f=o/t,m=(a.width||p)*f,h=(a.height||p)*f,u=a.x==null?e.length/2-m/2:a.x*f,x=a.y==null?e.length/2-h/2:a.y*f,w=a.opacity==null?1:a.opacity;let C=null;if(a.excavate){let R=Math.floor(u),I=Math.floor(x);C={x:R,y:I,w:Math.ceil(m+u-R),h:Math.ceil(h+x-I)}}const A=a.crossOrigin;return{x:u,y:x,h,w:m,excavation:C,opacity:w,crossOrigin:A}}function vie(e,t){return t!=null?Math.max(Math.floor(t),0):e?mie:fie}function C4({value:e,level:t,minVersion:n,includeMargin:a,marginSize:o,imageSettings:p,size:f,boostLevel:m}){let h=kn.useMemo(()=>{const A=(Array.isArray(e)?e:[e]).reduce((R,I)=>(R.push(...Qs.QrSegment.makeSegments(I)),R),[]);return Qs.QrCode.encodeSegments(A,pie[t],n,void 0,void 0,m)},[e,t,n,m]);const{cells:u,margin:x,numCells:w,calculatedImageSettings:C}=kn.useMemo(()=>{let A=h.getModules();const R=vie(a,o);return{cells:A,margin:R,numCells:A.length+R*2,calculatedImageSettings:gie(A,f,R,p)}},[h,f,p,a,o]);return{qrcode:h,margin:x,cells:u,numCells:w,calculatedImageSettings:C}}var yie=(function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0})(),bie=kn.forwardRef(function(t,n){const a=t,{value:o,size:p=v4,level:f=y4,bgColor:m=b4,fgColor:h=S4,includeMargin:u=x4,minVersion:x=k4,boostLevel:w,marginSize:C,imageSettings:A}=a,R=Ty(a,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:I}=R,O=Ty(R,["style"]),D=A?.src,z=kn.useRef(null),B=kn.useRef(null),q=kn.useCallback(Ce=>{z.current=Ce,typeof n=="function"?n(Ce):n&&(n.current=Ce)},[n]),[G,ae]=kn.useState(!1),{margin:Q,cells:H,numCells:oe,calculatedImageSettings:we}=C4({value:o,level:f,minVersion:x,boostLevel:w,includeMargin:u,marginSize:C,imageSettings:A,size:p});kn.useEffect(()=>{if(z.current!=null){const Ce=z.current,re=Ce.getContext("2d");if(!re)return;let Te=H;const F=B.current,ue=we!=null&&F!==null&&F.complete&&F.naturalHeight!==0&&F.naturalWidth!==0;ue&&we.excavation!=null&&(Te=M4(H,we.excavation));const ke=window.devicePixelRatio||1;Ce.height=Ce.width=p*ke;const Ee=p/oe*ke;re.scale(Ee,Ee),re.fillStyle=m,re.fillRect(0,0,oe,oe),re.fillStyle=h,yie?re.fill(new Path2D(w4(Te,Q))):H.forEach(function(fe,L){fe.forEach(function(ee,me){ee&&re.fillRect(me+Q,L+Q,1,1)})}),we&&(re.globalAlpha=we.opacity),ue&&re.drawImage(F,we.x+Q,we.y+Q,we.w,we.h)}}),kn.useEffect(()=>{ae(!1)},[D]);const Me=_y({height:p,width:p},I);let Ae=null;return D!=null&&(Ae=kn.createElement("img",{src:D,key:D,style:{display:"none"},onLoad:()=>{ae(!0)},ref:B,crossOrigin:we?.crossOrigin})),kn.createElement(kn.Fragment,null,kn.createElement("canvas",_y({style:Me,height:p,width:p,ref:q,role:"img"},O)),Ae)});bie.displayName="QRCodeCanvas";var Sie=kn.forwardRef(function(t,n){const a=t,{value:o,size:p=v4,level:f=y4,bgColor:m=b4,fgColor:h=S4,includeMargin:u=x4,minVersion:x=k4,boostLevel:w,title:C,marginSize:A,imageSettings:R}=a,I=Ty(a,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:O,cells:D,numCells:z,calculatedImageSettings:B}=C4({value:o,level:f,minVersion:x,boostLevel:w,includeMargin:u,marginSize:A,imageSettings:R,size:p});let q=D,G=null;R!=null&&B!=null&&(B.excavation!=null&&(q=M4(D,B.excavation)),G=kn.createElement("image",{href:R.src,height:B.h,width:B.w,x:B.x+O,y:B.y+O,preserveAspectRatio:"none",opacity:B.opacity,crossOrigin:B.crossOrigin}));const ae=w4(q,O);return kn.createElement("svg",_y({height:p,width:p,viewBox:`0 0 ${z} ${z}`,ref:n,role:"img"},I),!!C&&kn.createElement("title",null,C),kn.createElement("path",{fill:m,d:`M0,0 h${z}v${z}H0z`,shapeRendering:"crispEdges"}),kn.createElement("path",{fill:h,d:ae,shapeRendering:"crispEdges"}),G)});Sie.displayName="QRCodeSVG";var rC=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,oC=e4,Bo=(e,t)=>n=>{var a;if(t?.variants==null)return oC(e,n?.class,n?.className);const{variants:o,defaultVariants:p}=t,f=Object.keys(o).map(h=>{const u=n?.[h],x=p?.[h];if(u===null)return null;const w=rC(u)||rC(x);return o[h][w]}),m=n&&Object.entries(n).reduce((h,u)=>{let[x,w]=u;return w===void 0||(h[x]=w),h},{});return oC(e,f,t==null||(a=t.compoundVariants)===null||a===void 0?void 0:a.reduce((h,u)=>{let{class:x,className:w,...C}=u;return Object.entries(C).every(A=>{let[R,I]=A;return Array.isArray(I)?I.includes({...p,...m}[R]):{...p,...m}[R]===I})?[...h,x,w]:h},[]),n?.class,n?.className)},xie=Bo("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"}}),Iy=T.forwardRef(({className:e,variant:t,size:n,...a},o)=>v.jsx("button",{ref:o,className:se(xie({variant:t,size:n}),e),...a}));Iy.displayName="Button";var kie=Bo("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 hover:bg-surface-hover"},size:{sm:"h-7 w-7",md:"h-8 w-8",lg:"h-9 w-9"}},defaultVariants:{variant:"primary",size:"sm"}}),wie=T.forwardRef(({className:e,variant:t,size:n,icon:a,...o},p)=>v.jsx("button",{ref:p,className:se(kie({variant:t,size:n}),e),...o,children:v.jsx(a,{className:"h-4 w-4"})}));wie.displayName="IconButton";var Mie=Bo("inline-flex items-center rounded-full text-xs font-medium px-2 py-0.5",{variants:{variant:{default:"bg-surface-hover text-foreground",success:"bg-success/15 text-success",warning:"bg-warning/15 text-warning",danger:"bg-danger/15 text-danger",info:"bg-info/15 text-info"},styleVariant:{solid:"",outline:"border bg-transparent"}},defaultVariants:{variant:"default",styleVariant:"solid"}}),Cie=T.forwardRef(({className:e,variant:t,style:n,...a},o)=>v.jsx("span",{ref:o,className:se(Mie({variant:t,styleVariant:n}),e),...a}));Cie.displayName="Badge";var Aie=Bo("rounded-lg p-3",{variants:{variant:{flat:"bg-surface",bordered:"bg-surface border border-border"}},defaultVariants:{variant:"bordered"}}),Eie=T.forwardRef(({className:e,variant:t,...n},a)=>v.jsx("div",{ref:a,className:se(Aie({variant:t}),e),...n}));Eie.displayName="Card";var Rie=T.forwardRef(({className:e,...t},n)=>v.jsx("label",{ref:n,className:se("text-[10px] uppercase tracking-wider text-foreground-muted font-medium",e),...t}));Rie.displayName="Label";var _ie=Bo("",{variants:{orientation:{horizontal:"h-px w-full bg-border-subtle",vertical:"w-px h-full bg-border-subtle"}},defaultVariants:{orientation:"horizontal"}}),Tie=T.forwardRef(({className:e,orientation:t,...n},a)=>v.jsx("div",{ref:a,role:"separator",className:se(_ie({orientation:t}),e),...n}));Tie.displayName="Separator";var Iie=T.forwardRef(({className:e,...t},n)=>v.jsx("div",{ref:n,className:se("animate-pulse bg-surface-hover rounded-md h-4 w-full",e),...t}));Iie.displayName="Skeleton";var sC=Bo("h-7 w-full px-2.5 text-xs bg-surface border rounded-md text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary transition-colors disabled:opacity-50 disabled:cursor-not-allowed",{variants:{state:{default:"border-border",error:"border-danger"}},defaultVariants:{state:"default"}}),Nie=T.forwardRef(({className:e,state:t,leftSlot:n,rightSlot:a,...o},p)=>n||a?v.jsxs("div",{className:"relative flex items-center w-full",children:[n&&v.jsx("div",{className:"absolute left-2.5 flex items-center pointer-events-none",children:n}),v.jsx("input",{ref:p,className:se(sC({state:t}),n?"pl-7":"",a?"pr-7":"",e),...o}),a&&v.jsx("div",{className:"absolute right-2.5 flex items-center pointer-events-none",children:a})]}):v.jsx("input",{ref:p,className:se(sC({state:t}),e),...o}));Nie.displayName="Input";var Oie=T.forwardRef(({className:e,options:t,disabled:n,...a},o)=>v.jsxs("div",{className:"relative w-full",children:[v.jsx("select",{ref:o,disabled:n,className:se("h-7 w-full px-2.5 text-xs bg-surface border border-border rounded-md text-foreground appearance-none pr-7 focus:outline-none focus:ring-1 focus:ring-primary","disabled:opacity-50 disabled:cursor-not-allowed",e),...a,children:t.map(p=>v.jsx("option",{value:p.value,children:p.label},p.value))}),v.jsx("div",{className:se("absolute right-2 top-1/2 -translate-y-1/2 pointer-events-none text-foreground-muted",n===!0?"opacity-50":""),children:v.jsx(zo,{className:"h-3.5 w-3.5"})})]}));Oie.displayName="Select";var jie=T.forwardRef(({className:e,...t},n)=>v.jsx("input",{ref:n,type:"checkbox",className:se("w-3.5 h-3.5 rounded-sm border border-border accent-primary",e),...t}));jie.displayName="Checkbox";var Pie=T.forwardRef(({className:e,checked:t,onCheckedChange:n,label:a,...o},p)=>v.jsxs("button",{ref:p,role:"switch","aria-checked":t,type:"button",onClick:()=>n(!t),className:se("inline-flex items-center gap-2",e),...o,children:[v.jsx("span",{className:se("w-8 h-4 rounded-full transition-colors",t?"bg-primary":"bg-surface-hover"),children:v.jsx("span",{className:se("block w-3.5 h-3.5 rounded-full bg-white transition-transform",t?"translate-x-4":"translate-x-0.5")})}),a&&v.jsx("span",{className:"text-xs text-foreground",children:a})]}));Pie.displayName="Switch";var A4=T.createContext(null);function Die(){const e=T.useContext(A4);if(!e)throw new Error("Dialog compound components must be used within <Dialog>");return e}function E4({children:e,open:t,onOpenChange:n}){const[a,o]=T.useState(!1),p=t??a,f=T.useId(),m=T.useCallback(h=>{n?.(h),t===void 0&&o(h)},[t,n]);return v.jsx(A4.Provider,{value:{open:p,setOpen:m,contentId:f},children:e})}var zie=Bo("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"},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"},{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"}}),f0=T.forwardRef(({className:e,width:t,placement:n,scroll:a,children:o,...p},f)=>{const{open:m,setOpen:h,contentId:u}=Die(),x=T.useRef(null),w=f??x;T.useEffect(()=>{const A=w.current;A&&(m&&!A.open&&A.showModal(),!m&&A.open&&A.close())},[m,w]);const C=A=>{A.target===A.currentTarget&&h(!1)};return v.jsx("dialog",{ref:w,id:u,className:se(zie({width:t,placement:n,scroll:a}),e),onClick:C,onClose:()=>h(!1),...p,children:o})});f0.displayName="DialogContent";function Lie({className:e,...t}){return v.jsx("div",{className:se("flex flex-col gap-1 mb-3 shrink-0",e),...t})}function qie({className:e,...t}){return v.jsx("div",{className:se("flex justify-end gap-2 mt-4 shrink-0",e),...t})}function Bie({className:e,...t}){return v.jsx("h2",{className:se("text-sm font-semibold text-foreground",e),...t})}function Uie({className:e,...t}){return v.jsx("p",{className:se("text-xs text-foreground-muted",e),...t})}T.createContext(null);T.createContext(null);T.createContext(null);T.createContext(null);var Fie=T.forwardRef(({className:e,...t},n)=>v.jsx("div",{ref:n,className:se("overflow-auto [&::-webkit-scrollbar]:w-1 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-thumb]:bg-surface-hover [&::-webkit-scrollbar-thumb]:rounded-full",e),...t}));Fie.displayName="ScrollArea";var zg={baseDelayMs:1500,maxDelayMs:15e3,maxAttempts:40};function Hie(e,t=Math.random){if(e>=zg.maxAttempts)return{kind:"exhausted",attempts:e};const n=Math.min(zg.maxDelayMs,zg.baseDelayMs*2**e);return{kind:"retry",delayMs:Math.round(n*(.8+t()*.4))}}var $ie="/adaptive-probe",Qie=2500;function R4(e){return e>=8?"high":e>=2.5?"mid":"low"}function Vie(e){const{downlinkMbps:t,...n}=e;return n}function lC(e){return R4(e)!=="low"}function cC(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}function Gie(e,t){return cC(e)??cC(t)}function Zie(e){const t=e.downlinkMbps===void 0?"none":R4(e.downlinkMbps);return[e.phase,e.viewportWidth??"-",e.viewportHeight??"-",e.devicePixelRatio??"-",t,e.prefersTier??"-",e.probeOrigin??"unreachable"].join("|")}async function Kie(e,t){const n=e.replace(/\/+$/,""),a=new AbortController,o=setTimeout(()=>a.abort(),Qie),p=t.now();try{const f=await t.fetchImpl(`${n}${$ie}`,{signal:a.signal});if(!f.ok)return null;const m=await f.arrayBuffer(),h=Math.max(1,t.now()-p);return m.byteLength<1024?null:m.byteLength*8/h/1e3}catch{return null}finally{clearTimeout(o)}}function vo(e,t){e.muted=t;const n=e.srcObject;if(n instanceof MediaStream)for(const a of n.getAudioTracks())a.enabled=!t}function Wie(){return typeof window>"u"?!1:window.matchMedia("(hover: none) and (pointer: coarse)").matches||typeof navigator<"u"&&navigator.maxTouchPoints>0||"ontouchstart"in window}function Yie(e,t,n){let f=0;for(let m=0;m<8;m++)for(let h=0;h<8;h++){const u=Math.min(t-1,Math.floor((h+.5)/8*t)),x=Math.min(n-1,Math.floor((m+.5)/8*n)),{data:w}=e.getImageData(u,x,1,1);.2126*(w[0]??0)+.7152*(w[1]??0)+.0722*(w[2]??0)>12&&f++}return f<=1}function Lg(e){const t={};if(typeof window<"u"){const n=window.devicePixelRatio||1;if(e){const a=e.getBoundingClientRect();a.width>0&&a.height>0&&(t.viewportWidth=Math.round(a.width*n),t.viewportHeight=Math.round(a.height*n))}t.viewportWidth===void 0&&(t.viewportWidth=Math.round(window.innerWidth*n),t.viewportHeight=Math.round(window.innerHeight*n)),t.devicePixelRatio=n}return t}var hc=null,Xie=3e4;function xp(e){return Gie(e,typeof window<"u"?window.location.origin:void 0)}async function gc(e){const t=xp(e);if(t===null)return;if(hc&&hc.origin===t&&Date.now()-hc.at<Xie)return hc.mbps;const n=await Kie(t,{fetchImpl:(a,o)=>fetch(a,o),now:()=>Date.now()});if(!(n===null||!Number.isFinite(n)))return hc={origin:t,mbps:n,at:Date.now()},n}function uC(e,t,n,a){const o={...e,...n!==void 0?{downlinkMbps:n}:{},...t};return a?Vie(o):o}var Jie=8e3;function _4({serverUrl:e,streamKey:t,label:n,autoPlay:a=!0,muted:o=!0,showControls:p=!0,showStats:f=!1,onPlaybackStats:m,onClientNetworkSample:h,onConnectTiming:u,className:x="",onStateChange:w,onError:C,onReconnectAttempt:A,overlay:R,createSession:I,sendAnswer:O,handleOffer:D,getIceServers:z,addIceCandidate:B,getIceCandidates:q,closeSession:G,getSessionState:ae,reoffer:Q,posterUrl:H,hintsOverride:oe,onAdaptiveHints:we,reconnectSignal:Me,onControlChannel:Ae,onVideoElement:Ce}){const re=T.useRef(null),Te=T.useRef(null),F=T.useRef(null),ue=T.useRef(new Set),ke=T.useRef(null),Ee=T.useRef(null),fe=T.useRef(0),L=T.useRef(!0),ee=T.useRef(Ae);ee.current=Ae;const me=T.useRef(Ce);me.current=Ce,T.useEffect(()=>(me.current?.(re.current),()=>me.current?.(null)),[]);const be=T.useRef(we);be.current=we;const X=T.useRef(null),xe=T.useCallback((ce,Ue,Xe)=>{const wt=be.current;if(!wt)return;const Ye={phase:ce,probeOrigin:Xe,...Ue},Nt=Zie(Ye);Nt!==X.current&&(X.current=Nt,wt(Ye))},[]),Oe=T.useRef(null),le=T.useRef(null),ye=T.useRef(0),Be=T.useRef(!1),ot=T.useRef(!1),Ve=T.useRef(async()=>{}),[Ie,bt]=T.useState("idle"),[Re,Le]=T.useState(""),[lt,st]=T.useState(o),Pt=T.useRef(lt);Pt.current=lt;const[Rt,gn]=T.useState(!1),[Ca,Wa]=T.useState(!1),$t=Wie(),[Ya,Xa]=T.useState(!0),zn=T.useRef(null),Kn=T.useRef(!1);(O||I)&&(Kn.current=!0);const We=Kn.current,_n=T.useRef(!1);D&&(_n.current=!0);const Aa=_n.current,[Ja,yi]=T.useState(!1),vn=T.useRef(null),[Wn,ge]=T.useState(null),[_e,_t]=T.useState(!1),tn=T.useCallback(()=>{const ce=re.current;if(!(!ce||ce.readyState<2||!ce.videoWidth||!ce.videoHeight))try{const Ue=document.createElement("canvas");Ue.width=ce.videoWidth,Ue.height=ce.videoHeight;const Xe=Ue.getContext("2d");if(!Xe||(Xe.drawImage(ce,0,0),Yie(Xe,Ue.width,Ue.height)))return;vn.current=Ue.toDataURL("image/jpeg",.6)}catch{}},[]),Tt=T.useCallback(ce=>{bt(ce),ce==="playing"&&yi(!0),w?.(ce)},[w]),In=T.useCallback(()=>{if(ke.current?.abort(),ke.current=null,Ee.current&&(clearTimeout(Ee.current),Ee.current=null),le.current&&(clearTimeout(le.current),le.current=null),Oe.current=null,ot.current=!1,ye.current=0,F.current&&(F.current.close(),F.current=null),G&&ue.current.size>0){for(const ce of ue.current)G(ce).catch(()=>{});ue.current.clear()}},[G]),bi=T.useCallback(()=>{ke.current?.abort(),ke.current=null,Ee.current&&(clearTimeout(Ee.current),Ee.current=null),le.current&&(clearTimeout(le.current),le.current=null),Oe.current=null,ot.current=!1,ye.current=0},[]),ei=1e3,ti=T.useCallback(ce=>{if(!ae||!Q)return;le.current&&(clearTimeout(le.current),le.current=null);const Ue=async()=>{if(L.current&&Oe.current===ce){if(!ot.current)try{const{pendingRenegotiation:Xe}=await ae(ce);if(L.current&&Oe.current===ce&&Xe&&Xe.epoch>ye.current&&!ot.current){ye.current=Xe.epoch,await Ve.current(ce,Xe.target);return}}catch{}!L.current||Oe.current!==ce||(le.current=setTimeout(()=>{Ue()},ei))}};le.current=setTimeout(()=>{Ue()},ei)},[ae,Q]),Si=T.useCallback(async(ce=!1,Ue=ce)=>{if(!L.current||!I||!O)return;const Xe=ce?F.current:null,wt=ce?new Set(ue.current):null;ce?bi():In(),Tt("connecting");const Ye=new AbortController;ke.current=Ye;try{const Nt=Ue?void 0:gc(e),He=uC(Lg(Te.current),oe,Ue?await gc(e):void 0,!Ue);xe(Ue?"probe-climb":"cold-start",He,xp(e));const{sessionId:tt,sdpOffer:Zt,iceServers:Kt}=await I(He);if(ue.current.add(tt),Nt!==void 0&&Nt.then(at=>{at===void 0||!lC(at)||!L.current||Ye.signal.aborted||Be.current||(Be.current=!0,Si(!0,!0))}),!L.current||Ye.signal.aborted){G?.(tt).catch(()=>{}),ue.current.delete(tt);return}const $e=new RTCPeerConnection({iceServers:[...Kt??[],{urls:"stun:stun.l.google.com:19302"}]});ce||(F.current=$e);const Mt=new MediaStream;let St=!1;const Ot=()=>{if(!(St||!L.current)){if(St=!0,F.current=$e,re.current&&(re.current.srcObject=Mt,vo(re.current,Pt.current),re.current.play().catch(()=>{})),Xe&&Xe!==$e)try{Xe.close()}catch{}if(wt)for(const at of wt)ue.current.delete(at),G?.(at).catch(()=>{})}};$e.ontrack=at=>{if(console.debug("[WebRTC] ontrack",at.track.kind,at.track.readyState),Mt.addTrack(at.track),ce){Ot();return}re.current&&(re.current.srcObject=Mt,vo(re.current,Pt.current),re.current.play().catch(()=>{}))},$e.oniceconnectionstatechange=()=>{if(!L.current)return;const at=$e.iceConnectionState;if(console.debug("[WebRTC] ICE state:",at),at==="connected"||at==="completed")fe.current=0,ce&&Ot(),Tt("playing"),re.current?.paused&&(console.debug("[WebRTC] video was paused at ICE connected — calling play()"),re.current.play().catch(()=>{}));else if(at==="failed"||at==="disconnected"||at==="closed"){if(ce&&!St)try{$e.close()}catch{}Tt("disconnected"),qa()}},$e.onicecandidateerror=at=>{console.debug("[WebRTC] ICE candidate error:",at)},console.debug("[WebRTC] Setting remote description (server offer)..."),await $e.setRemoteDescription({type:"offer",sdp:Zt});const Yn=await $e.createAnswer();if(await $e.setLocalDescription(Yn),console.debug("[WebRTC] Local description set, waiting for ICE gathering..."),await dC($e),!L.current)return;const nn=($e.localDescription?.sdp??"").split(`
81
+ ${fI(this.remoteInfo)}`),this.remoteEntryExports=t,this.remoteEntryExports}async init(e,t,n,a){const o=await this.getEntry(a);if(this.inited)return await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:o,cached:!0,origin:this.host}),o;if(this.initPromise){try{await this.initPromise,await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:o,cached:!0,origin:this.host})}catch(p){throw await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:o,error:p,cached:!0,origin:this.host}),p}return o}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:p,shareScope:f,initScope:m}=lae(this.remoteInfo,this.host.shareScopeMap,n),h=await this.host.hooks.lifecycle.beforeInitContainer.emit({shareScope:f,remoteEntryInitOptions:p,initScope:m,remoteInfo:this.remoteInfo,origin:this.host});typeof o?.init>"u"&&Xt(OI,ca,{hostName:this.host.name,remoteName:this.remoteInfo.name,remoteEntryUrl:this.remoteInfo.entry,remoteEntryKey:this.remoteInfo.entryGlobalName},void 0,Wi(this.host.options));try{await o.init(h.shareScope,h.initScope,h.remoteEntryInitOptions)}catch(u){Xt(HI,ca,{hostName:this.host.name,remoteName:this.remoteInfo.name,remoteEntryUrl:this.remoteInfo.entry,remoteEntryKey:this.remoteInfo.entryGlobalName,shareScope:this.remoteInfo.shareScope},`${u}`,Wi(this.host.options))}await this.host.hooks.lifecycle.initContainer.emit({...h,id:e,remoteSnapshot:t,remoteEntryExports:o}),this.inited=!0})();try{await this.initPromise,await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:o,origin:this.host})}catch(p){throw await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:o,error:p,origin:this.host}),p}finally{this.initing=!1,this.initPromise=void 0}return o}async get(e,t,n,a){const{loadFactory:o=!0}=n||{loadFactory:!0},p=await this.init(e,a,void 0,t);this.lib=p,await this.host.loaderHook.lifecycle.beforeGetExpose.emit({id:e,expose:t,moduleInfo:this.remoteInfo,remoteEntryExports:p,origin:this.host});let f;try{const u=await this.host.loaderHook.lifecycle.getModuleFactory.emit({remoteEntryExports:p,expose:t,moduleInfo:this.remoteInfo});f=typeof u=="function"?u:void 0,f||(f=await p.get(t)),f||Xt(FI,ca,{hostName:this.host.name,remoteName:this.remoteInfo.name,remoteEntryUrl:this.remoteInfo.entry,expose:t,requestId:e,availableExposes:sae(a)},void 0,Wi(this.host.options)),await this.host.loaderHook.lifecycle.afterGetExpose.emit({id:e,expose:t,moduleInfo:this.remoteInfo,remoteEntryExports:p,moduleFactory:f,origin:this.host})}catch(u){throw await this.host.loaderHook.lifecycle.afterGetExpose.emit({id:e,expose:t,moduleInfo:this.remoteInfo,remoteEntryExports:p,error:u,origin:this.host}),u}const m=one(this.remoteInfo.name,t),h=this.wraperFactory(f,m);if(!o)return h;await this.host.loaderHook.lifecycle.beforeExecuteFactory.emit({id:e,expose:t,moduleInfo:this.remoteInfo,loadFactory:o,origin:this.host});try{const u=await h();return await this.host.loaderHook.lifecycle.afterExecuteFactory.emit({id:e,expose:t,moduleInfo:this.remoteInfo,loadFactory:o,exposeModule:u,origin:this.host}),u}catch(u){throw await this.host.loaderHook.lifecycle.afterExecuteFactory.emit({id:e,expose:t,moduleInfo:this.remoteInfo,loadFactory:o,error:u,origin:this.host}),u}}wraperFactory(e,t){function n(a,o){a&&typeof a=="object"&&Object.isExtensible(a)&&!Object.getOwnPropertyDescriptor(a,Symbol.for("mf_module_id"))&&Object.defineProperty(a,Symbol.for("mf_module_id"),{value:o,enumerable:!1})}return()=>{const a=e();return a instanceof Promise?a.then(o=>(n(o,t),o)):(n(a,t),a)}}},sa=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 n(...a){return t.remove(n),e.apply(null,a)})}emit(...e){let t;return this.listeners.size>0&&this.listeners.forEach(n=>{const a=n(...e);a!==void 0&&(t=a)}),t}remove(e){this.listeners.delete(e)}removeAll(){this.listeners.clear()}},wn=class extends sa{emit(...e){let t;const n=Array.from(this.listeners);if(n.length>0){let a=0;const o=p=>p===!1?!1:a<n.length?Promise.resolve(n[a++].apply(null,e)).then(f=>f===void 0||e.length===1&&f===e[0]?o(p):o(f)):p;t=o()}return Promise.resolve(t)}};function KI(e,t){if(!r0(t))return!1;if(e!==t){for(const n in e)if(!(n in t))return!1}return!0}var Zs=class extends sa{constructor(e){super(),this.onerror=Xt,this.type=e}emit(e){r0(e)||Xt(`The data for the "${this.type}" hook should be an object.`);for(const t of this.listeners)try{const n=t(e);if(n===void 0)continue;if(KI(e,n))e=n;else{this.onerror(`A plugin returned an unacceptable value for the "${this.type}" type.`);break}}catch(n){$c(n),this.onerror(n)}return e}},Lr=class extends sa{constructor(e){super(),this.onerror=Xt,this.type=e}emit(e){r0(e)||Xt(`The response data for the "${this.type}" hook must be an object.`);const t=Array.from(this.listeners);if(t.length>0){let n=0;const a=p=>($c(p),this.onerror(p),e),o=p=>{if(p!==void 0&&KI(e,p))e=p;else if(p!==void 0)return this.onerror(`A plugin returned an incorrect value for the "${this.type}" type.`),e;if(n<t.length)try{return Promise.resolve(t[n++](e)).then(o,a)}catch(f){return a(f)}return e};return Promise.resolve(o(e))}return Promise.resolve(e)}},Ks=class{constructor(e){this.registerPlugins={},this.lifecycle=e,this.lifecycleKeys=Object.keys(e)}applyPlugin(e,t){Zi(rne(e),"Plugin configuration is invalid.");const n=e.name;Zi(n,"A name must be provided by the plugin."),this.registerPlugins[n]||(this.registerPlugins[n]=e,e.apply?.(t),Object.keys(this.lifecycle).forEach(a=>{const o=e[a];o&&this.lifecycle[a].on(o)}))}removePlugin(e){Zi(e,"A name is required.");const t=this.registerPlugins[e];Zi(t,`The plugin "${e}" is not registered.`),Object.keys(t).forEach(n=>{n!=="name"&&this.lifecycle[n].remove(t[n])})}};function WI(e,t){const n=wI(t);n.url||Xt(BI,ca,{remoteName:e.name});let a=ky(t,n.url);!Vr&&!a.startsWith("http")&&(a=`https:${a}`),e.type=n.type,e.entryGlobalName=n.globalName,e.entry=a,e.version=t.version,e.buildVersion=t.buildVersion}function cae(){return{name:"snapshot-plugin",async afterResolve(e){const{remote:t,pkgNameOrAlias:n,expose:a,origin:o,remoteInfo:p,id:f}=e;if(!i0(t)||!xI(t)){const{remoteSnapshot:m,globalSnapshot:h}=await o.snapshotHandler.loadRemoteSnapshotInfo({moduleInfo:t,id:c0(t.name,a)});WI(p,m);const u={remote:t,preloadConfig:{nameOrAlias:n,exposes:[a],resourceCategory:"sync",share:!1,depsRemote:!1}},x=await o.remoteHandler.hooks.lifecycle.generatePreloadAssets.emit({origin:o,preloadOptions:u,remoteInfo:p,remote:t,remoteSnapshot:m,globalSnapshot:h});return x&&GI(p,o,x,!1,{initiator:"loadRemote",id:f}).catch(()=>{}),{...e,remoteSnapshot:m}}return e}}}function uae(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 YI(e,t,n,a,o={},p){const{value:f}=ol(e,Kp(t)),m=p||f;if(m&&!hI(m)&&(n(m,t,a),m.remotesInfo)){const h=Object.keys(m.remotesInfo);for(const u of h){if(o[u])continue;o[u]=!0;const x=uae(u),w=m.remotesInfo[u];YI(e,{name:x.name,version:w.matchedVersion},n,!1,o,void 0)}}}var Pg=(e,t)=>document.querySelector(`${e}[${e==="link"?"href":"src"}="${t}"]`);function dae(e,t,n,a,o){const p=[],f=[],m=[],h=new Set,u=new Set,{options:x}=e,{preloadConfig:w}=t,{depsRemote:C}=w;if(YI(a,n,(R,I,O)=>{let D;if(O)D=w;else if(Array.isArray(C)){const ae=C.find(Q=>Q.nameOrAlias===I.name||Q.nameOrAlias===I.alias);if(!ae)return;D=VI(ae)}else if(C===!0)D=w;else return;const z=ky(R,wI(R).url);z&&m.push({name:I.name,moduleInfo:{name:I.name,entry:z,type:"remoteEntryType"in R?R.remoteEntryType:"global",entryGlobalName:"globalName"in R?R.globalName:I.name,shareScope:"",version:"version"in R?R.version:void 0},url:z});let B="modules"in R?R.modules:[];const q=iae(D.exposes);q.length&&"modules"in R&&(B=R?.modules?.reduce((ae,Q)=>(q?.indexOf(Q.moduleName)!==-1&&ae.push(Q),ae),[]));function G(ae){const Q=ae.map(H=>ky(R,H));return D.filter?Q.filter(D.filter):Q}if(B){const ae=B.length;for(let Q=0;Q<ae;Q++){const H=B[Q],oe=`${I.name}/${H.moduleName}`;e.remoteHandler.hooks.lifecycle.handlePreloadModule.emit({id:H.moduleName==="."?I.name:oe,name:I.name,remoteSnapshot:R,preloadConfig:D,remote:I,origin:e}),!dne(oe)&&(D.resourceCategory==="all"?(p.push(...G(H.assets.css.async)),p.push(...G(H.assets.css.sync)),f.push(...G(H.assets.js.async)),f.push(...G(H.assets.js.sync))):D.resourceCategory==="sync"&&(p.push(...G(H.assets.css.sync)),f.push(...G(H.assets.js.sync))),pne(oe))}}},!0,{},o),o.shared&&o.shared.length>0){const R=(I,O)=>{const{shared:D}=Sp(e.shareScopeMap,O.sharedName,I,e.sharedHandler.hooks.lifecycle.resolveShare)||{};D&&typeof D.lib=="function"&&(O.assets.js.sync.forEach(z=>{h.add(z)}),O.assets.css.sync.forEach(z=>{u.add(z)}))};o.shared.forEach(I=>{const O=x.shared?.[I.sharedName];if(!O)return;const D=I.version?O.find(z=>z.version===I.version):O;D&&kI(D).forEach(z=>{R(z,I)})})}const A=f.filter(R=>!h.has(R)&&!Pg("script",R));return{cssAssets:p.filter(R=>!u.has(R)&&!Pg("link",R)),jsAssetsWithoutEntry:A,entryAssets:m.filter(R=>!Pg("script",R.url))}}var pae=function(){return{name:"generate-preload-assets-plugin",async generatePreloadAssets(e){const{origin:t,preloadOptions:n,remoteInfo:a,remote:o,globalSnapshot:p,remoteSnapshot:f}=e;return Vr?i0(o)&&xI(o)?{cssAssets:[],jsAssetsWithoutEntry:[],entryAssets:[{name:o.name,url:o.entry,moduleInfo:{name:a.name,entry:o.entry,type:a.type||"global",entryGlobalName:"",shareScope:""}}]}:(WI(a,f),dae(t,n,a,p,f)):{cssAssets:[],jsAssetsWithoutEntry:[],entryAssets:[]}}}};function XI(e,t){const n=vp({name:t.name,version:t.options.version}),a=n&&"remotesInfo"in n&&n.remotesInfo&&ol(n.remotesInfo,e.name).value;return a&&a.matchedVersion?{hostGlobalSnapshot:n,globalSnapshot:H2(),remoteSnapshot:vp({name:e.name,version:a.matchedVersion})}:{hostGlobalSnapshot:void 0,globalSnapshot:H2(),remoteSnapshot:vp({name:e.name,version:"version"in e?e.version:void 0})}}var mae=class{constructor(e){this.loadingHostSnapshot=null,this.manifestCache=new Map,this.hooks=new Ks({beforeLoadRemoteSnapshot:new wn("beforeLoadRemoteSnapshot"),loadSnapshot:new Lr("loadGlobalSnapshot"),loadRemoteSnapshot:new Lr("loadRemoteSnapshot"),afterLoadSnapshot:new Lr("afterLoadSnapshot")}),this.manifestLoading=Qc.__FEDERATION__.__MANIFEST_LOADING__,this.HostInstance=e,this.loaderHook=e.loaderHook}async loadRemoteSnapshotInfo({moduleInfo:e,id:t,initiator:n="loadRemote"}){const{options:a}=this.HostInstance;await this.hooks.lifecycle.beforeLoadRemoteSnapshot.emit({options:a,moduleInfo:e,origin:this.HostInstance});let o=vp({name:this.HostInstance.options.name,version:this.HostInstance.options.version});o||(o={version:this.HostInstance.options.version||"",remoteEntry:"",remotesInfo:{}},cne({[this.HostInstance.options.name]:o})),o&&"remotesInfo"in o&&!ol(o.remotesInfo,e.name).value&&("version"in e||"entry"in e)&&(o.remotesInfo={...o?.remotesInfo,[e.name]:{matchedVersion:"version"in e?e.version:e.entry}});const{hostGlobalSnapshot:p,remoteSnapshot:f,globalSnapshot:m}=this.getGlobalRemoteInfo(e),{remoteSnapshot:h,globalSnapshot:u}=await this.hooks.lifecycle.loadSnapshot.emit({options:a,moduleInfo:e,hostGlobalSnapshot:p,remoteSnapshot:f,globalSnapshot:m});let x,w;if(h)if(hI(h)){const C=Vr?h.remoteEntry:h.ssrRemoteEntry||h.remoteEntry||"",A=await this.loadManifestSnapshot(C,e,{},{initiator:n,id:t||e.name}),R=$2({...e,entry:C},A);x=A,w=R}else{const{remoteSnapshot:C}=await this.hooks.lifecycle.loadRemoteSnapshot.emit({options:this.HostInstance.options,moduleInfo:e,remoteSnapshot:h,from:"global"});x=C,w=u}else if(i0(e)){const C=await this.loadManifestSnapshot(e.entry,e,{},{initiator:n,id:t||e.name}),A=$2(e,C);x=C,w=A}else Xt(zI,ca,{remoteName:e.name,remoteVersion:e.version,hostName:this.HostInstance.options.name,globalSnapshot:JSON.stringify(u)},void 0,Wi(this.HostInstance.options));return await this.hooks.lifecycle.afterLoadSnapshot.emit({id:t,host:this.HostInstance,options:a,moduleInfo:e,remoteSnapshot:x}),{remoteSnapshot:x,globalSnapshot:w}}getGlobalRemoteInfo(e){return XI(e,this.HostInstance)}async getManifestJson(e,t,n,a){return(async()=>{const p=$s(t);let f=this.manifestCache.get(e);if(f)return f;try{let h=await this.loaderHook.lifecycle.fetch.emit(e,{},p,a?{...a,url:e,resourceType:"manifest"}:void 0);(!h||!(h instanceof Response))&&(h=await fetch(e,{})),f=await h.json()}catch(h){f=await this.HostInstance.remoteHandler.hooks.lifecycle.errorLoadRemote.emit({id:e,error:h,from:"runtime",lifecycle:"afterResolve",remote:p,origin:this.HostInstance}),f||(delete this.manifestLoading[e],Xt(jI,ca,{manifestUrl:e,moduleName:t.name,hostName:this.HostInstance.options.name},`${h}`,Wi(this.HostInstance.options)))}const m=[!f.metaData&&"metaData",!f.exposes&&"exposes",!f.shared&&"shared"].filter(Boolean);return m.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: ${m.join(", ")}.`),from:"runtime",lifecycle:"afterResolve",remote:p,origin:this.HostInstance}),m.length>0&&Xt(UI,ca,{manifestUrl:e,moduleName:t.name,hostName:this.HostInstance.options.name,missingFields:m.join(",")},void 0,Wi(this.HostInstance.options)),this.manifestCache.set(e,f),f})()}async loadManifestSnapshot(e,t,n,a){const o=async()=>{const p=await this.getManifestJson(e,t,n,a),f=$te(p,{version:e}),{remoteSnapshot:m}=await this.hooks.lifecycle.loadRemoteSnapshot.emit({options:this.HostInstance.options,moduleInfo:t,manifestJson:p,remoteSnapshot:f,manifestUrl:e,from:"manifest"});return m};return this.manifestLoading[e]||(this.manifestLoading[e]=o().then(p=>p)),this.manifestLoading[e]}},fae=class{constructor(e){this.hooks=new Ks({beforeRegisterShare:new Zs("beforeRegisterShare"),afterResolve:new Lr("afterResolve"),beforeLoadShare:new Lr("beforeLoadShare"),loadShare:new wn,afterLoadShare:new sa("afterLoadShare"),errorLoadShare:new sa("errorLoadShare"),resolveShare:new Zs("resolveShare"),initContainerShareScopeMap:new Zs("initContainerShareScopeMap")}),this.host=e,this.shareScopeMap={},this.initTokens={},this._setGlobalShareScopeMap(e.options)}emitAfterLoadShare({lifecycle:e,pkgName:t,shareInfo:n,selectedShared:a}){try{this.hooks.lifecycle.afterLoadShare.emit({pkgName:t,shareInfo:n,selectedShared:a,shared:this.host.options.shared,shareScopeMap:this.shareScopeMap,lifecycle:e,origin:this.host})}catch(o){$c(o)}}emitErrorLoadShare({lifecycle:e,pkgName:t,shareInfo:n,error:a,recovered:o}){try{this.hooks.lifecycle.errorLoadShare.emit({pkgName:t,shareInfo:n,shared:this.host.options.shared,shareScopeMap:this.shareScopeMap,lifecycle:e,origin:this.host,error:a,recovered:o})}catch(p){$c(p)}}registerShared(e,t){const{newShareInfos:n,allShareInfos:a}=TI(e,t);return Object.keys(n).forEach(o=>{n[o].forEach(p=>{p.scope.forEach(f=>{this.hooks.lifecycle.beforeRegisterShare.emit({origin:this.host,pkgName:o,shared:p}),this.shareScopeMap[f]?.[o]||this.setShared({pkgName:o,lib:p.lib,get:p.get,loaded:p.loaded||!!p.lib,shared:p,from:t.name})})})}),{newShareInfos:n,allShareInfos:a}}async loadShare(e,t){const{host:n}=this,a=W2({pkgName:e,extraOptions:t,shareInfos:n.options.shared});let o=a;try{a?.scope&&await Promise.all(a.scope.map(async h=>{await Promise.all(this.initializeSharing(h,{strategy:a.strategy}))})),o=(await this.hooks.lifecycle.beforeLoadShare.emit({pkgName:e,shareInfo:a,shared:n.options.shared,origin:n})).shareInfo,Zi(o,`Cannot find shared "${e}" in host "${n.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 p=o,{shared:f,useTreesShaking:m}=Sp(this.shareScopeMap,e,o,this.hooks.lifecycle.resolveShare)||{};if(f){const h=$d(f,m);if(h.lib)return Ts(h,n.options.name),this.emitAfterLoadShare({lifecycle:"loadShare",pkgName:e,shareInfo:p,selectedShared:f}),h.lib;if(h.loading&&!h.loaded){const u=await h.loading;return h.loaded=!0,h.lib||(h.lib=u),Ts(h,n.options.name),this.emitAfterLoadShare({lifecycle:"loadShare",pkgName:e,shareInfo:p,selectedShared:f}),u}else{const x=(async()=>{const C=await h.get();return Ts(h,n.options.name),h.loaded=!0,h.lib=C,C})();this.setShared({pkgName:e,loaded:!1,shared:f,from:n.options.name,lib:null,loading:x,treeShaking:m?h:void 0});const w=await x;return this.emitAfterLoadShare({lifecycle:"loadShare",pkgName:e,shareInfo:p,selectedShared:f}),w}}else{if(t?.customShareInfo)return this.emitErrorLoadShare({lifecycle:"loadShare",pkgName:e,shareInfo:p,recovered:!0}),!1;const h=Vc(p.treeShaking),u=$d(p,h),w=(async()=>{const A=await u.get();u.lib=A,u.loaded=!0,Ts(u,n.options.name);const{shared:R,useTreesShaking:I}=Sp(this.shareScopeMap,e,p,this.hooks.lifecycle.resolveShare)||{};if(R){const O=$d(R,I);O.lib=A,O.loaded=!0,R.from=p.from}return A})();this.setShared({pkgName:e,loaded:!1,shared:p,from:n.options.name,lib:null,loading:w,treeShaking:h?u:void 0});const C=await w;return this.emitAfterLoadShare({lifecycle:"loadShare",pkgName:e,shareInfo:p,selectedShared:p}),C}}catch(p){throw this.emitErrorLoadShare({lifecycle:"loadShare",pkgName:e,shareInfo:o,error:p}),p}}initializeSharing(e=Am,t){const{host:n}=this,a=t?.from,o=t?.strategy;let p=t?.initScope;const f=[];if(a!=="build"){const{initTokens:C}=this;p||(p=[]);let A=C[e];if(A||(A=C[e]={from:this.host.name}),p.indexOf(A)>=0)return f;p.push(A)}const m=this.shareScopeMap,h=n.options.name;m[e]||(m[e]={});const u=m[e],x=(C,A)=>{const{version:R,eager:I}=A;u[C]=u[C]||{};const O=u[C],D=O[R]&&$d(O[R]),z=!!(D&&("eager"in D&&D.eager||"shareConfig"in D&&D.shareConfig?.eager));(!D||D.strategy!=="loaded-first"&&!D.loaded&&(!I!=!z?I:h>O[R].from))&&(O[R]=A)},w=async C=>{const{module:A}=await n.remoteHandler.getRemoteModuleAndOptions({id:C});let R;try{R=await A.getEntry()}catch(I){if(R=await n.remoteHandler.hooks.lifecycle.errorLoadRemote.emit({id:C,error:I,from:"runtime",lifecycle:"beforeLoadShare",remote:A.remoteInfo,origin:n}),!R)return}finally{R?.init&&!A.initing&&(A.remoteEntryExports=R,await A.init(void 0,void 0,p))}};return Object.keys(n.options.shared).forEach(C=>{n.options.shared[C].forEach(A=>{A.scope.includes(e)&&x(C,A)})}),(n.options.shareStrategy==="version-first"||o==="version-first")&&n.options.remotes.forEach(C=>{C.shareScope===e&&f.push(w(C.name))}),f}loadShareSync(e,t){const{host:n}=this,a=W2({pkgName:e,extraOptions:t,shareInfos:n.options.shared});try{a?.scope&&a.scope.forEach(p=>{this.initializeSharing(p,{strategy:a.strategy})});const{shared:o}=Sp(this.shareScopeMap,e,a,this.hooks.lifecycle.resolveShare)||{};if(o){if(typeof o.lib=="function")return Ts(o,n.options.name),o.loaded||(o.loaded=!0,o.from===n.options.name&&(a.loaded=!0)),this.emitAfterLoadShare({lifecycle:"loadShareSync",pkgName:e,shareInfo:a,selectedShared:o}),o.lib;if(typeof o.get=="function"){const p=o.get();if(!(p instanceof Promise))return Ts(o,n.options.name),this.setShared({pkgName:e,loaded:!0,from:n.options.name,lib:p,shared:o}),this.emitAfterLoadShare({lifecycle:"loadShareSync",pkgName:e,shareInfo:a,selectedShared:o}),p}}if(a.lib)return a.loaded||(a.loaded=!0),this.emitAfterLoadShare({lifecycle:"loadShareSync",pkgName:e,shareInfo:a,selectedShared:a}),a.lib;if(a.get){const p=a.get();return p instanceof Promise&&Xt(t?.from==="build"?DI:Ay,ca,{hostName:n.options.name,sharedPkgName:e},void 0,Wi(n.options)),a.lib=p,this.setShared({pkgName:e,loaded:!0,from:n.options.name,lib:a.lib,shared:a}),this.emitAfterLoadShare({lifecycle:"loadShareSync",pkgName:e,shareInfo:a,selectedShared:a}),a.lib}Xt(Ay,ca,{hostName:n.options.name,sharedPkgName:e},void 0,Wi(n.options))}catch(o){throw this.emitErrorLoadShare({lifecycle:"loadShareSync",pkgName:e,shareInfo:a,error:o}),o}}initShareScopeMap(e,t,n={}){const{host:a}=this;this.shareScopeMap[e]=t,this.hooks.lifecycle.initContainerShareScopeMap.emit({shareScope:t,options:a.options,origin:a,scopeName:e,hostShareScopeMap:n.hostShareScopeMap})}setShared({pkgName:e,shared:t,from:n,lib:a,loading:o,loaded:p,get:f,treeShaking:m}){const{version:h,scope:u="default",...x}=t,w=Array.isArray(u)?u:[u],C=A=>{const R=(O,D,z)=>{z&&!O[D]&&(O[D]=z)},I=m?A.treeShaking:A;R(I,"loaded",p),R(I,"loading",o),R(I,"get",f)};w.forEach(A=>{this.shareScopeMap[A]||(this.shareScopeMap[A]={}),this.shareScopeMap[A][e]||(this.shareScopeMap[A][e]={}),this.shareScopeMap[A][e][h]||(this.shareScopeMap[A][e][h]={version:h,scope:[A],...x,lib:a});const R=this.shareScopeMap[A][e][h];C(R),n&&R.from!==n&&(R.from=n)})}_setGlobalShareScopeMap(e){const t=II(),n=e.id||e.name;n&&!t[n]&&(t[n]=this.shareScopeMap)}},hae=class{constructor(e){this.hooks=new Ks({beforeRegisterRemote:new Zs("beforeRegisterRemote"),registerRemote:new Zs("registerRemote"),beforeRequest:new Lr("beforeRequest"),afterMatchRemote:new wn("afterMatchRemote"),onLoad:new wn("onLoad"),afterLoadRemote:new wn("afterLoadRemote"),handlePreloadModule:new sa("handlePreloadModule"),errorLoadRemote:new wn("errorLoadRemote"),beforePreloadRemote:new wn("beforePreloadRemote"),generatePreloadAssets:new wn("generatePreloadAssets"),afterPreloadRemote:new wn("afterPreloadRemote"),loadEntry:new wn}),this.host=e,this.idToRemoteMap={}}formatAndRegisterRemote(e,t){return(t.remotes||[]).reduce((n,a)=>(this.registerRemote(a,n,{force:!1}),n),e.remotes)}setIdToRemoteMap(e,t){const{remote:n,expose:a}=t,{name:o,alias:p}=n;if(this.idToRemoteMap[e]={name:n.name,expose:a},p&&e.startsWith(o)){const f=e.replace(o,p);this.idToRemoteMap[f]={name:n.name,expose:a};return}if(p&&e.startsWith(p)){const f=e.replace(p,o);this.idToRemoteMap[f]={name:n.name,expose:a}}}async loadRemote(e,t){const{host:n}=this,a=Y2(n.options.remotes,e);let o=e,p=a?.expose,f=a?$s(a.remote):void 0,m;try{const{loadFactory:h=!0}=t||{loadFactory:!0},{module:u,moduleOptions:x,remoteMatchInfo:w}=await this.getRemoteModuleAndOptions({id:e}),{pkgNameOrAlias:C,remote:A,expose:R,id:I,remoteSnapshot:O}=w;o=I,p=R,f=$s(A);const D=await u.get(I,R,t,O),z=await this.hooks.lifecycle.onLoad.emit({id:I,pkgNameOrAlias:C,expose:R,exposeModule:h?D:void 0,exposeModuleFactory:h?void 0:D,remote:A,options:x,moduleInstance:u,origin:n});return this.setIdToRemoteMap(e,w),m={id:o,expose:p,remote:f,options:t,origin:n},typeof z=="function"?z:D}catch(h){const{from:u="runtime"}=t||{from:"runtime"};let x;try{x=await this.hooks.lifecycle.errorLoadRemote.emit({id:e,error:h,from:u,lifecycle:"onLoad",expose:p,remote:f,origin:n})}catch(w){throw m={id:o,expose:p,remote:f,options:t,error:w,origin:n},w}if(!x)throw m={id:o,expose:p,remote:f,options:t,error:h,origin:n},h;return m={id:o,expose:p,remote:f,options:t,error:h,origin:n,recovered:!0},x}finally{m&&await this.hooks.lifecycle.afterLoadRemote.emit(m)}}async preloadRemote(e){const{host:t}=this,n=[];await this.hooks.lifecycle.beforePreloadRemote.emit({preloadOps:e,options:t.options,origin:t});const a=aae(t.options.remotes,e),o=m=>{const{preloadConfig:h,remote:u}=m,x=h.exposes||[];return x.length?x.map(w=>({ops:{...m,preloadConfig:{...h,exposes:[w]}},id:c0(u.name,w)})):[{ops:m,id:`${u.name}/*`}]};let p;await Promise.all(a.flatMap(o).map(async m=>{const{ops:h,id:u}=m,{remote:x,preloadConfig:w}=h,C=$s(x);try{const{globalSnapshot:A,remoteSnapshot:R}=await t.snapshotHandler.loadRemoteSnapshotInfo({moduleInfo:x,id:u,initiator:"preloadRemote"}),I=await this.hooks.lifecycle.generatePreloadAssets.emit({origin:t,preloadOptions:h,remote:x,remoteInfo:C,globalSnapshot:A,remoteSnapshot:R});if(!I)return;const O=await GI(C,t,I,!0,{initiator:"preloadRemote",id:u});n.push({remote:x,remoteInfo:C,preloadConfig:w,id:u,results:O})}catch(A){n.push({remote:x,remoteInfo:C,preloadConfig:w,id:u,results:[{url:C.entry,status:"error",resourceType:/\.json(?:$|[?#])/i.test(C.entry)?"manifest":"remoteEntry",initiator:"preloadRemote",id:u,error:A}]})}}));const f=n.flatMap(m=>m.results.filter(h=>h.status==="error"||h.status==="timeout"));if(f.length>0&&(p=new Error(`preloadRemote failed to load ${f.length} resource(s).`),Object.assign(p,{results:n,failedResults:f})),await this.hooks.lifecycle.afterPreloadRemote.emit({preloadOps:e,options:t.options,origin:t,results:n,error:p}),p)throw p}registerRemotes(e,t){const{host:n}=this;e.forEach(a=>{this.registerRemote(a,n.options.remotes,{force:t?.force})})}async getRemoteModuleAndOptions(e){const{host:t}=this,{id:n}=e;let a;try{a=await this.hooks.lifecycle.beforeRequest.emit({id:n,options:t.options,origin:t})}catch(A){if(a=await this.hooks.lifecycle.errorLoadRemote.emit({id:n,options:t.options,origin:t,from:"runtime",error:A,lifecycle:"beforeRequest"}),!a)throw A}const{id:o}=a,p=Y2(t.options.remotes,o);if(!p)try{Xt(PI,ca,{hostName:t.options.name,requestId:o},void 0,Wi(t.options))}catch(A){throw await this.hooks.lifecycle.afterMatchRemote.emit({id:o,options:t.options,error:A,origin:t}),A}const{remote:f}=p,m=$s(f);await this.hooks.lifecycle.afterMatchRemote.emit({id:o,...p,options:t.options,remoteInfo:m,origin:t});const h=await t.sharedHandler.hooks.lifecycle.afterResolve.emit({id:o,...p,options:t.options,origin:t,remoteInfo:m}),{remote:u,expose:x}=h;Zi(u&&x,`The 'beforeRequest' hook was executed, but it failed to return the correct 'remote' and 'expose' values while loading ${o}.`);let w=t.moduleCache.get(u.name);const C={host:t,remoteInfo:m};return w||(w=new ZI(C),t.moduleCache.set(u.name,w)),{module:w,moduleOptions:C,remoteMatchInfo:h}}registerRemote(e,t,n){const{host:a}=this,o=()=>{if(e.alias){const f=t.find(m=>e.alias&&(m.name.startsWith(e.alias)||m.alias?.startsWith(e.alias)));Zi(!f,`The alias ${e.alias} of remote ${e.name} is not allowed to be the prefix of ${f&&f.name} name or alias`)}"entry"in e&&Vr&&typeof window<"u"&&!e.entry.startsWith("http")&&(e.entry=new URL(e.entry,window.location.origin).href),e.shareScope||(e.shareScope=Am),e.type||(e.type=qne)};this.hooks.lifecycle.beforeRegisterRemote.emit({remote:e,origin:a});const p=t.find(f=>f.name===e.name);if(!p)o(),t.push(e),this.hooks.lifecycle.registerRemote.emit({remote:e,origin:a});else{const f=[`The remote "${e.name}" is already registered.`,"Please note that overriding it may cause unexpected errors."];n?.force&&(this.removeRemote(p),o(),t.push(e),this.hooks.lifecycle.registerRemote.emit({remote:e,origin:a}),mI(f.join(" ")))}}removeRemote(e){try{const{host:t}=this,{name:n}=e,a=t.options.remotes.findIndex(p=>p.name===n);a!==-1&&t.options.remotes.splice(a,1);const o=t.moduleCache.get(e.name);if(o){const p=o.remoteInfo,f=p.entryGlobalName;Dn[f]&&(Object.getOwnPropertyDescriptor(Dn,f)?.configurable?delete Dn[f]:Dn[f]=void 0);const m=Ey(o.remoteInfo);Hs[m]&&delete Hs[m],t.snapshotHandler.manifestCache.delete(p.entry);let h=p.buildVersion?pI(p.name,p.buildVersion):p.name;const u=Dn.__FEDERATION__.__INSTANCES__.findIndex(w=>p.buildVersion?w.options.id===h:w.name===h);if(u!==-1){const w=Dn.__FEDERATION__.__INSTANCES__[u];h=w.options.id||h;const C=II();let A=!0;const R=[];Object.keys(C).forEach(I=>{const O=C[I];O&&Object.keys(O).forEach(D=>{const z=O[D];z&&Object.keys(z).forEach(B=>{const q=z[B];q&&Object.keys(q).forEach(G=>{const ae=q[G];ae&&typeof ae=="object"&&ae.from===p.name&&(ae.loaded||ae.loading?(ae.useIn=ae.useIn.filter(Q=>Q!==p.name),ae.useIn.length?A=!1:R.push([I,D,B,G])):R.push([I,D,B,G]))})})})}),A&&(w.shareScopeMap={},delete C[h]),R.forEach(([I,O,D,z])=>{delete C[I]?.[O]?.[D]?.[z]}),Dn.__FEDERATION__.__INSTANCES__.splice(u,1)}const{hostGlobalSnapshot:x}=XI(e,t);if(x){const w=x&&"remotesInfo"in x&&x.remotesInfo&&ol(x.remotesInfo,e.name).key;w&&(delete x.remotesInfo[w],Qc.__FEDERATION__.__MANIFEST_LOADING__[w]&&delete Qc.__FEDERATION__.__MANIFEST_LOADING__[w])}t.moduleCache.delete(e.name)}}catch(t){Cy.error(`removeRemote failed: ${t instanceof Error?t.message:String(t)}`)}}},gae=typeof FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN=="boolean"?!FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN:!0,vae=class{constructor(e){this.hooks=new Ks({beforeInit:new Zs("beforeInit"),init:new sa,beforeInitContainer:new Lr("beforeInitContainer"),initContainer:new Lr("initContainer")}),this.version="2.5.1",this.moduleCache=new Map,this.loaderHook=new Ks({getModuleInfo:new sa,createScript:new sa,createLink:new sa,fetch:new wn,loadEntryError:new wn,afterLoadEntry:new wn("afterLoadEntry"),beforeInitRemote:new wn("beforeInitRemote"),afterInitRemote:new wn("afterInitRemote"),beforeGetExpose:new wn("beforeGetExpose"),afterGetExpose:new wn("afterGetExpose"),beforeExecuteFactory:new wn("beforeExecuteFactory"),afterExecuteFactory:new wn("afterExecuteFactory"),getModuleFactory:new wn}),this.bridgeHook=new Ks({beforeBridgeRender:new sa,afterBridgeRender:new sa,beforeBridgeDestroy:new sa,afterBridgeDestroy:new sa});const t=gae?[cae(),pae()]:[],n={id:eae(),name:e.name,plugins:t,remotes:[],shared:{},inBrowser:Vr};this.name=e.name,this.options=n,this.snapshotHandler=new mae(this),this.sharedHandler=new fae(this),this.remoteHandler=new hae(this),this.shareScopeMap=this.sharedHandler.shareScopeMap,this.registerPlugins([...n.plugins,...e.plugins||[]]),this.options=this.formatOptions(n,e)}initOptions(e){e.name&&e.name!==this.options.name&&Xt(SI(qI,ca)),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=Am,t){return this.sharedHandler.initializeSharing(e,t)}initRawContainer(e,t,n){const a=$s({name:e,entry:t}),o=new ZI({host:this,remoteInfo:a});return o.remoteEntryExports=n,this.moduleCache.set(e,o),o}async loadRemote(e,t){return this.remoteHandler.loadRemote(e,t)}async preloadRemote(e){return this.remoteHandler.preloadRemote(e)}initShareScopeMap(e,t,n={}){this.sharedHandler.initShareScopeMap(e,t,n)}formatOptions(e,t){const{allShareInfos:n}=TI(e,t),{userOptions:a,options:o}=this.hooks.lifecycle.beforeInit.emit({origin:this,userOptions:t,options:e,shareInfo:n}),p=this.remoteHandler.formatAndRegisterRemote(o,a),{allShareInfos:f}=this.sharedHandler.registerShared(o,a),m=[...o.plugins];a.plugins&&a.plugins.forEach(u=>{m.includes(u)||m.push(u)});const h={...e,...t,plugins:m,remotes:p,shared:f,id:a.id||e.id};return this.hooks.lifecycle.init.emit({origin:this,options:h}),h}registerPlugins(e){const t=tae(e,this);this.options.plugins=this.options.plugins.reduce((n,a)=>(a&&n&&!n.find(o=>o.name===a.name)&&n.push(a),n),t||[])}registerRemotes(e,t){return this.remoteHandler.registerRemotes(e,t)}registerShared(e){this.sharedHandler.registerShared(this.options,{...this.options,shared:e})}};sne(vae);gi("camstack:widget-registry",null);function ehe({title:e,icon:t,headerRight:n,collapsible:a=!1,defaultOpen:o=!0,bodyClassName:p="p-3",children:f}){const[m,h]=T.useState(o),u=!a||m,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]}),a?m?v.jsx(zo,{className:"h-3.5 w-3.5 text-foreground-subtle"}):v.jsx(Nee,{className:"h-3.5 w-3.5 text-foreground-subtle"}):n]}),w=`px-4 py-2 flex items-center justify-between ${u?"border-b border-border":""}`;return v.jsxs("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[a?v.jsx("button",{type:"button",onClick:()=>h(C=>!C),className:`w-full text-left ${w}`,children:x}):v.jsx("div",{className:w,children:x}),u?v.jsx("div",{className:p,children:f}):null]})}var yae="capability.binding-changed";function mu(e,t){const[n,a]=T.useState(null);return T.useEffect(()=>{if(t===null){a(null);return}let o=!1;const p=async()=>{try{const m=await e.deviceManager.getBindings.query({deviceId:t});o||a(m)}catch{o||a(m=>m)}};p();const f=e.live?.onEvent.subscribe({category:yae},{onData:m=>{const h=m.data?.source;if(!h){p();return}h.type==="device"&&h.id===t&&p()}});return()=>{o=!0,f?.unsubscribe()}},[e,t]),T.useMemo(()=>n?HE(e,n):null,[e,n])}function To(e){const t=T.useCallback(a=>e?e.subscribe(()=>a()):()=>{},[e]),n=T.useCallback(()=>e?.value,[e]);return T.useSyncExternalStore(t,n,n)}function ft(e){const t=mu(e.trpc,e.deviceId),n=To(t!==null?e.slice(t):void 0),a=t!==null?e.cap(t):void 0,o=To(t!==null?t.state.deviceStatus:void 0),p=o?.online??!0,f=p?null:o?.lastChangedAt??null;return{dev:t,cap:a,slice:n,available:(e.requireFeature===void 0||(e.deviceFeatures??[]).includes(e.requireFeature))&&a!==void 0&&n!==void 0&&p,online:p,offlineSince:f}}function bae(e){if(e==null||typeof e!="object")return null;const t=Reflect.get(e,"data");if(t!=null&&typeof t=="object"){const n=Reflect.get(t,"capRouteReason");if(typeof n=="string")return n}return null}function the(e){const t=bae(e);return t!==null?t==="no-provider"||t==="node-offline":(e instanceof Error?e.message:String(e)).includes("provider not available")}function JI(e){var t,n,a="";if(typeof e=="string"||typeof e=="number")a+=e;else if(typeof e=="object")if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(n=JI(e[t]))&&(a&&(a+=" "),a+=n)}else for(n in e)e[n]&&(a&&(a+=" "),a+=n);return a}function e4(){for(var e,t,n=0,a="",o=arguments.length;n<o;n++)(e=arguments[n])&&(t=JI(e))&&(a&&(a+=" "),a+=t);return a}var Sae=(e,t)=>{const n=new Array(e.length+t.length);for(let a=0;a<e.length;a++)n[a]=e[a];for(let a=0;a<t.length;a++)n[e.length+a]=t[a];return n},xae=(e,t)=>({classGroupId:e,validator:t}),t4=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Yp="-",X2=[],kae="arbitrary..",wae=e=>{const t=Cae(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:a}=e;return{getClassGroupId:f=>{if(f.startsWith("[")&&f.endsWith("]"))return Mae(f);const m=f.split(Yp);return n4(m,m[0]===""&&m.length>1?1:0,t)},getConflictingClassGroupIds:(f,m)=>{if(m){const h=a[f],u=n[f];return h?u?Sae(u,h):h:u||X2}return n[f]||X2}}},n4=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const a=e[t],o=n.nextPart.get(a);if(o){const h=n4(e,t+1,o);if(h)return h}const p=n.validators;if(p===null)return;const f=t===0?e.join(Yp):e.slice(t).join(Yp),m=p.length;for(let h=0;h<m;h++){const u=p[h];if(u.validator(f))return u.classGroupId}},Mae=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),a=t.slice(0,n);return a?kae+a:void 0})(),Cae=e=>{const{theme:t,classGroups:n}=e;return Aae(n,t)},Aae=(e,t)=>{const n=t4();for(const a in e){const o=e[a];p0(o,n,a,t)}return n},p0=(e,t,n,a)=>{const o=e.length;for(let p=0;p<o;p++){const f=e[p];Eae(f,t,n,a)}},Eae=(e,t,n,a)=>{if(typeof e=="string"){Rae(e,t,n);return}if(typeof e=="function"){_ae(e,t,n,a);return}Tae(e,t,n,a)},Rae=(e,t,n)=>{const a=e===""?t:a4(t,e);a.classGroupId=n},_ae=(e,t,n,a)=>{if(Iae(e)){p0(e(a),t,n,a);return}t.validators===null&&(t.validators=[]),t.validators.push(xae(n,e))},Tae=(e,t,n,a)=>{const o=Object.entries(e),p=o.length;for(let f=0;f<p;f++){const[m,h]=o[f];p0(h,a4(t,m),n,a)}},a4=(e,t)=>{let n=e;const a=t.split(Yp),o=a.length;for(let p=0;p<o;p++){const f=a[p];let m=n.nextPart.get(f);m||(m=t4(),n.nextPart.set(f,m)),n=m}return n},Iae=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,Nae=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),a=Object.create(null);const o=(p,f)=>{n[p]=f,t++,t>e&&(t=0,a=n,n=Object.create(null))};return{get(p){let f=n[p];if(f!==void 0)return f;if((f=a[p])!==void 0)return o(p,f),f},set(p,f){p in n?n[p]=f:o(p,f)}}},Ry="!",J2=":",Oae=[],eC=(e,t,n,a,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:a,isExternal:o}),jae=e=>{const{prefix:t,experimentalParseClassName:n}=e;let a=o=>{const p=[];let f=0,m=0,h=0,u;const x=o.length;for(let I=0;I<x;I++){const O=o[I];if(f===0&&m===0){if(O===J2){p.push(o.slice(h,I)),h=I+1;continue}if(O==="/"){u=I;continue}}O==="["?f++:O==="]"?f--:O==="("?m++:O===")"&&m--}const w=p.length===0?o:o.slice(h);let C=w,A=!1;w.endsWith(Ry)?(C=w.slice(0,-1),A=!0):w.startsWith(Ry)&&(C=w.slice(1),A=!0);const R=u&&u>h?u-h:void 0;return eC(p,A,C,R)};if(t){const o=t+J2,p=a;a=f=>f.startsWith(o)?p(f.slice(o.length)):eC(Oae,!1,f,void 0,!0)}if(n){const o=a;a=p=>n({className:p,parseClassName:o})}return a},Pae=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,a)=>{t.set(n,1e6+a)}),n=>{const a=[];let o=[];for(let p=0;p<n.length;p++){const f=n[p],m=f[0]==="[",h=t.has(f);m||h?(o.length>0&&(o.sort(),a.push(...o),o=[]),a.push(f)):o.push(f)}return o.length>0&&(o.sort(),a.push(...o)),a}},Dae=e=>({cache:Nae(e.cacheSize),parseClassName:jae(e),sortModifiers:Pae(e),postfixLookupClassGroupIds:zae(e),...wae(e)}),zae=e=>{const t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let a=0;a<n.length;a++)t[n[a]]=!0;return t},Lae=/\s+/,qae=(e,t)=>{const{parseClassName:n,getClassGroupId:a,getConflictingClassGroupIds:o,sortModifiers:p,postfixLookupClassGroupIds:f}=t,m=[],h=e.trim().split(Lae);let u="";for(let x=h.length-1;x>=0;x-=1){const w=h[x],{isExternal:C,modifiers:A,hasImportantModifier:R,baseClassName:I,maybePostfixModifierPosition:O}=n(w);if(C){u=w+(u.length>0?" "+u:u);continue}let D=!!O,z;if(D){z=a(I.substring(0,O));const Q=z&&f[z]?a(I):void 0;Q&&Q!==z&&(z=Q,D=!1)}else z=a(I);if(!z){if(!D){u=w+(u.length>0?" "+u:u);continue}if(z=a(I),!z){u=w+(u.length>0?" "+u:u);continue}D=!1}const B=A.length===0?"":A.length===1?A[0]:p(A).join(":"),q=R?B+Ry:B,G=q+z;if(m.indexOf(G)>-1)continue;m.push(G);const ae=o(z,D);for(let Q=0;Q<ae.length;++Q){const H=ae[Q];m.push(q+H)}u=w+(u.length>0?" "+u:u)}return u},Bae=(...e)=>{let t=0,n,a,o="";for(;t<e.length;)(n=e[t++])&&(a=i4(n))&&(o&&(o+=" "),o+=a);return o},i4=e=>{if(typeof e=="string")return e;let t,n="";for(let a=0;a<e.length;a++)e[a]&&(t=i4(e[a]))&&(n&&(n+=" "),n+=t);return n},Uae=(e,...t)=>{let n,a,o,p;const f=h=>(n=Dae(t.reduce((u,x)=>x(u),e())),a=n.cache.get,o=n.cache.set,p=m,m(h)),m=h=>{const u=a(h);if(u)return u;const x=qae(h,n);return o(h,x),x};return p=f,(...h)=>p(Bae(...h))},Fae=[],En=e=>{const t=n=>n[e]||Fae;return t.isThemeGetter=!0,t},r4=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,o4=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Hae=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,$ae=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Qae=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Vae=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Gae=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Zae=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,_r=e=>Hae.test(e),ct=e=>!!e&&!Number.isNaN(Number(e)),ci=e=>!!e&&Number.isInteger(Number(e)),Dg=e=>e.endsWith("%")&&ct(e.slice(0,-1)),Hi=e=>$ae.test(e),s4=()=>!0,Kae=e=>Qae.test(e)&&!Vae.test(e),m0=()=>!1,Wae=e=>Gae.test(e),Yae=e=>Zae.test(e),Xae=e=>!je(e)&&!Pe(e),Jae=e=>e.startsWith("@container")&&(e[10]==="/"&&e[11]!==void 0||e[11]==="s"&&e[16]!==void 0&&e.startsWith("-size/",10)||e[11]==="n"&&e[18]!==void 0&&e.startsWith("-normal/",10)),eie=e=>Gr(e,u4,m0),je=e=>r4.test(e),go=e=>Gr(e,d4,Kae),tC=e=>Gr(e,lie,ct),tie=e=>Gr(e,m4,s4),nie=e=>Gr(e,p4,m0),nC=e=>Gr(e,l4,m0),aie=e=>Gr(e,c4,Yae),Qd=e=>Gr(e,f4,Wae),Pe=e=>o4.test(e),fc=e=>qo(e,d4),iie=e=>qo(e,p4),aC=e=>qo(e,l4),rie=e=>qo(e,u4),oie=e=>qo(e,c4),Vd=e=>qo(e,f4,!0),sie=e=>qo(e,m4,!0),Gr=(e,t,n)=>{const a=r4.exec(e);return a?a[1]?t(a[1]):n(a[2]):!1},qo=(e,t,n=!1)=>{const a=o4.exec(e);return a?a[1]?t(a[1]):n:!1},l4=e=>e==="position"||e==="percentage",c4=e=>e==="image"||e==="url",u4=e=>e==="length"||e==="size"||e==="bg-size",d4=e=>e==="length",lie=e=>e==="number",p4=e=>e==="family-name",m4=e=>e==="number"||e==="weight",f4=e=>e==="shadow",cie=()=>{const e=En("color"),t=En("font"),n=En("text"),a=En("font-weight"),o=En("tracking"),p=En("leading"),f=En("breakpoint"),m=En("container"),h=En("spacing"),u=En("radius"),x=En("shadow"),w=En("inset-shadow"),C=En("text-shadow"),A=En("drop-shadow"),R=En("blur"),I=En("perspective"),O=En("aspect"),D=En("ease"),z=En("animate"),B=()=>["auto","avoid","all","avoid-page","page","left","right","column"],q=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],G=()=>[...q(),Pe,je],ae=()=>["auto","hidden","clip","visible","scroll"],Q=()=>["auto","contain","none"],H=()=>[Pe,je,h],oe=()=>[_r,"full","auto",...H()],we=()=>[ci,"none","subgrid",Pe,je],Me=()=>["auto",{span:["full",ci,Pe,je]},ci,Pe,je],Ae=()=>[ci,"auto",Pe,je],Ce=()=>["auto","min","max","fr",Pe,je],re=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],Te=()=>["start","end","center","stretch","center-safe","end-safe"],F=()=>["auto",...H()],ue=()=>[_r,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...H()],ke=()=>[_r,"screen","full","dvw","lvw","svw","min","max","fit",...H()],Ee=()=>[_r,"screen","full","lh","dvh","lvh","svh","min","max","fit",...H()],fe=()=>[e,Pe,je],L=()=>[...q(),aC,nC,{position:[Pe,je]}],ee=()=>["no-repeat",{repeat:["","x","y","space","round"]}],me=()=>["auto","cover","contain",rie,eie,{size:[Pe,je]}],be=()=>[Dg,fc,go],X=()=>["","none","full",u,Pe,je],xe=()=>["",ct,fc,go],Oe=()=>["solid","dashed","dotted","double"],le=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ye=()=>[ct,Dg,aC,nC],Be=()=>["","none",R,Pe,je],ot=()=>["none",ct,Pe,je],Ve=()=>["none",ct,Pe,je],Ie=()=>[ct,Pe,je],bt=()=>[_r,"full",...H()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Hi],breakpoint:[Hi],color:[s4],container:[Hi],"drop-shadow":[Hi],ease:["in","out","in-out"],font:[Xae],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Hi],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Hi],shadow:[Hi],spacing:["px",ct],text:[Hi],"text-shadow":[Hi],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",_r,je,Pe,O]}],container:["container"],"container-type":[{"@container":["","normal","size",Pe,je]}],"container-named":[Jae],columns:[{columns:[ct,je,Pe,m]}],"break-after":[{"break-after":B()}],"break-before":[{"break-before":B()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:G()}],overflow:[{overflow:ae()}],"overflow-x":[{"overflow-x":ae()}],"overflow-y":[{"overflow-y":ae()}],overscroll:[{overscroll:Q()}],"overscroll-x":[{"overscroll-x":Q()}],"overscroll-y":[{"overscroll-y":Q()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:oe()}],"inset-x":[{"inset-x":oe()}],"inset-y":[{"inset-y":oe()}],start:[{"inset-s":oe(),start:oe()}],end:[{"inset-e":oe(),end:oe()}],"inset-bs":[{"inset-bs":oe()}],"inset-be":[{"inset-be":oe()}],top:[{top:oe()}],right:[{right:oe()}],bottom:[{bottom:oe()}],left:[{left:oe()}],visibility:["visible","invisible","collapse"],z:[{z:[ci,"auto",Pe,je]}],basis:[{basis:[_r,"full","auto",m,...H()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ct,_r,"auto","initial","none",je]}],grow:[{grow:["",ct,Pe,je]}],shrink:[{shrink:["",ct,Pe,je]}],order:[{order:[ci,"first","last","none",Pe,je]}],"grid-cols":[{"grid-cols":we()}],"col-start-end":[{col:Me()}],"col-start":[{"col-start":Ae()}],"col-end":[{"col-end":Ae()}],"grid-rows":[{"grid-rows":we()}],"row-start-end":[{row:Me()}],"row-start":[{"row-start":Ae()}],"row-end":[{"row-end":Ae()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":Ce()}],"auto-rows":[{"auto-rows":Ce()}],gap:[{gap:H()}],"gap-x":[{"gap-x":H()}],"gap-y":[{"gap-y":H()}],"justify-content":[{justify:[...re(),"normal"]}],"justify-items":[{"justify-items":[...Te(),"normal"]}],"justify-self":[{"justify-self":["auto",...Te()]}],"align-content":[{content:["normal",...re()]}],"align-items":[{items:[...Te(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...Te(),{baseline:["","last"]}]}],"place-content":[{"place-content":re()}],"place-items":[{"place-items":[...Te(),"baseline"]}],"place-self":[{"place-self":["auto",...Te()]}],p:[{p:H()}],px:[{px:H()}],py:[{py:H()}],ps:[{ps:H()}],pe:[{pe:H()}],pbs:[{pbs:H()}],pbe:[{pbe:H()}],pt:[{pt:H()}],pr:[{pr:H()}],pb:[{pb:H()}],pl:[{pl:H()}],m:[{m:F()}],mx:[{mx:F()}],my:[{my:F()}],ms:[{ms:F()}],me:[{me:F()}],mbs:[{mbs:F()}],mbe:[{mbe:F()}],mt:[{mt:F()}],mr:[{mr:F()}],mb:[{mb:F()}],ml:[{ml:F()}],"space-x":[{"space-x":H()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":H()}],"space-y-reverse":["space-y-reverse"],size:[{size:ue()}],"inline-size":[{inline:["auto",...ke()]}],"min-inline-size":[{"min-inline":["auto",...ke()]}],"max-inline-size":[{"max-inline":["none",...ke()]}],"block-size":[{block:["auto",...Ee()]}],"min-block-size":[{"min-block":["auto",...Ee()]}],"max-block-size":[{"max-block":["none",...Ee()]}],w:[{w:[m,"screen",...ue()]}],"min-w":[{"min-w":[m,"screen","none",...ue()]}],"max-w":[{"max-w":[m,"screen","none","prose",{screen:[f]},...ue()]}],h:[{h:["screen","lh",...ue()]}],"min-h":[{"min-h":["screen","lh","none",...ue()]}],"max-h":[{"max-h":["screen","lh",...ue()]}],"font-size":[{text:["base",n,fc,go]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,sie,tie]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Dg,je]}],"font-family":[{font:[iie,nie,t]}],"font-features":[{"font-features":[je]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[o,Pe,je]}],"line-clamp":[{"line-clamp":[ct,"none",Pe,tC]}],leading:[{leading:[p,...H()]}],"list-image":[{"list-image":["none",Pe,je]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Pe,je]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:fe()}],"text-color":[{text:fe()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Oe(),"wavy"]}],"text-decoration-thickness":[{decoration:[ct,"from-font","auto",Pe,go]}],"text-decoration-color":[{decoration:fe()}],"underline-offset":[{"underline-offset":[ct,"auto",Pe,je]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:H()}],"tab-size":[{tab:[ci,Pe,je]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Pe,je]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Pe,je]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:L()}],"bg-repeat":[{bg:ee()}],"bg-size":[{bg:me()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},ci,Pe,je],radial:["",Pe,je],conic:[ci,Pe,je]},oie,aie]}],"bg-color":[{bg:fe()}],"gradient-from-pos":[{from:be()}],"gradient-via-pos":[{via:be()}],"gradient-to-pos":[{to:be()}],"gradient-from":[{from:fe()}],"gradient-via":[{via:fe()}],"gradient-to":[{to:fe()}],rounded:[{rounded:X()}],"rounded-s":[{"rounded-s":X()}],"rounded-e":[{"rounded-e":X()}],"rounded-t":[{"rounded-t":X()}],"rounded-r":[{"rounded-r":X()}],"rounded-b":[{"rounded-b":X()}],"rounded-l":[{"rounded-l":X()}],"rounded-ss":[{"rounded-ss":X()}],"rounded-se":[{"rounded-se":X()}],"rounded-ee":[{"rounded-ee":X()}],"rounded-es":[{"rounded-es":X()}],"rounded-tl":[{"rounded-tl":X()}],"rounded-tr":[{"rounded-tr":X()}],"rounded-br":[{"rounded-br":X()}],"rounded-bl":[{"rounded-bl":X()}],"border-w":[{border:xe()}],"border-w-x":[{"border-x":xe()}],"border-w-y":[{"border-y":xe()}],"border-w-s":[{"border-s":xe()}],"border-w-e":[{"border-e":xe()}],"border-w-bs":[{"border-bs":xe()}],"border-w-be":[{"border-be":xe()}],"border-w-t":[{"border-t":xe()}],"border-w-r":[{"border-r":xe()}],"border-w-b":[{"border-b":xe()}],"border-w-l":[{"border-l":xe()}],"divide-x":[{"divide-x":xe()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":xe()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Oe(),"hidden","none"]}],"divide-style":[{divide:[...Oe(),"hidden","none"]}],"border-color":[{border:fe()}],"border-color-x":[{"border-x":fe()}],"border-color-y":[{"border-y":fe()}],"border-color-s":[{"border-s":fe()}],"border-color-e":[{"border-e":fe()}],"border-color-bs":[{"border-bs":fe()}],"border-color-be":[{"border-be":fe()}],"border-color-t":[{"border-t":fe()}],"border-color-r":[{"border-r":fe()}],"border-color-b":[{"border-b":fe()}],"border-color-l":[{"border-l":fe()}],"divide-color":[{divide:fe()}],"outline-style":[{outline:[...Oe(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ct,Pe,je]}],"outline-w":[{outline:["",ct,fc,go]}],"outline-color":[{outline:fe()}],shadow:[{shadow:["","none",x,Vd,Qd]}],"shadow-color":[{shadow:fe()}],"inset-shadow":[{"inset-shadow":["none",w,Vd,Qd]}],"inset-shadow-color":[{"inset-shadow":fe()}],"ring-w":[{ring:xe()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:fe()}],"ring-offset-w":[{"ring-offset":[ct,go]}],"ring-offset-color":[{"ring-offset":fe()}],"inset-ring-w":[{"inset-ring":xe()}],"inset-ring-color":[{"inset-ring":fe()}],"text-shadow":[{"text-shadow":["none",C,Vd,Qd]}],"text-shadow-color":[{"text-shadow":fe()}],opacity:[{opacity:[ct,Pe,je]}],"mix-blend":[{"mix-blend":[...le(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":le()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[ct]}],"mask-image-linear-from-pos":[{"mask-linear-from":ye()}],"mask-image-linear-to-pos":[{"mask-linear-to":ye()}],"mask-image-linear-from-color":[{"mask-linear-from":fe()}],"mask-image-linear-to-color":[{"mask-linear-to":fe()}],"mask-image-t-from-pos":[{"mask-t-from":ye()}],"mask-image-t-to-pos":[{"mask-t-to":ye()}],"mask-image-t-from-color":[{"mask-t-from":fe()}],"mask-image-t-to-color":[{"mask-t-to":fe()}],"mask-image-r-from-pos":[{"mask-r-from":ye()}],"mask-image-r-to-pos":[{"mask-r-to":ye()}],"mask-image-r-from-color":[{"mask-r-from":fe()}],"mask-image-r-to-color":[{"mask-r-to":fe()}],"mask-image-b-from-pos":[{"mask-b-from":ye()}],"mask-image-b-to-pos":[{"mask-b-to":ye()}],"mask-image-b-from-color":[{"mask-b-from":fe()}],"mask-image-b-to-color":[{"mask-b-to":fe()}],"mask-image-l-from-pos":[{"mask-l-from":ye()}],"mask-image-l-to-pos":[{"mask-l-to":ye()}],"mask-image-l-from-color":[{"mask-l-from":fe()}],"mask-image-l-to-color":[{"mask-l-to":fe()}],"mask-image-x-from-pos":[{"mask-x-from":ye()}],"mask-image-x-to-pos":[{"mask-x-to":ye()}],"mask-image-x-from-color":[{"mask-x-from":fe()}],"mask-image-x-to-color":[{"mask-x-to":fe()}],"mask-image-y-from-pos":[{"mask-y-from":ye()}],"mask-image-y-to-pos":[{"mask-y-to":ye()}],"mask-image-y-from-color":[{"mask-y-from":fe()}],"mask-image-y-to-color":[{"mask-y-to":fe()}],"mask-image-radial":[{"mask-radial":[Pe,je]}],"mask-image-radial-from-pos":[{"mask-radial-from":ye()}],"mask-image-radial-to-pos":[{"mask-radial-to":ye()}],"mask-image-radial-from-color":[{"mask-radial-from":fe()}],"mask-image-radial-to-color":[{"mask-radial-to":fe()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":q()}],"mask-image-conic-pos":[{"mask-conic":[ct]}],"mask-image-conic-from-pos":[{"mask-conic-from":ye()}],"mask-image-conic-to-pos":[{"mask-conic-to":ye()}],"mask-image-conic-from-color":[{"mask-conic-from":fe()}],"mask-image-conic-to-color":[{"mask-conic-to":fe()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:L()}],"mask-repeat":[{mask:ee()}],"mask-size":[{mask:me()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Pe,je]}],filter:[{filter:["","none",Pe,je]}],blur:[{blur:Be()}],brightness:[{brightness:[ct,Pe,je]}],contrast:[{contrast:[ct,Pe,je]}],"drop-shadow":[{"drop-shadow":["","none",A,Vd,Qd]}],"drop-shadow-color":[{"drop-shadow":fe()}],grayscale:[{grayscale:["",ct,Pe,je]}],"hue-rotate":[{"hue-rotate":[ct,Pe,je]}],invert:[{invert:["",ct,Pe,je]}],saturate:[{saturate:[ct,Pe,je]}],sepia:[{sepia:["",ct,Pe,je]}],"backdrop-filter":[{"backdrop-filter":["","none",Pe,je]}],"backdrop-blur":[{"backdrop-blur":Be()}],"backdrop-brightness":[{"backdrop-brightness":[ct,Pe,je]}],"backdrop-contrast":[{"backdrop-contrast":[ct,Pe,je]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ct,Pe,je]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ct,Pe,je]}],"backdrop-invert":[{"backdrop-invert":["",ct,Pe,je]}],"backdrop-opacity":[{"backdrop-opacity":[ct,Pe,je]}],"backdrop-saturate":[{"backdrop-saturate":[ct,Pe,je]}],"backdrop-sepia":[{"backdrop-sepia":["",ct,Pe,je]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":H()}],"border-spacing-x":[{"border-spacing-x":H()}],"border-spacing-y":[{"border-spacing-y":H()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Pe,je]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ct,"initial",Pe,je]}],ease:[{ease:["linear","initial",D,Pe,je]}],delay:[{delay:[ct,Pe,je]}],animate:[{animate:["none",z,Pe,je]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[I,Pe,je]}],"perspective-origin":[{"perspective-origin":G()}],rotate:[{rotate:ot()}],"rotate-x":[{"rotate-x":ot()}],"rotate-y":[{"rotate-y":ot()}],"rotate-z":[{"rotate-z":ot()}],scale:[{scale:Ve()}],"scale-x":[{"scale-x":Ve()}],"scale-y":[{"scale-y":Ve()}],"scale-z":[{"scale-z":Ve()}],"scale-3d":["scale-3d"],skew:[{skew:Ie()}],"skew-x":[{"skew-x":Ie()}],"skew-y":[{"skew-y":Ie()}],transform:[{transform:[Pe,je,"","none","gpu","cpu"]}],"transform-origin":[{origin:G()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:bt()}],"translate-x":[{"translate-x":bt()}],"translate-y":[{"translate-y":bt()}],"translate-z":[{"translate-z":bt()}],"translate-none":["translate-none"],zoom:[{zoom:[ci,Pe,je]}],accent:[{accent:fe()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:fe()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Pe,je]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":fe()}],"scrollbar-track-color":[{"scrollbar-track":fe()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":H()}],"scroll-mx":[{"scroll-mx":H()}],"scroll-my":[{"scroll-my":H()}],"scroll-ms":[{"scroll-ms":H()}],"scroll-me":[{"scroll-me":H()}],"scroll-mbs":[{"scroll-mbs":H()}],"scroll-mbe":[{"scroll-mbe":H()}],"scroll-mt":[{"scroll-mt":H()}],"scroll-mr":[{"scroll-mr":H()}],"scroll-mb":[{"scroll-mb":H()}],"scroll-ml":[{"scroll-ml":H()}],"scroll-p":[{"scroll-p":H()}],"scroll-px":[{"scroll-px":H()}],"scroll-py":[{"scroll-py":H()}],"scroll-ps":[{"scroll-ps":H()}],"scroll-pe":[{"scroll-pe":H()}],"scroll-pbs":[{"scroll-pbs":H()}],"scroll-pbe":[{"scroll-pbe":H()}],"scroll-pt":[{"scroll-pt":H()}],"scroll-pr":[{"scroll-pr":H()}],"scroll-pb":[{"scroll-pb":H()}],"scroll-pl":[{"scroll-pl":H()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Pe,je]}],fill:[{fill:["none",...fe()]}],"stroke-w":[{stroke:[ct,fc,go,tC]}],stroke:[{stroke:["none",...fe()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},uie=Uae(cie);function se(...e){return uie(e4(e))}gi("camstack:vod-playback",{request:null,play:()=>{},clear:()=>{}});gi("camstack:recorded-playback",{bindControlChannel:null,channelOpen:!1,mode:"live",positionMs:null,send:()=>!1});T.lazy(()=>Ys(()=>import("./MotionZonesSettings-DNdnFHso-P9zbA9fe.js"),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.MotionZonesSettings}))),T.lazy(()=>Ys(()=>import("./PrivacyMaskSettings-DNSLc6ww-DRxNCXl7.js"),__vite__mapDeps([2,1]),import.meta.url).then(e=>({default:e.PrivacyMaskSettings})));var die=Object.defineProperty,Xp=Object.getOwnPropertySymbols,h4=Object.prototype.hasOwnProperty,g4=Object.prototype.propertyIsEnumerable,iC=(e,t,n)=>t in e?die(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,_y=(e,t)=>{for(var n in t||(t={}))h4.call(t,n)&&iC(e,n,t[n]);if(Xp)for(var n of Xp(t))g4.call(t,n)&&iC(e,n,t[n]);return e},Ty=(e,t)=>{var n={};for(var a in e)h4.call(e,a)&&t.indexOf(a)<0&&(n[a]=e[a]);if(e!=null&&Xp)for(var a of Xp(e))t.indexOf(a)<0&&g4.call(e,a)&&(n[a]=e[a]);return n};var No;(e=>{const t=class mt{constructor(h,u,x,w){if(this.version=h,this.errorCorrectionLevel=u,this.modules=[],this.isFunction=[],h<mt.MIN_VERSION||h>mt.MAX_VERSION)throw new RangeError("Version value out of range");if(w<-1||w>7)throw new RangeError("Mask value out of range");this.size=h*4+17;let C=[];for(let R=0;R<this.size;R++)C.push(!1);for(let R=0;R<this.size;R++)this.modules.push(C.slice()),this.isFunction.push(C.slice());this.drawFunctionPatterns();const A=this.addEccAndInterleave(x);if(this.drawCodewords(A),w==-1){let R=1e9;for(let I=0;I<8;I++){this.applyMask(I),this.drawFormatBits(I);const O=this.getPenaltyScore();O<R&&(w=I,R=O),this.applyMask(I)}}o(0<=w&&w<=7),this.mask=w,this.applyMask(w),this.drawFormatBits(w),this.isFunction=[]}static encodeText(h,u){const x=e.QrSegment.makeSegments(h);return mt.encodeSegments(x,u)}static encodeBinary(h,u){const x=e.QrSegment.makeBytes(h);return mt.encodeSegments([x],u)}static encodeSegments(h,u,x=1,w=40,C=-1,A=!0){if(!(mt.MIN_VERSION<=x&&x<=w&&w<=mt.MAX_VERSION)||C<-1||C>7)throw new RangeError("Invalid value");let R,I;for(R=x;;R++){const B=mt.getNumDataCodewords(R,u)*8,q=f.getTotalBits(h,R);if(q<=B){I=q;break}if(R>=w)throw new RangeError("Data too long")}for(const B of[mt.Ecc.MEDIUM,mt.Ecc.QUARTILE,mt.Ecc.HIGH])A&&I<=mt.getNumDataCodewords(R,B)*8&&(u=B);let O=[];for(const B of h){n(B.mode.modeBits,4,O),n(B.numChars,B.mode.numCharCountBits(R),O);for(const q of B.getData())O.push(q)}o(O.length==I);const D=mt.getNumDataCodewords(R,u)*8;o(O.length<=D),n(0,Math.min(4,D-O.length),O),n(0,(8-O.length%8)%8,O),o(O.length%8==0);for(let B=236;O.length<D;B^=253)n(B,8,O);let z=[];for(;z.length*8<O.length;)z.push(0);return O.forEach((B,q)=>z[q>>>3]|=B<<7-(q&7)),new mt(R,u,z,C)}getModule(h,u){return 0<=h&&h<this.size&&0<=u&&u<this.size&&this.modules[u][h]}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 h=this.getAlignmentPatternPositions(),u=h.length;for(let x=0;x<u;x++)for(let w=0;w<u;w++)x==0&&w==0||x==0&&w==u-1||x==u-1&&w==0||this.drawAlignmentPattern(h[x],h[w]);this.drawFormatBits(0),this.drawVersion()}drawFormatBits(h){const u=this.errorCorrectionLevel.formatBits<<3|h;let x=u;for(let C=0;C<10;C++)x=x<<1^(x>>>9)*1335;const w=(u<<10|x)^21522;o(w>>>15==0);for(let C=0;C<=5;C++)this.setFunctionModule(8,C,a(w,C));this.setFunctionModule(8,7,a(w,6)),this.setFunctionModule(8,8,a(w,7)),this.setFunctionModule(7,8,a(w,8));for(let C=9;C<15;C++)this.setFunctionModule(14-C,8,a(w,C));for(let C=0;C<8;C++)this.setFunctionModule(this.size-1-C,8,a(w,C));for(let C=8;C<15;C++)this.setFunctionModule(8,this.size-15+C,a(w,C));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let h=this.version;for(let x=0;x<12;x++)h=h<<1^(h>>>11)*7973;const u=this.version<<12|h;o(u>>>18==0);for(let x=0;x<18;x++){const w=a(u,x),C=this.size-11+x%3,A=Math.floor(x/3);this.setFunctionModule(C,A,w),this.setFunctionModule(A,C,w)}}drawFinderPattern(h,u){for(let x=-4;x<=4;x++)for(let w=-4;w<=4;w++){const C=Math.max(Math.abs(w),Math.abs(x)),A=h+w,R=u+x;0<=A&&A<this.size&&0<=R&&R<this.size&&this.setFunctionModule(A,R,C!=2&&C!=4)}}drawAlignmentPattern(h,u){for(let x=-2;x<=2;x++)for(let w=-2;w<=2;w++)this.setFunctionModule(h+w,u+x,Math.max(Math.abs(w),Math.abs(x))!=1)}setFunctionModule(h,u,x){this.modules[u][h]=x,this.isFunction[u][h]=!0}addEccAndInterleave(h){const u=this.version,x=this.errorCorrectionLevel;if(h.length!=mt.getNumDataCodewords(u,x))throw new RangeError("Invalid argument");const w=mt.NUM_ERROR_CORRECTION_BLOCKS[x.ordinal][u],C=mt.ECC_CODEWORDS_PER_BLOCK[x.ordinal][u],A=Math.floor(mt.getNumRawDataModules(u)/8),R=w-A%w,I=Math.floor(A/w);let O=[];const D=mt.reedSolomonComputeDivisor(C);for(let B=0,q=0;B<w;B++){let G=h.slice(q,q+I-C+(B<R?0:1));q+=G.length;const ae=mt.reedSolomonComputeRemainder(G,D);B<R&&G.push(0),O.push(G.concat(ae))}let z=[];for(let B=0;B<O[0].length;B++)O.forEach((q,G)=>{(B!=I-C||G>=R)&&z.push(q[B])});return o(z.length==A),z}drawCodewords(h){if(h.length!=Math.floor(mt.getNumRawDataModules(this.version)/8))throw new RangeError("Invalid argument");let u=0;for(let x=this.size-1;x>=1;x-=2){x==6&&(x=5);for(let w=0;w<this.size;w++)for(let C=0;C<2;C++){const A=x-C,R=(x+1&2)==0?this.size-1-w:w;!this.isFunction[R][A]&&u<h.length*8&&(this.modules[R][A]=a(h[u>>>3],7-(u&7)),u++)}}o(u==h.length*8)}applyMask(h){if(h<0||h>7)throw new RangeError("Mask value out of range");for(let u=0;u<this.size;u++)for(let x=0;x<this.size;x++){let w;switch(h){case 0:w=(x+u)%2==0;break;case 1:w=u%2==0;break;case 2:w=x%3==0;break;case 3:w=(x+u)%3==0;break;case 4:w=(Math.floor(x/3)+Math.floor(u/2))%2==0;break;case 5:w=x*u%2+x*u%3==0;break;case 6:w=(x*u%2+x*u%3)%2==0;break;case 7:w=((x+u)%2+x*u%3)%2==0;break;default:throw new Error("Unreachable")}!this.isFunction[u][x]&&w&&(this.modules[u][x]=!this.modules[u][x])}}getPenaltyScore(){let h=0;for(let C=0;C<this.size;C++){let A=!1,R=0,I=[0,0,0,0,0,0,0];for(let O=0;O<this.size;O++)this.modules[C][O]==A?(R++,R==5?h+=mt.PENALTY_N1:R>5&&h++):(this.finderPenaltyAddHistory(R,I),A||(h+=this.finderPenaltyCountPatterns(I)*mt.PENALTY_N3),A=this.modules[C][O],R=1);h+=this.finderPenaltyTerminateAndCount(A,R,I)*mt.PENALTY_N3}for(let C=0;C<this.size;C++){let A=!1,R=0,I=[0,0,0,0,0,0,0];for(let O=0;O<this.size;O++)this.modules[O][C]==A?(R++,R==5?h+=mt.PENALTY_N1:R>5&&h++):(this.finderPenaltyAddHistory(R,I),A||(h+=this.finderPenaltyCountPatterns(I)*mt.PENALTY_N3),A=this.modules[O][C],R=1);h+=this.finderPenaltyTerminateAndCount(A,R,I)*mt.PENALTY_N3}for(let C=0;C<this.size-1;C++)for(let A=0;A<this.size-1;A++){const R=this.modules[C][A];R==this.modules[C][A+1]&&R==this.modules[C+1][A]&&R==this.modules[C+1][A+1]&&(h+=mt.PENALTY_N2)}let u=0;for(const C of this.modules)u=C.reduce((A,R)=>A+(R?1:0),u);const x=this.size*this.size,w=Math.ceil(Math.abs(u*20-x*10)/x)-1;return o(0<=w&&w<=9),h+=w*mt.PENALTY_N4,o(0<=h&&h<=2568888),h}getAlignmentPatternPositions(){if(this.version==1)return[];{const h=Math.floor(this.version/7)+2,u=this.version==32?26:Math.ceil((this.version*4+4)/(h*2-2))*2;let x=[6];for(let w=this.size-7;x.length<h;w-=u)x.splice(1,0,w);return x}}static getNumRawDataModules(h){if(h<mt.MIN_VERSION||h>mt.MAX_VERSION)throw new RangeError("Version number out of range");let u=(16*h+128)*h+64;if(h>=2){const x=Math.floor(h/7)+2;u-=(25*x-10)*x-55,h>=7&&(u-=36)}return o(208<=u&&u<=29648),u}static getNumDataCodewords(h,u){return Math.floor(mt.getNumRawDataModules(h)/8)-mt.ECC_CODEWORDS_PER_BLOCK[u.ordinal][h]*mt.NUM_ERROR_CORRECTION_BLOCKS[u.ordinal][h]}static reedSolomonComputeDivisor(h){if(h<1||h>255)throw new RangeError("Degree out of range");let u=[];for(let w=0;w<h-1;w++)u.push(0);u.push(1);let x=1;for(let w=0;w<h;w++){for(let C=0;C<u.length;C++)u[C]=mt.reedSolomonMultiply(u[C],x),C+1<u.length&&(u[C]^=u[C+1]);x=mt.reedSolomonMultiply(x,2)}return u}static reedSolomonComputeRemainder(h,u){let x=u.map(w=>0);for(const w of h){const C=w^x.shift();x.push(0),u.forEach((A,R)=>x[R]^=mt.reedSolomonMultiply(A,C))}return x}static reedSolomonMultiply(h,u){if(h>>>8||u>>>8)throw new RangeError("Byte out of range");let x=0;for(let w=7;w>=0;w--)x=x<<1^(x>>>7)*285,x^=(u>>>w&1)*h;return o(x>>>8==0),x}finderPenaltyCountPatterns(h){const u=h[1];o(u<=this.size*3);const x=u>0&&h[2]==u&&h[3]==u*3&&h[4]==u&&h[5]==u;return(x&&h[0]>=u*4&&h[6]>=u?1:0)+(x&&h[6]>=u*4&&h[0]>=u?1:0)}finderPenaltyTerminateAndCount(h,u,x){return h&&(this.finderPenaltyAddHistory(u,x),u=0),u+=this.size,this.finderPenaltyAddHistory(u,x),this.finderPenaltyCountPatterns(x)}finderPenaltyAddHistory(h,u){u[0]==0&&(h+=this.size),u.pop(),u.unshift(h)}};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 n(m,h,u){if(h<0||h>31||m>>>h)throw new RangeError("Value out of range");for(let x=h-1;x>=0;x--)u.push(m>>>x&1)}function a(m,h){return(m>>>h&1)!=0}function o(m){if(!m)throw new Error("Assertion error")}const p=class cn{constructor(h,u,x){if(this.mode=h,this.numChars=u,this.bitData=x,u<0)throw new RangeError("Invalid argument");this.bitData=x.slice()}static makeBytes(h){let u=[];for(const x of h)n(x,8,u);return new cn(cn.Mode.BYTE,h.length,u)}static makeNumeric(h){if(!cn.isNumeric(h))throw new RangeError("String contains non-numeric characters");let u=[];for(let x=0;x<h.length;){const w=Math.min(h.length-x,3);n(parseInt(h.substring(x,x+w),10),w*3+1,u),x+=w}return new cn(cn.Mode.NUMERIC,h.length,u)}static makeAlphanumeric(h){if(!cn.isAlphanumeric(h))throw new RangeError("String contains unencodable characters in alphanumeric mode");let u=[],x;for(x=0;x+2<=h.length;x+=2){let w=cn.ALPHANUMERIC_CHARSET.indexOf(h.charAt(x))*45;w+=cn.ALPHANUMERIC_CHARSET.indexOf(h.charAt(x+1)),n(w,11,u)}return x<h.length&&n(cn.ALPHANUMERIC_CHARSET.indexOf(h.charAt(x)),6,u),new cn(cn.Mode.ALPHANUMERIC,h.length,u)}static makeSegments(h){return h==""?[]:cn.isNumeric(h)?[cn.makeNumeric(h)]:cn.isAlphanumeric(h)?[cn.makeAlphanumeric(h)]:[cn.makeBytes(cn.toUtf8ByteArray(h))]}static makeEci(h){let u=[];if(h<0)throw new RangeError("ECI assignment value out of range");if(h<128)n(h,8,u);else if(h<16384)n(2,2,u),n(h,14,u);else if(h<1e6)n(6,3,u),n(h,21,u);else throw new RangeError("ECI assignment value out of range");return new cn(cn.Mode.ECI,0,u)}static isNumeric(h){return cn.NUMERIC_REGEX.test(h)}static isAlphanumeric(h){return cn.ALPHANUMERIC_REGEX.test(h)}getData(){return this.bitData.slice()}static getTotalBits(h,u){let x=0;for(const w of h){const C=w.mode.numCharCountBits(u);if(w.numChars>=1<<C)return 1/0;x+=4+C+w.bitData.length}return x}static toUtf8ByteArray(h){h=encodeURI(h);let u=[];for(let x=0;x<h.length;x++)h.charAt(x)!="%"?u.push(h.charCodeAt(x)):(u.push(parseInt(h.substring(x+1,x+3),16)),x+=2);return u}};p.NUMERIC_REGEX=/^[0-9]*$/,p.ALPHANUMERIC_REGEX=/^[A-Z0-9 $%*+.\/:-]*$/,p.ALPHANUMERIC_CHARSET="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";let f=p;e.QrSegment=p})(No||(No={}));(e=>{(t=>{const n=class{constructor(o,p){this.ordinal=o,this.formatBits=p}};n.LOW=new n(0,1),n.MEDIUM=new n(1,0),n.QUARTILE=new n(2,3),n.HIGH=new n(3,2),t.Ecc=n})(e.QrCode||(e.QrCode={}))})(No||(No={}));(e=>{(t=>{const n=class{constructor(o,p){this.modeBits=o,this.numBitsCharCount=p}numCharCountBits(o){return this.numBitsCharCount[Math.floor((o+7)/17)]}};n.NUMERIC=new n(1,[10,12,14]),n.ALPHANUMERIC=new n(2,[9,11,13]),n.BYTE=new n(4,[8,16,16]),n.KANJI=new n(8,[8,10,12]),n.ECI=new n(7,[0,0,0]),t.Mode=n})(e.QrSegment||(e.QrSegment={}))})(No||(No={}));var Qs=No;var pie={L:Qs.QrCode.Ecc.LOW,M:Qs.QrCode.Ecc.MEDIUM,Q:Qs.QrCode.Ecc.QUARTILE,H:Qs.QrCode.Ecc.HIGH},v4=128,y4="L",b4="#FFFFFF",S4="#000000",x4=!1,k4=1,mie=4,fie=0,hie=.1;function w4(e,t=0){const n=[];return e.forEach(function(a,o){let p=null;a.forEach(function(f,m){if(!f&&p!==null){n.push(`M${p+t} ${o+t}h${m-p}v1H${p+t}z`),p=null;return}if(m===a.length-1){if(!f)return;p===null?n.push(`M${m+t},${o+t} h1v1H${m+t}z`):n.push(`M${p+t},${o+t} h${m+1-p}v1H${p+t}z`);return}f&&p===null&&(p=m)})}),n.join("")}function M4(e,t){return e.slice().map((n,a)=>a<t.y||a>=t.y+t.h?n:n.map((o,p)=>p<t.x||p>=t.x+t.w?o:!1))}function gie(e,t,n,a){if(a==null)return null;const o=e.length+n*2,p=Math.floor(t*hie),f=o/t,m=(a.width||p)*f,h=(a.height||p)*f,u=a.x==null?e.length/2-m/2:a.x*f,x=a.y==null?e.length/2-h/2:a.y*f,w=a.opacity==null?1:a.opacity;let C=null;if(a.excavate){let R=Math.floor(u),I=Math.floor(x);C={x:R,y:I,w:Math.ceil(m+u-R),h:Math.ceil(h+x-I)}}const A=a.crossOrigin;return{x:u,y:x,h,w:m,excavation:C,opacity:w,crossOrigin:A}}function vie(e,t){return t!=null?Math.max(Math.floor(t),0):e?mie:fie}function C4({value:e,level:t,minVersion:n,includeMargin:a,marginSize:o,imageSettings:p,size:f,boostLevel:m}){let h=kn.useMemo(()=>{const A=(Array.isArray(e)?e:[e]).reduce((R,I)=>(R.push(...Qs.QrSegment.makeSegments(I)),R),[]);return Qs.QrCode.encodeSegments(A,pie[t],n,void 0,void 0,m)},[e,t,n,m]);const{cells:u,margin:x,numCells:w,calculatedImageSettings:C}=kn.useMemo(()=>{let A=h.getModules();const R=vie(a,o);return{cells:A,margin:R,numCells:A.length+R*2,calculatedImageSettings:gie(A,f,R,p)}},[h,f,p,a,o]);return{qrcode:h,margin:x,cells:u,numCells:w,calculatedImageSettings:C}}var yie=(function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0})(),bie=kn.forwardRef(function(t,n){const a=t,{value:o,size:p=v4,level:f=y4,bgColor:m=b4,fgColor:h=S4,includeMargin:u=x4,minVersion:x=k4,boostLevel:w,marginSize:C,imageSettings:A}=a,R=Ty(a,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:I}=R,O=Ty(R,["style"]),D=A?.src,z=kn.useRef(null),B=kn.useRef(null),q=kn.useCallback(Ce=>{z.current=Ce,typeof n=="function"?n(Ce):n&&(n.current=Ce)},[n]),[G,ae]=kn.useState(!1),{margin:Q,cells:H,numCells:oe,calculatedImageSettings:we}=C4({value:o,level:f,minVersion:x,boostLevel:w,includeMargin:u,marginSize:C,imageSettings:A,size:p});kn.useEffect(()=>{if(z.current!=null){const Ce=z.current,re=Ce.getContext("2d");if(!re)return;let Te=H;const F=B.current,ue=we!=null&&F!==null&&F.complete&&F.naturalHeight!==0&&F.naturalWidth!==0;ue&&we.excavation!=null&&(Te=M4(H,we.excavation));const ke=window.devicePixelRatio||1;Ce.height=Ce.width=p*ke;const Ee=p/oe*ke;re.scale(Ee,Ee),re.fillStyle=m,re.fillRect(0,0,oe,oe),re.fillStyle=h,yie?re.fill(new Path2D(w4(Te,Q))):H.forEach(function(fe,L){fe.forEach(function(ee,me){ee&&re.fillRect(me+Q,L+Q,1,1)})}),we&&(re.globalAlpha=we.opacity),ue&&re.drawImage(F,we.x+Q,we.y+Q,we.w,we.h)}}),kn.useEffect(()=>{ae(!1)},[D]);const Me=_y({height:p,width:p},I);let Ae=null;return D!=null&&(Ae=kn.createElement("img",{src:D,key:D,style:{display:"none"},onLoad:()=>{ae(!0)},ref:B,crossOrigin:we?.crossOrigin})),kn.createElement(kn.Fragment,null,kn.createElement("canvas",_y({style:Me,height:p,width:p,ref:q,role:"img"},O)),Ae)});bie.displayName="QRCodeCanvas";var Sie=kn.forwardRef(function(t,n){const a=t,{value:o,size:p=v4,level:f=y4,bgColor:m=b4,fgColor:h=S4,includeMargin:u=x4,minVersion:x=k4,boostLevel:w,title:C,marginSize:A,imageSettings:R}=a,I=Ty(a,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:O,cells:D,numCells:z,calculatedImageSettings:B}=C4({value:o,level:f,minVersion:x,boostLevel:w,includeMargin:u,marginSize:A,imageSettings:R,size:p});let q=D,G=null;R!=null&&B!=null&&(B.excavation!=null&&(q=M4(D,B.excavation)),G=kn.createElement("image",{href:R.src,height:B.h,width:B.w,x:B.x+O,y:B.y+O,preserveAspectRatio:"none",opacity:B.opacity,crossOrigin:B.crossOrigin}));const ae=w4(q,O);return kn.createElement("svg",_y({height:p,width:p,viewBox:`0 0 ${z} ${z}`,ref:n,role:"img"},I),!!C&&kn.createElement("title",null,C),kn.createElement("path",{fill:m,d:`M0,0 h${z}v${z}H0z`,shapeRendering:"crispEdges"}),kn.createElement("path",{fill:h,d:ae,shapeRendering:"crispEdges"}),G)});Sie.displayName="QRCodeSVG";var rC=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,oC=e4,Bo=(e,t)=>n=>{var a;if(t?.variants==null)return oC(e,n?.class,n?.className);const{variants:o,defaultVariants:p}=t,f=Object.keys(o).map(h=>{const u=n?.[h],x=p?.[h];if(u===null)return null;const w=rC(u)||rC(x);return o[h][w]}),m=n&&Object.entries(n).reduce((h,u)=>{let[x,w]=u;return w===void 0||(h[x]=w),h},{});return oC(e,f,t==null||(a=t.compoundVariants)===null||a===void 0?void 0:a.reduce((h,u)=>{let{class:x,className:w,...C}=u;return Object.entries(C).every(A=>{let[R,I]=A;return Array.isArray(I)?I.includes({...p,...m}[R]):{...p,...m}[R]===I})?[...h,x,w]:h},[]),n?.class,n?.className)},xie=Bo("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"}}),Iy=T.forwardRef(({className:e,variant:t,size:n,...a},o)=>v.jsx("button",{ref:o,className:se(xie({variant:t,size:n}),e),...a}));Iy.displayName="Button";var kie=Bo("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 hover:bg-surface-hover"},size:{sm:"h-7 w-7",md:"h-8 w-8",lg:"h-9 w-9"}},defaultVariants:{variant:"primary",size:"sm"}}),wie=T.forwardRef(({className:e,variant:t,size:n,icon:a,...o},p)=>v.jsx("button",{ref:p,className:se(kie({variant:t,size:n}),e),...o,children:v.jsx(a,{className:"h-4 w-4"})}));wie.displayName="IconButton";var Mie=Bo("inline-flex items-center rounded-full text-xs font-medium px-2 py-0.5",{variants:{variant:{default:"bg-surface-hover text-foreground",success:"bg-success/15 text-success",warning:"bg-warning/15 text-warning",danger:"bg-danger/15 text-danger",info:"bg-info/15 text-info"},styleVariant:{solid:"",outline:"border bg-transparent"}},defaultVariants:{variant:"default",styleVariant:"solid"}}),Cie=T.forwardRef(({className:e,variant:t,style:n,...a},o)=>v.jsx("span",{ref:o,className:se(Mie({variant:t,styleVariant:n}),e),...a}));Cie.displayName="Badge";var Aie=Bo("rounded-lg p-3",{variants:{variant:{flat:"bg-surface",bordered:"bg-surface border border-border"}},defaultVariants:{variant:"bordered"}}),Eie=T.forwardRef(({className:e,variant:t,...n},a)=>v.jsx("div",{ref:a,className:se(Aie({variant:t}),e),...n}));Eie.displayName="Card";var Rie=T.forwardRef(({className:e,...t},n)=>v.jsx("label",{ref:n,className:se("text-[10px] uppercase tracking-wider text-foreground-muted font-medium",e),...t}));Rie.displayName="Label";var _ie=Bo("",{variants:{orientation:{horizontal:"h-px w-full bg-border-subtle",vertical:"w-px h-full bg-border-subtle"}},defaultVariants:{orientation:"horizontal"}}),Tie=T.forwardRef(({className:e,orientation:t,...n},a)=>v.jsx("div",{ref:a,role:"separator",className:se(_ie({orientation:t}),e),...n}));Tie.displayName="Separator";var Iie=T.forwardRef(({className:e,...t},n)=>v.jsx("div",{ref:n,className:se("animate-pulse bg-surface-hover rounded-md h-4 w-full",e),...t}));Iie.displayName="Skeleton";var sC=Bo("h-7 w-full px-2.5 text-xs bg-surface border rounded-md text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary transition-colors disabled:opacity-50 disabled:cursor-not-allowed",{variants:{state:{default:"border-border",error:"border-danger"}},defaultVariants:{state:"default"}}),Nie=T.forwardRef(({className:e,state:t,leftSlot:n,rightSlot:a,...o},p)=>n||a?v.jsxs("div",{className:"relative flex items-center w-full",children:[n&&v.jsx("div",{className:"absolute left-2.5 flex items-center pointer-events-none",children:n}),v.jsx("input",{ref:p,className:se(sC({state:t}),n?"pl-7":"",a?"pr-7":"",e),...o}),a&&v.jsx("div",{className:"absolute right-2.5 flex items-center pointer-events-none",children:a})]}):v.jsx("input",{ref:p,className:se(sC({state:t}),e),...o}));Nie.displayName="Input";var Oie=T.forwardRef(({className:e,options:t,disabled:n,...a},o)=>v.jsxs("div",{className:"relative w-full",children:[v.jsx("select",{ref:o,disabled:n,className:se("h-7 w-full px-2.5 text-xs bg-surface border border-border rounded-md text-foreground appearance-none pr-7 focus:outline-none focus:ring-1 focus:ring-primary","disabled:opacity-50 disabled:cursor-not-allowed",e),...a,children:t.map(p=>v.jsx("option",{value:p.value,children:p.label},p.value))}),v.jsx("div",{className:se("absolute right-2 top-1/2 -translate-y-1/2 pointer-events-none text-foreground-muted",n===!0?"opacity-50":""),children:v.jsx(zo,{className:"h-3.5 w-3.5"})})]}));Oie.displayName="Select";var jie=T.forwardRef(({className:e,...t},n)=>v.jsx("input",{ref:n,type:"checkbox",className:se("w-3.5 h-3.5 rounded-sm border border-border accent-primary",e),...t}));jie.displayName="Checkbox";var Pie=T.forwardRef(({className:e,checked:t,onCheckedChange:n,label:a,...o},p)=>v.jsxs("button",{ref:p,role:"switch","aria-checked":t,type:"button",onClick:()=>n(!t),className:se("inline-flex items-center gap-2",e),...o,children:[v.jsx("span",{className:se("w-8 h-4 rounded-full transition-colors",t?"bg-primary":"bg-surface-hover"),children:v.jsx("span",{className:se("block w-3.5 h-3.5 rounded-full bg-white transition-transform",t?"translate-x-4":"translate-x-0.5")})}),a&&v.jsx("span",{className:"text-xs text-foreground",children:a})]}));Pie.displayName="Switch";var A4=T.createContext(null);function Die(){const e=T.useContext(A4);if(!e)throw new Error("Dialog compound components must be used within <Dialog>");return e}function E4({children:e,open:t,onOpenChange:n}){const[a,o]=T.useState(!1),p=t??a,f=T.useId(),m=T.useCallback(h=>{n?.(h),t===void 0&&o(h)},[t,n]);return v.jsx(A4.Provider,{value:{open:p,setOpen:m,contentId:f},children:e})}var zie=Bo("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"},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"},{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"}}),f0=T.forwardRef(({className:e,width:t,placement:n,scroll:a,children:o,...p},f)=>{const{open:m,setOpen:h,contentId:u}=Die(),x=T.useRef(null),w=f??x;T.useEffect(()=>{const A=w.current;A&&(m&&!A.open&&A.showModal(),!m&&A.open&&A.close())},[m,w]);const C=A=>{A.target===A.currentTarget&&h(!1)};return v.jsx("dialog",{ref:w,id:u,className:se(zie({width:t,placement:n,scroll:a}),e),onClick:C,onClose:()=>h(!1),...p,children:o})});f0.displayName="DialogContent";function Lie({className:e,...t}){return v.jsx("div",{className:se("flex flex-col gap-1 mb-3 shrink-0",e),...t})}function qie({className:e,...t}){return v.jsx("div",{className:se("flex justify-end gap-2 mt-4 shrink-0",e),...t})}function Bie({className:e,...t}){return v.jsx("h2",{className:se("text-sm font-semibold text-foreground",e),...t})}function Uie({className:e,...t}){return v.jsx("p",{className:se("text-xs text-foreground-muted",e),...t})}T.createContext(null);T.createContext(null);T.createContext(null);T.createContext(null);var Fie=T.forwardRef(({className:e,...t},n)=>v.jsx("div",{ref:n,className:se("overflow-auto [&::-webkit-scrollbar]:w-1 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-thumb]:bg-surface-hover [&::-webkit-scrollbar-thumb]:rounded-full",e),...t}));Fie.displayName="ScrollArea";var zg={baseDelayMs:1500,maxDelayMs:15e3,maxAttempts:40};function Hie(e,t=Math.random){if(e>=zg.maxAttempts)return{kind:"exhausted",attempts:e};const n=Math.min(zg.maxDelayMs,zg.baseDelayMs*2**e);return{kind:"retry",delayMs:Math.round(n*(.8+t()*.4))}}var $ie="/adaptive-probe",Qie=2500;function R4(e){return e>=8?"high":e>=2.5?"mid":"low"}function Vie(e){const{downlinkMbps:t,...n}=e;return n}function lC(e){return R4(e)!=="low"}function cC(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}function Gie(e,t){return cC(e)??cC(t)}function Zie(e){const t=e.downlinkMbps===void 0?"none":R4(e.downlinkMbps);return[e.phase,e.viewportWidth??"-",e.viewportHeight??"-",e.devicePixelRatio??"-",t,e.prefersTier??"-",e.probeOrigin??"unreachable"].join("|")}async function Kie(e,t){const n=e.replace(/\/+$/,""),a=new AbortController,o=setTimeout(()=>a.abort(),Qie),p=t.now();try{const f=await t.fetchImpl(`${n}${$ie}`,{signal:a.signal});if(!f.ok)return null;const m=await f.arrayBuffer(),h=Math.max(1,t.now()-p);return m.byteLength<1024?null:m.byteLength*8/h/1e3}catch{return null}finally{clearTimeout(o)}}function vo(e,t){e.muted=t;const n=e.srcObject;if(n instanceof MediaStream)for(const a of n.getAudioTracks())a.enabled=!t}function Wie(){return typeof window>"u"?!1:window.matchMedia("(hover: none) and (pointer: coarse)").matches||typeof navigator<"u"&&navigator.maxTouchPoints>0||"ontouchstart"in window}function Yie(e,t,n){let f=0;for(let m=0;m<8;m++)for(let h=0;h<8;h++){const u=Math.min(t-1,Math.floor((h+.5)/8*t)),x=Math.min(n-1,Math.floor((m+.5)/8*n)),{data:w}=e.getImageData(u,x,1,1);.2126*(w[0]??0)+.7152*(w[1]??0)+.0722*(w[2]??0)>12&&f++}return f<=1}function Lg(e){const t={};if(typeof window<"u"){const n=window.devicePixelRatio||1;if(e){const a=e.getBoundingClientRect();a.width>0&&a.height>0&&(t.viewportWidth=Math.round(a.width*n),t.viewportHeight=Math.round(a.height*n))}t.viewportWidth===void 0&&(t.viewportWidth=Math.round(window.innerWidth*n),t.viewportHeight=Math.round(window.innerHeight*n)),t.devicePixelRatio=n}return t}var hc=null,Xie=3e4;function xp(e){return Gie(e,typeof window<"u"?window.location.origin:void 0)}async function gc(e){const t=xp(e);if(t===null)return;if(hc&&hc.origin===t&&Date.now()-hc.at<Xie)return hc.mbps;const n=await Kie(t,{fetchImpl:(a,o)=>fetch(a,o),now:()=>Date.now()});if(!(n===null||!Number.isFinite(n)))return hc={origin:t,mbps:n,at:Date.now()},n}function uC(e,t,n,a){const o={...e,...n!==void 0?{downlinkMbps:n}:{},...t};return a?Vie(o):o}var Jie=8e3;function _4({serverUrl:e,streamKey:t,label:n,autoPlay:a=!0,muted:o=!0,showControls:p=!0,showStats:f=!1,onPlaybackStats:m,onClientNetworkSample:h,onConnectTiming:u,className:x="",onStateChange:w,onError:C,onReconnectAttempt:A,overlay:R,createSession:I,sendAnswer:O,handleOffer:D,getIceServers:z,addIceCandidate:B,getIceCandidates:q,closeSession:G,getSessionState:ae,reoffer:Q,posterUrl:H,hintsOverride:oe,onAdaptiveHints:we,reconnectSignal:Me,onControlChannel:Ae,onVideoElement:Ce}){const re=T.useRef(null),Te=T.useRef(null),F=T.useRef(null),ue=T.useRef(new Set),ke=T.useRef(null),Ee=T.useRef(null),fe=T.useRef(0),L=T.useRef(!0),ee=T.useRef(Ae);ee.current=Ae;const me=T.useRef(Ce);me.current=Ce,T.useEffect(()=>(me.current?.(re.current),()=>me.current?.(null)),[]);const be=T.useRef(we);be.current=we;const X=T.useRef(null),xe=T.useCallback((ce,Ue,Xe)=>{const wt=be.current;if(!wt)return;const Ye={phase:ce,probeOrigin:Xe,...Ue},Nt=Zie(Ye);Nt!==X.current&&(X.current=Nt,wt(Ye))},[]),Oe=T.useRef(null),le=T.useRef(null),ye=T.useRef(0),Be=T.useRef(!1),ot=T.useRef(!1),Ve=T.useRef(async()=>{}),[Ie,bt]=T.useState("idle"),[Re,Le]=T.useState(""),[lt,st]=T.useState(o),Pt=T.useRef(lt);Pt.current=lt;const[Rt,gn]=T.useState(!1),[Ca,Wa]=T.useState(!1),$t=Wie(),[Ya,Xa]=T.useState(!0),zn=T.useRef(null),Kn=T.useRef(!1);(O||I)&&(Kn.current=!0);const We=Kn.current,_n=T.useRef(!1);D&&(_n.current=!0);const Aa=_n.current,[Ja,yi]=T.useState(!1),vn=T.useRef(null),[Wn,ge]=T.useState(null),[_e,_t]=T.useState(!1),tn=T.useCallback(()=>{const ce=re.current;if(!(!ce||ce.readyState<2||!ce.videoWidth||!ce.videoHeight))try{const Ue=document.createElement("canvas");Ue.width=ce.videoWidth,Ue.height=ce.videoHeight;const Xe=Ue.getContext("2d");if(!Xe||(Xe.drawImage(ce,0,0),Yie(Xe,Ue.width,Ue.height)))return;vn.current=Ue.toDataURL("image/jpeg",.6)}catch{}},[]),Tt=T.useCallback(ce=>{bt(ce),ce==="playing"&&yi(!0),w?.(ce)},[w]),In=T.useCallback(()=>{if(ke.current?.abort(),ke.current=null,Ee.current&&(clearTimeout(Ee.current),Ee.current=null),le.current&&(clearTimeout(le.current),le.current=null),Oe.current=null,ot.current=!1,ye.current=0,F.current&&(F.current.close(),F.current=null),G&&ue.current.size>0){for(const ce of ue.current)G(ce).catch(()=>{});ue.current.clear()}},[G]),bi=T.useCallback(()=>{ke.current?.abort(),ke.current=null,Ee.current&&(clearTimeout(Ee.current),Ee.current=null),le.current&&(clearTimeout(le.current),le.current=null),Oe.current=null,ot.current=!1,ye.current=0},[]),ei=1e3,ti=T.useCallback(ce=>{if(!ae||!Q)return;le.current&&(clearTimeout(le.current),le.current=null);const Ue=async()=>{if(L.current&&Oe.current===ce){if(!ot.current)try{const{pendingRenegotiation:Xe}=await ae(ce);if(L.current&&Oe.current===ce&&Xe&&Xe.epoch>ye.current&&!ot.current){ye.current=Xe.epoch,await Ve.current(ce,Xe.target);return}}catch{}!L.current||Oe.current!==ce||(le.current=setTimeout(()=>{Ue()},ei))}};le.current=setTimeout(()=>{Ue()},ei)},[ae,Q]),Si=T.useCallback(async(ce=!1,Ue=ce)=>{if(!L.current||!I||!O)return;const Xe=ce?F.current:null,wt=ce?new Set(ue.current):null;ce?bi():In(),Tt("connecting");const Ye=new AbortController;ke.current=Ye;try{const Nt=Ue?void 0:gc(e),He=uC(Lg(Te.current),oe,Ue?await gc(e):void 0,!Ue);xe(Ue?"probe-climb":"cold-start",He,xp(e));const{sessionId:tt,sdpOffer:Zt,iceServers:Kt}=await I(He);if(ue.current.add(tt),Nt!==void 0&&Nt.then(at=>{at===void 0||!lC(at)||!L.current||Ye.signal.aborted||Be.current||(Be.current=!0,Si(!0,!0))}),!L.current||Ye.signal.aborted){G?.(tt).catch(()=>{}),ue.current.delete(tt);return}const $e=new RTCPeerConnection({iceServers:[...Kt??[],{urls:"stun:stun.l.google.com:19302"}]});ce||(F.current=$e);const Mt=new MediaStream;let St=!1;const Ot=()=>{if(!(St||!L.current)){if(St=!0,F.current=$e,re.current&&(re.current.srcObject=Mt,vo(re.current,Pt.current),re.current.play().catch(()=>{})),Xe&&Xe!==$e)try{Xe.close()}catch{}if(wt)for(const at of wt)ue.current.delete(at),G?.(at).catch(()=>{})}};$e.ontrack=at=>{if(console.debug("[WebRTC] ontrack",at.track.kind,at.track.readyState),Mt.addTrack(at.track),ce){Ot();return}re.current&&(re.current.srcObject=Mt,vo(re.current,Pt.current),re.current.play().catch(()=>{}))},$e.oniceconnectionstatechange=()=>{if(!L.current)return;const at=$e.iceConnectionState;if(console.debug("[WebRTC] ICE state:",at),at==="connected"||at==="completed")fe.current=0,ce&&Ot(),Tt("playing"),re.current?.paused&&(console.debug("[WebRTC] video was paused at ICE connected — calling play()"),re.current.play().catch(()=>{}));else if(at==="failed"||at==="disconnected"||at==="closed"){if(ce&&!St)try{$e.close()}catch{}Tt("disconnected"),qa()}},$e.onicecandidateerror=at=>{console.debug("[WebRTC] ICE candidate error:",at)},console.debug("[WebRTC] Setting remote description (server offer)..."),await $e.setRemoteDescription({type:"offer",sdp:Zt});const Yn=await $e.createAnswer();if(await $e.setLocalDescription(Yn),console.debug("[WebRTC] Local description set, waiting for ICE gathering..."),await dC($e),!L.current)return;const nn=($e.localDescription?.sdp??"").split(`
82
82
  `).filter(at=>at.startsWith("a=candidate:")).length;console.debug("[WebRTC] Sending answer to server",{localCandidates:nn,sessionId:tt.slice(0,8)}),await O(tt,$e.localDescription?.sdp??""),console.debug("[WebRTC] Answer sent successfully");const Bt=$e,Un=()=>{const at=Bt.connectionState;if(at==="closed"||at==="failed")return;const dn=re.current;dn&&dn.readyState===0&&console.log(`[WebRTC] no video data yet (ice=${Bt.iceConnectionState})`)};setTimeout(Un,3e3),setTimeout(Un,8e3)}catch(Nt){if(!L.current)return;const He=Nt instanceof Error?Nt.message:String(Nt);Le(He),Tt("error"),C?.(He),qa()}},[e,t,I,O,In,bi,G,Tt,C,oe,xe]),Im=T.useCallback(async()=>{if(L.current){In(),Tt("connecting");try{const ce=new RTCPeerConnection({iceServers:[{urls:"stun:stun.l.google.com:19302"}]});F.current=ce,ce.addTransceiver("video",{direction:"recvonly"}),ce.addTransceiver("audio",{direction:"recvonly"});const Ue=new MediaStream;ce.ontrack=He=>{Ue.addTrack(He.track),re.current&&(re.current.srcObject=Ue,vo(re.current,Pt.current),re.current.play().catch(()=>{}))},ce.oniceconnectionstatechange=()=>{if(!L.current)return;const He=ce.iceConnectionState;He==="connected"||He==="completed"?(fe.current=0,Tt("playing"),re.current?.paused&&re.current.play().catch(()=>{})):(He==="failed"||He==="disconnected"||He==="closed")&&(Tt("disconnected"),qa())};const Xe=await ce.createOffer();if(await ce.setLocalDescription(Xe),await dC(ce),!L.current)return;const wt=`${e}/api/webrtc?src=${encodeURIComponent(t)}`,Ye=await fetch(wt,{method:"POST",headers:{"Content-Type":"application/sdp"},body:ce.localDescription?.sdp??""});if(!Ye.ok)throw new Error(`WHEP ${Ye.status}: ${Ye.statusText}`);const Nt=await Ye.text();await ce.setRemoteDescription({type:"answer",sdp:Nt})}catch(ce){if(!L.current)return;const Ue=ce instanceof Error?ce.message:String(ce);Le(Ue),Tt("error"),C?.(Ue),qa()}}},[e,t,In,Tt,C]),Uo=T.useCallback(async(ce=!1,Ue=ce)=>{if(!L.current||!D)return;const Xe=ce?F.current:null,wt=ce?new Set(ue.current):null;ce?bi():In(),Tt("connecting");const Ye=new AbortController;ke.current=Ye;const Nt=performance.now(),He=()=>Math.round(performance.now()-Nt),tt={};try{const Zt=Ue?void 0:gc(e),Kt=await z?.();if(tt.iceServersMs=He(),!L.current||Ye.signal.aborted)return;const $e=new RTCPeerConnection({iceServers:[...Kt??[],{urls:"stun:stun.l.google.com:19302"}]});ce||(F.current=$e);const Mt=new MediaStream;let St=!1;const Ot=()=>{if(!(St||!L.current)){if(St=!0,F.current=$e,re.current&&(re.current.srcObject=Mt,vo(re.current,Pt.current),re.current.play().catch(()=>{})),Xe&&Xe!==$e)try{Xe.close()}catch{}if(wt)for(const ut of wt)ue.current.delete(ut),G?.(ut).catch(()=>{})}};$e.ontrack=ut=>{if(tt.firstTrackMs===void 0&&(tt.firstTrackMs=He()),console.debug("[WebRTC] ontrack (client-offer)",ut.track.kind,ut.track.readyState),Mt.addTrack(ut.track),ce){Ot();return}re.current&&(re.current.srcObject=Mt,vo(re.current,Pt.current),re.current.play().catch(()=>{}))};let Yn=!1;$e.oniceconnectionstatechange=()=>{if(!L.current)return;const ut=$e.iceConnectionState;if(console.debug("[WebRTC] ICE state (client-offer):",ut),ut==="connected"||ut==="completed"){if(!Yn){Yn=!0,tt.iceConnectedMs=He(),console.info("[WebRTC timing] client-offer connected",{streamKey:t,...tt}),u?.({...tt});const Jn=re.current;Jn&&"requestVideoFrameCallback"in Jn&&(Jn.requestVideoFrameCallback(()=>{tt.firstFrameMs=He(),console.info("[WebRTC timing] first decoded frame",{streamKey:t,firstFrameMs:tt.firstFrameMs}),u?.({...tt})}),setTimeout(()=>{L.current&&tt.firstFrameMs===void 0&&(console.warn("[WebRTC timing] NO decoded frame (stalled)",{streamKey:t,sinceIceConnectedMs:He()-(tt.iceConnectedMs??0),iceConnectedMs:tt.iceConnectedMs,firstTrackMs:tt.firstTrackMs}),Fo.current("no decoded frame after connect"),qa())},Jie))}fe.current=0,ce&&Ot(),Tt("playing"),re.current?.paused&&re.current.play().catch(()=>{})}else if(ut==="failed"||ut==="disconnected"||ut==="closed"){if(ce&&!St)try{$e.close()}catch{}Tt("disconnected"),qa()}};let nn=null;const Bt=[];if($e.onicecandidate=ut=>{if(!ut.candidate)return;const Jn=ut.candidate.toJSON();nn&&B?B(nn,Jn).catch(()=>{}):Bt.push(Jn)},$e.addTransceiver("video",{direction:"recvonly"}),$e.addTransceiver("audio",{direction:"recvonly"}),ee.current){const ut=$e.createDataChannel("camstack-control");ee.current(ut)}const Un=await $e.createOffer();if(tt.offerCreatedMs=He(),await $e.setLocalDescription(Un),tt.localSetMs=He(),!L.current||Ye.signal.aborted)return;const at=Ue?await gc(e):void 0,dn=uC(Lg(Te.current),oe,at,!Ue);xe(Ue?"probe-climb":"cold-start",dn,xp(e));const Ea=He(),{sessionId:Xn,sdpAnswer:Je}=await D($e.localDescription?.sdp??Un.sdp??"",void 0,dn);if(tt.signalingRttMs=He()-Ea,nn=Xn,ue.current.add(Xn),Zt!==void 0&&Zt.then(ut=>{ut===void 0||!lC(ut)||!L.current||Ye.signal.aborted||Be.current||(Be.current=!0,Uo(!0,!0))}),Oe.current=Xn,!L.current||Ye.signal.aborted){G?.(Xn).catch(()=>{}),ue.current.delete(Xn);return}if(B)for(const ut of Bt)B(Xn,ut).catch(()=>{});if(Bt.length=0,await $e.setRemoteDescription({type:"answer",sdp:Je}),tt.answerSetMs=He(),console.debug("[WebRTC] Client-offer answer set (trickle)",{sessionId:Xn.slice(0,8)}),q){const ut=new Set,Jn=Date.now(),Wr=async()=>{if(!(!L.current||Ye.signal.aborted)&&!($e.connectionState==="closed"||$e.signalingState==="closed")){try{const{candidates:ni,done:Qo}=await q(Xn);for(const Mi of ni){const Yr=Mi.candidate??"";Yr&&!ut.has(Yr)&&(ut.add(Yr),$e.addIceCandidate(new RTCIceCandidate(Mi)).catch(()=>{}))}const rr=$e.iceConnectionState;if(Qo||Date.now()-Jn>1e4||rr==="connected"||rr==="completed")return}catch{}setTimeout(()=>{Wr()},200)}};Wr()}ti(Xn)}catch(Zt){if(!L.current)return;const Kt=Zt instanceof Error?Zt.message:String(Zt);Le(Kt),Tt("error"),C?.(Kt),qa()}},[e,D,z,B,q,G,In,bi,Tt,C,ti,oe,xe]);Ve.current=T.useCallback(async(ce,Ue)=>{const Xe=Q;if(!L.current||!Xe)return;const wt=F.current;ot.current=!0;try{let Ye=function(){if(Zt||!L.current){Ot();return}Zt=!0,F.current=He,re.current&&(re.current.srcObject=tt,re.current.play().catch(()=>{})),wt&&wt!==He&&wt.close(),Ot()};const Nt=await z?.();if(!L.current)return;const He=new RTCPeerConnection({iceServers:[...Nt??[],{urls:"stun:stun.l.google.com:19302"}]}),tt=new MediaStream;let Zt=!1,Kt=!1,$e=null,Mt,St;const Ot=()=>{St!==void 0&&(clearTimeout(St),St=void 0);const Je=$e;if($e=null,!!Je){Mt!==void 0&&typeof Je.cancelVideoFrameCallback=="function"&&Je.cancelVideoFrameCallback(Mt),Je.removeEventListener("loadeddata",Ye);try{Je.srcObject=null}catch{}Je.remove()}},Yn=()=>{if(Kt||Zt||!L.current)return;if(Kt=!0,typeof document>"u"){Ye();return}const Je=document.createElement("video");Je.muted=!0,Je.playsInline=!0,Je.autoplay=!0,Je.style.cssText="position:absolute;left:-9999px;top:0;width:1px;height:1px;opacity:0;pointer-events:none;",Je.srcObject=tt,$e=Je,(Te.current??document.body).appendChild(Je),Je.play().catch(()=>{}),typeof Je.requestVideoFrameCallback=="function"&&(Mt=Je.requestVideoFrameCallback(()=>Ye())),Je.addEventListener("loadeddata",Ye,{once:!0}),St=setTimeout(()=>Ye(),1800)};He.ontrack=Je=>{console.debug("[WebRTC] ontrack (reoffer)",Je.track.kind,Je.track.readyState),tt.addTrack(Je.track),Yn()},He.oniceconnectionstatechange=()=>{if(!L.current)return;const Je=He.iceConnectionState;console.debug("[WebRTC] ICE state (reoffer):",Je),Je==="connected"||Je==="completed"?(fe.current=0,Yn(),Tt("playing"),re.current?.paused&&re.current.play().catch(()=>{})):(Je==="failed"||Je==="closed")&&(Ot(),!Zt&&Je==="failed"&&He.close(),Tt("disconnected"),qa())};let nn=null;const Bt=[];if(He.onicecandidate=Je=>{if(!Je.candidate)return;const ut=Je.candidate.toJSON();nn&&B?B(nn,ut).catch(()=>{}):Bt.push(ut)},He.addTransceiver("video",{direction:"recvonly"}),He.addTransceiver("audio",{direction:"recvonly"}),ee.current){const Je=He.createDataChannel("camstack-control");ee.current(Je)}const Un=await He.createOffer();if(await He.setLocalDescription(Un),!L.current){He.close();return}const at=await gc(e),dn={...Lg(Te.current),...at!==void 0?{downlinkMbps:at}:{},...oe};xe("renegotiate",dn,xp(e));const{sessionId:Ea,sdpAnswer:Xn}=await Xe(ce,He.localDescription?.sdp??Un.sdp??"",Ue,dn);if(!L.current){He.close();return}if(nn=Ea,ue.current.add(Ea),Oe.current=Ea,B)for(const Je of Bt)B(Ea,Je).catch(()=>{});if(Bt.length=0,await He.setRemoteDescription({type:"answer",sdp:Xn}),q){const Je=new Set,ut=Date.now(),Jn=async()=>{if(L.current&&!(He.connectionState==="closed"||He.signalingState==="closed")){try{const{candidates:Wr,done:ni}=await q(Ea);for(const rr of Wr){const Mi=rr.candidate??"";Mi&&!Je.has(Mi)&&(Je.add(Mi),He.addIceCandidate(new RTCIceCandidate(rr)).catch(()=>{}))}const Qo=He.iceConnectionState;if(ni||Date.now()-ut>1e4||Qo==="connected"||Qo==="completed")return}catch{}setTimeout(()=>{Jn()},200)}};Jn()}ti(Ea)}catch(Ye){console.debug("[WebRTC] reoffer failed; keeping last frame, re-arming poll",Ye instanceof Error?Ye.message:String(Ye)),ti(ce)}finally{ot.current=!1}},[e,Q,z,B,q,Tt,ti,oe,xe]);const La=Aa?Uo:We?Si:Im,tr=T.useRef(()=>{}),gu=T.useRef(A);gu.current=A;const Fo=T.useRef(()=>{});Fo.current=ce=>{console.warn("[WebRTC] hard error",{streamKey:t,msg:ce}),Le(ce),C?.(ce),Tt("error")},tr.current=La;const qa=T.useCallback(()=>{if(!L.current)return;const ce=fe.current,Ue=Hie(ce);if(gu.current?.(Ue),Ue.kind==="exhausted"){Fo.current(`reconnect attempts exhausted (${Ue.attempts})`);return}fe.current+=1,Ee.current=setTimeout(()=>{L.current&&tr.current()},Ue.delayMs)},[]);T.useEffect(()=>(L.current=!0,fe.current=0,a&&La(),()=>{L.current=!1,In()}),[]);const ml=T.useRef(!1);T.useEffect(()=>{if(a){if(Aa){if(!D)return}else if(We){if(!I||!O)return}else return;ml.current||F.current||(ml.current=!0,La())}},[a,Aa,We,D,I,O,La]);const Ho=()=>{fe.current=0,La()},$o=()=>{if(fe.current=0,F.current&&Aa){Uo(!0);return}if(F.current&&We){Si(!0);return}La()},fl=T.useRef(e),hl=T.useRef(t);T.useEffect(()=>{const ce=fl.current!==e,Ue=hl.current!==t;if(fl.current=e,hl.current=t,!(!ce&&!Ue)&&L.current){if(fe.current=0,Be.current=!1,ce){In(),La();return}$o()}},[e,t]);const Ba=T.useRef(Me);T.useEffect(()=>{Ba.current!==Me&&(Ba.current=Me,L.current&&$o())},[Me]);const Cn=()=>{if(re.current){const ce=!re.current.muted;vo(re.current,ce),st(ce)}},Ln=async()=>{if(Te.current)try{if(document.fullscreenElement){await document.exitFullscreen();return}if(Te.current.requestFullscreen){await Te.current.requestFullscreen();return}const ce=re.current;ce?.webkitEnterFullscreen&&ce.webkitEnterFullscreen()}catch(ce){console.warn(`Fullscreen toggle failed: ${ce instanceof Error?ce.message:ce}`)}},nr=async()=>{const ce=re.current;if(ce)try{if(typeof ce.webkitSetPresentationMode=="function"){ce.webkitSetPresentationMode(ce.webkitPresentationMode==="picture-in-picture"?"inline":"picture-in-picture");return}document.pictureInPictureElement?await document.exitPictureInPicture():await ce.requestPictureInPicture()}catch(Ue){console.warn(`PiP toggle failed: ${Ue instanceof Error?Ue.message:String(Ue)}`)}},gl=()=>{if(!re.current)return;const ce=document.createElement("canvas");ce.width=re.current.videoWidth||1280,ce.height=re.current.videoHeight||720;const Ue=ce.getContext("2d");if(!Ue)return;Ue.drawImage(re.current,0,0);const Xe=document.createElement("a");Xe.download=`${t.replace(/[/:]/g,"-")}-${Date.now()}.jpg`,Xe.href=ce.toDataURL("image/jpeg",.92),Xe.click()};T.useEffect(()=>{const ce=()=>gn(!!document.fullscreenElement);document.addEventListener("fullscreenchange",ce);const Ue=re.current;return Ue?.addEventListener("webkitbeginfullscreen",ce),Ue?.addEventListener("webkitendfullscreen",ce),()=>{document.removeEventListener("fullscreenchange",ce),Ue?.removeEventListener("webkitbeginfullscreen",ce),Ue?.removeEventListener("webkitendfullscreen",ce)}},[]),T.useEffect(()=>{const ce=re.current,Ue=typeof document<"u"&&document.pictureInPictureEnabled===!0,Xe=ce!==null&&typeof ce.webkitSetPresentationMode=="function";Wa(Ue||Xe)},[]);const[vu,yu]=T.useState(""),xi=T.useRef(null);T.useEffect(()=>{if(!f){yu(""),xi.current=null;return}const ce=async()=>{const Xe=F.current;if(Xe)try{const wt=await Xe.getStats();let Ye=0,Nt=0,He=0,tt=0,Zt=0,Kt=0;wt.forEach(St=>{const Ot=St;Ot.type==="inbound-rtp"&&(Ot.kind??Ot.mediaType)==="video"?(Ye=Ot.bytesReceived??0,Nt=Ot.timestamp,He=Ot.framesPerSecond??0,tt=Ot.frameWidth??0,Zt=Ot.frameHeight??0):Ot.type==="candidate-pair"&&Ot.nominated&&typeof Ot.currentRoundTripTime=="number"&&(Kt=Ot.currentRoundTripTime)});let $e=0;xi.current&&Nt>xi.current.ts&&($e=Math.round((Ye-xi.current.bytes)*8/(Nt-xi.current.ts))),xi.current={bytes:Ye,ts:Nt};const Mt=[];tt&&Zt&&Mt.push(`${tt}×${Zt}`),He&&Mt.push(`${Math.round(He)}fps`),$e>0&&Mt.push(`${$e} kbps`),Kt&&Mt.push(`${Math.round(Kt*1e3)}ms`),yu(Mt.join(" · "))}catch{}};ce();const Ue=setInterval(()=>{ce()},1e3);return()=>clearInterval(Ue)},[f]);const ki=T.useRef(null);T.useEffect(()=>{if(!h){ki.current=null;return}const ce=async()=>{const Xe=F.current;if(Xe)try{const wt=await Xe.getStats();let Ye=0,Nt=0,He=0,tt=0,Zt=0,Kt=0;wt.forEach(nn=>{const Bt=nn;Bt.type==="inbound-rtp"&&(Bt.kind??Bt.mediaType)==="video"?(Ye=Bt.packetsLost??0,Nt=Bt.packetsReceived??0,He=Bt.bytesReceived??0,tt=Bt.timestamp,Zt=Bt.jitter??0):Bt.type==="candidate-pair"&&Bt.nominated&&typeof Bt.currentRoundTripTime=="number"&&(Kt=Bt.currentRoundTripTime)});const $e=ki.current;if(ki.current={lost:Ye,recv:Nt,bytes:He,ts:tt},!$e||tt<=$e.ts)return;const Mt=Math.max(0,Ye-$e.lost),St=Mt+Math.max(0,Nt-$e.recv),Ot=St>0?Math.min(100,Mt/St*100):0,Yn=Math.max(0,Math.round((He-$e.bytes)*8/(tt-$e.ts)));h({rttMs:Math.round(Kt*1e3),jitterMs:Math.round(Zt*1e3),estimatedBandwidthKbps:Yn,packetLossPercent:Ot})}catch{}},Ue=setInterval(()=>{ce()},2e3);return()=>clearInterval(Ue)},[h]);const Kr=T.useRef(null);T.useEffect(()=>{if(!m){Kr.current=null;return}const ce=async()=>{const Xe=F.current,wt=re.current;if(Xe)try{const Ye=await Xe.getStats();let Nt=0,He=0,tt=0,Zt=0,Kt=0,$e=0,Mt=0,St=0;Ye.forEach(Un=>{const at=Un;at.type==="inbound-rtp"&&(at.kind??at.mediaType)==="video"&&(Nt=at.framesReceived??0,He=at.framesDecoded??0,tt=at.framesDropped??0,Zt=at.framesPerSecond??0,Kt=at.freezeCount??0,$e=at.totalFreezesDuration??0,Mt=at.jitterBufferDelay??0,St=at.jitterBufferEmittedCount??0)});const Ot=wt?.currentTime??0,Yn=Date.now(),nn=Kr.current,Bt=St>0?Math.round(Mt/St*1e3):0;nn&&m({dRecv:Nt-nn.recv,dDec:He-nn.dec,dDrop:tt-nn.drop,fps:Math.round(Zt),dFreeze:Kt-nn.freeze,freezeTotalMs:Math.round($e*1e3),avgJitterMs:Bt,dCtMs:Math.round((Ot-nn.ct)*1e3),dtMs:Yn-nn.ts,readyState:wt?.readyState??-1}),Kr.current={recv:Nt,dec:He,drop:tt,freeze:Kt,ct:Ot,ts:Yn}}catch{}};ce();const Ue=setInterval(()=>{ce()},5e3);return()=>clearInterval(Ue)},[m]),T.useEffect(()=>{st(o);const ce=re.current;ce&&(vo(ce,o),o||ce.play().catch(()=>{}))},[o]);const wi=()=>{$t||(Xa(!0),zn.current&&clearTimeout(zn.current),zn.current=setTimeout(()=>Xa(!1),3e3))},ar=()=>{Xa(ce=>!ce),zn.current&&clearTimeout(zn.current)};T.useEffect(()=>{if(Ie==="playing"){tn();const ce=setInterval(tn,2e3);return()=>clearInterval(ce)}Ja&&vn.current&&ge(vn.current)},[Ie,Ja,tn]),T.useEffect(()=>{if(Ie!=="playing"){_t(!1);return}const ce=re.current;if(!ce)return;let Ue=!1;const Xe=()=>{Ue||_t(!0)};let wt;typeof ce.requestVideoFrameCallback=="function"&&(wt=ce.requestVideoFrameCallback(()=>Xe())),ce.addEventListener("loadeddata",Xe,{once:!0});const Ye=setTimeout(Xe,12e3);return()=>{Ue=!0,clearTimeout(Ye),wt!==void 0&&typeof ce.cancelVideoFrameCallback=="function"&&ce.cancelVideoFrameCallback(wt),ce.removeEventListener("loadeddata",Xe)}},[Ie]);const da=Ja&&Wn?Wn:H??null,ir=!_e&&da!==null;return v.jsxs("div",{ref:Te,className:`relative isolate bg-black overflow-hidden group ${x}`,onMouseMove:wi,onMouseEnter:wi,onTouchStart:ar,children:[v.jsx("video",{ref:re,autoPlay:a,muted:lt,playsInline:!0,className:"w-full h-full object-contain relative z-0"}),ir&&da&&v.jsx("img",{src:da,alt:"",className:"absolute inset-0 w-full h-full object-contain z-[5] transform-gpu pointer-events-none"}),n&&Ie==="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:n}),f&&vu&&v.jsx("div",{className:"absolute top-2 right-2 z-10 transform-gpu px-2 py-0.5 rounded bg-black/60 text-[10px] text-white font-mono",children:vu}),R,p&&!da&&Ie==="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…"})]}),p&&!da&&(Ie==="error"||Ie==="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:Ie==="error"?Re||"Connection failed":"Disconnected"}),v.jsx("button",{onClick:Ho,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"})]}),p&&da&&(Ie==="connecting"||Ie==="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]"})})}),p&&da&&Ie==="error"&&v.jsx("button",{onClick:Ho,title:Re||"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"})]})}),p&&Ie!=="idle"&&Ie!=="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 ${$t||Ya?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none"}`,children:[v.jsx("div",{className:"flex items-center gap-1",children:v.jsx(Gd,{onClick:Cn,title:lt?"Unmute":"Mute",children:lt?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(Gd,{onClick:gl,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"})]})}),Ca&&v.jsx(Gd,{onClick:nr,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(Gd,{onClick:Ln,title:Rt?"Exit fullscreen":"Fullscreen",children:Rt?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 Gd({onClick:e,title:t,children:n}){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:n})}async function dC(e){if(e.iceGatheringState!=="complete")return new Promise(t=>{let n=!1,a;const o=()=>{n||(n=!0,a&&clearInterval(a),e.removeEventListener("icegatheringstatechange",p),t())},p=()=>{e.iceGatheringState==="complete"&&o()};e.addEventListener("icegatheringstatechange",p);const f=Date.now();a=setInterval(()=>{const m=e.localDescription?.sdp??"";/ typ host/.test(m)&&Date.now()-f>=600&&o()},100),setTimeout(o,2500)})}var qg=["day","ir"],ere={day:"Daylight",ir:"Night (IR)",night:"Night",dawn:"Dawn",dusk:"Dusk"};function kp(e){return ere[e]??e}function ihe(e){const t=new Set(e.coveredConditions),n=qg.map(f=>`${kp(f)} ${t.has(f)?"✓":"✗"}`),a=[...t].filter(f=>!qg.some(m=>m===f));for(const f of a)n.push(`${kp(f)} ✓`);const o=qg.filter(f=>!t.has(f));if(o.length===0)return n.join(" · ");if(t.size===0)return`${n.join(" · ")} — nothing captured yet, so this scene is not watching.`;const p=o.map(f=>kp(f).toLowerCase()).join(" and ");return e.onUncoveredCondition==="judge-anyway"?`${n.join(" · ")} — ${p} judged against the references you do have.`:`${n.join(" · ")} — optional; checks in ${p} are skipped.`}function tre(e){if(e.suspendedCondition===null)return null;const t=kp(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 nre={"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 rhe(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?nre[e.unavailable]:"can’t tell right now.";const n=e.verdict==="diverged"?e.divergedAt:e.armedAt,a=n!==null?` for ${ire(Math.max(0,t-n))}`:"";if(e.latched)return e.verdict==="diverged"?`CHANGED${a} — press Reset when you have dealt with it.`:`Back to normal, but still flagged as changed${a}. Press Reset to clear it.`;const o=tre(e);return o!==null?o:e.verdict==="diverged"?`CHANGED${a}`:`Normal${a}`}function ohe(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 are=.4;function she(e){return e.width*e.height>are}function ire(e){const t=Math.floor(e/1e3);if(t<60)return`${t}s`;const n=Math.floor(t/60);if(n<60)return`${n}m`;const a=Math.floor(n/60);return a<48?`${a}h`:`${Math.floor(a/24)}d`}var lhe="text-[10px] text-foreground-subtle",rre={face:"#a855f7",plate:"#ec4899"};Object.freeze({...Object.fromEntries(Object.values(Cb).filter(e=>e.category==="detection"||e.kind==="motion").map(e=>[e.kind,e.color])),...rre});var ore=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()}},T4=class{constructor(e){this.generateIdentifier=e,this.kv=new ore}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)}},sre=class extends T4{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 lre(e){if("values"in Object)return Object.values(e);const t=[];for(const n in e)e.hasOwnProperty(n)&&t.push(e[n]);return t}function cre(e,t){const n=lre(e);if("find"in n)return n.find(t);const a=n;for(let o=0;o<a.length;o++){const p=a[o];if(t(p))return p}}function ll(e,t){Object.entries(e).forEach(([n,a])=>t(a,n))}function wp(e,t){return e.indexOf(t)!==-1}function pC(e,t){for(let n=0;n<e.length;n++){const a=e[n];if(t(a))return a}}var ure=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return cre(this.transfomers,t=>t.isApplicable(e))}findByName(e){return this.transfomers[e]}},dre=e=>Object.prototype.toString.call(e).slice(8,-1),I4=e=>typeof e>"u",pre=e=>e===null,Zc=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,Ny=e=>Zc(e)&&Object.keys(e).length===0,Fr=e=>Array.isArray(e),mre=e=>typeof e=="string",fre=e=>typeof e=="number"&&!isNaN(e),hre=e=>typeof e=="boolean",gre=e=>e instanceof RegExp,Kc=e=>e instanceof Map,Wc=e=>e instanceof Set,N4=e=>dre(e)==="Symbol",vre=e=>e instanceof Date&&!isNaN(e.valueOf()),O4=e=>e instanceof Error,mC=e=>typeof e=="number"&&isNaN(e),yre=e=>hre(e)||pre(e)||I4(e)||fre(e)||mre(e)||N4(e),bre=e=>typeof e=="bigint",Sre=e=>e===1/0||e===-1/0,xre=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),kre=e=>e instanceof URL,Oy=e=>e.replace(/\\/g,"\\\\").replace(/\./g,"\\."),Bg=e=>e.map(String).map(Oy).join("."),_c=(e,t)=>{const n=[];let a="";for(let p=0;p<e.length;p++){let f=e.charAt(p);if(!t&&f==="\\"){const m=e.charAt(p+1);if(m==="\\"){a+="\\",p++;continue}else if(m!==".")throw Error("invalid path")}if(f==="\\"&&e.charAt(p+1)==="."){a+=".",p++;continue}if(f==="."){n.push(a),a="";continue}a+=f}const o=a;return n.push(o),n};function ui(e,t,n,a){return{isApplicable:e,annotation:t,transform:n,untransform:a}}var j4=[ui(I4,"undefined",()=>null,()=>{}),ui(bre,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):(console.error("Please add a BigInt polyfill."),e)),ui(vre,"Date",e=>e.toISOString(),e=>new Date(e)),ui(O4,"Error",(e,t)=>{const n={name:e.name,message:e.message};return"cause"in e&&(n.cause=e.cause),t.allowedErrorProps.forEach(a=>{n[a]=e[a]}),n},(e,t)=>{const n=new Error(e.message,{cause:e.cause});return n.name=e.name,n.stack=e.stack,t.allowedErrorProps.forEach(a=>{n[a]=e[a]}),n}),ui(gre,"regexp",e=>""+e,e=>{const t=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(t,n)}),ui(Wc,"set",e=>[...e.values()],e=>new Set(e)),ui(Kc,"map",e=>[...e.entries()],e=>new Map(e)),ui(e=>mC(e)||Sre(e),"number",e=>mC(e)?"NaN":e>0?"Infinity":"-Infinity",Number),ui(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),ui(kre,"URL",e=>e.toString(),e=>new URL(e))];function Em(e,t,n,a){return{isApplicable:e,annotation:t,transform:n,untransform:a}}var P4=Em((e,t)=>N4(e)?!!t.symbolRegistry.getIdentifier(e):!1,(e,t)=>["symbol",t.symbolRegistry.getIdentifier(e)],e=>e.description,(e,t,n)=>{const a=n.symbolRegistry.getValue(t[1]);if(!a)throw new Error("Trying to deserialize unknown symbol");return a}),wre=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,t)=>(e[t.name]=t,e),{}),D4=Em(xre,e=>["typed-array",e.constructor.name],e=>[...e],(e,t)=>{const n=wre[t[1]];if(!n)throw new Error("Trying to deserialize unknown typed array");return new n(e)});function z4(e,t){return e?.constructor?!!t.classRegistry.getIdentifier(e.constructor):!1}var L4=Em(z4,(e,t)=>["class",t.classRegistry.getIdentifier(e.constructor)],(e,t)=>{const n=t.classRegistry.getAllowedProps(e.constructor);if(!n)return{...e};const a={};return n.forEach(o=>{a[o]=e[o]}),a},(e,t,n)=>{const a=n.classRegistry.getValue(t[1]);if(!a)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(a.prototype),e)}),q4=Em((e,t)=>!!t.customTransformerRegistry.findApplicable(e),(e,t)=>["custom",t.customTransformerRegistry.findApplicable(e).name],(e,t)=>t.customTransformerRegistry.findApplicable(e).serialize(e),(e,t,n)=>{const a=n.customTransformerRegistry.findByName(t[1]);if(!a)throw new Error("Trying to deserialize unknown custom value");return a.deserialize(e)}),Mre=[L4,P4,q4,D4],fC=(e,t)=>{const n=pC(Mre,o=>o.isApplicable(e,t));if(n)return{value:n.transform(e,t),type:n.annotation(e,t)};const a=pC(j4,o=>o.isApplicable(e,t));if(a)return{value:a.transform(e,t),type:a.annotation}},B4={};j4.forEach(e=>{B4[e.annotation]=e});var Cre=(e,t,n)=>{if(Fr(t))switch(t[0]){case"symbol":return P4.untransform(e,t,n);case"class":return L4.untransform(e,t,n);case"custom":return q4.untransform(e,t,n);case"typed-array":return D4.untransform(e,t,n);default:throw new Error("Unknown transformation: "+t)}else{const a=B4[t];if(!a)throw new Error("Unknown transformation: "+t);return a.untransform(e,n)}},Vs=(e,t)=>{if(t>e.size)throw new Error("index out of bounds");const n=e.keys();for(;t>0;)n.next(),t--;return n.next().value};function U4(e){if(wp(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(wp(e,"prototype"))throw new Error("prototype is not allowed as a property");if(wp(e,"constructor"))throw new Error("constructor is not allowed as a property")}var Are=(e,t)=>{U4(t);for(let n=0;n<t.length;n++){const a=t[n];if(Wc(e))e=Vs(e,+a);else if(Kc(e)){const o=+a,p=+t[++n]==0?"key":"value",f=Vs(e,o);switch(p){case"key":e=f;break;case"value":e=e.get(f);break}}else e=e[a]}return e},jy=(e,t,n)=>{if(U4(t),t.length===0)return n(e);let a=e;for(let p=0;p<t.length-1;p++){const f=t[p];if(Fr(a)){const m=+f;a=a[m]}else if(Zc(a))a=a[f];else if(Wc(a)){const m=+f;a=Vs(a,m)}else if(Kc(a)){if(p===t.length-2)break;const m=+f,h=+t[++p]==0?"key":"value",u=Vs(a,m);switch(h){case"key":a=u;break;case"value":a=a.get(u);break}}}const o=t[t.length-1];if(Fr(a)?a[+o]=n(a[+o]):Zc(a)&&(a[o]=n(a[o])),Wc(a)){const p=Vs(a,+o),f=n(p);p!==f&&(a.delete(p),a.add(f))}if(Kc(a)){const p=+t[t.length-2],f=Vs(a,p);switch(+o==0?"key":"value"){case"key":{const m=n(f);a.set(m,a.get(f)),m!==f&&a.delete(f);break}case"value":a.set(f,n(a.get(f)));break}}return e},F4=e=>e<1;function Py(e,t,n,a=[]){if(!e)return;const o=F4(n);if(!Fr(e)){ll(e,(m,h)=>Py(m,t,n,[...a,..._c(h,o)]));return}const[p,f]=e;f&&ll(f,(m,h)=>{Py(m,t,n,[...a,..._c(h,o)])}),t(p,a)}function Ere(e,t,n,a){return Py(t,(o,p)=>{e=jy(e,p,f=>Cre(f,o,a))},n),e}function Rre(e,t,n){const a=F4(n);function o(p,f){const m=Are(e,_c(f,a));p.map(h=>_c(h,a)).forEach(h=>{e=jy(e,h,()=>m)})}if(Fr(t)){const[p,f]=t;p.forEach(m=>{e=jy(e,_c(m,a),()=>e)}),f&&ll(f,o)}else ll(t,o);return e}var _re=(e,t)=>Zc(e)||Fr(e)||Kc(e)||Wc(e)||O4(e)||z4(e,t);function Tre(e,t,n){const a=n.get(e);a?a.push(t):n.set(e,[t])}function Ire(e,t){const n={};let a;return e.forEach(o=>{if(o.length<=1)return;t||(o=o.map(m=>m.map(String)).sort((m,h)=>m.length-h.length));const[p,...f]=o;p.length===0?a=f.map(Bg):n[Bg(p)]=f.map(Bg)}),a?Ny(n)?[a]:[a,n]:Ny(n)?void 0:n}var H4=(e,t,n,a,o=[],p=[],f=new Map)=>{const m=yre(e);if(!m){Tre(e,o,t);const A=f.get(e);if(A)return a?{transformedValue:null}:A}if(!_re(e,n)){const A=fC(e,n),R=A?{transformedValue:A.value,annotations:[A.type]}:{transformedValue:e};return m||f.set(e,R),R}if(wp(p,e))return{transformedValue:null};const h=fC(e,n),u=h?.value??e,x=Fr(u)?[]:{},w={};ll(u,(A,R)=>{if(R==="__proto__"||R==="constructor"||R==="prototype")throw new Error(`Detected property ${R}. This is a prototype pollution risk, please remove it from your object.`);const I=H4(A,t,n,a,[...o,R],[...p,e],f);x[R]=I.transformedValue,Fr(I.annotations)?w[Oy(R)]=I.annotations:Zc(I.annotations)&&ll(I.annotations,(O,D)=>{w[Oy(R)+"."+D]=O})});const C=Ny(w)?{transformedValue:x,annotations:h?[h.type]:void 0}:{transformedValue:x,annotations:h?[h.type,w]:w};return m||f.set(e,C),C};function $4(e){return Object.prototype.toString.call(e).slice(8,-1)}function hC(e){return $4(e)==="Array"}function Nre(e){if($4(e)!=="Object")return!1;const t=Object.getPrototypeOf(e);return!!t&&t.constructor===Object&&t===Object.prototype}function Ore(e,t,n,a,o){const p={}.propertyIsEnumerable.call(a,t)?"enumerable":"nonenumerable";p==="enumerable"&&(e[t]=n),o&&p==="nonenumerable"&&Object.defineProperty(e,t,{value:n,enumerable:!1,writable:!0,configurable:!0})}function Dy(e,t={}){if(hC(e))return e.map(o=>Dy(o,t));if(!Nre(e))return e;const n=Object.getOwnPropertyNames(e),a=Object.getOwnPropertySymbols(e);return[...n,...a].reduce((o,p)=>{if(p==="__proto__"||hC(t.props)&&!t.props.includes(p))return o;const f=e[p];return Ore(o,p,Dy(f,t),e,t.nonenumerable),o},{})}var Gt=class{constructor({dedupe:e=!1}={}){this.classRegistry=new sre,this.symbolRegistry=new T4(t=>t.description??""),this.customTransformerRegistry=new ure,this.allowedErrorProps=[],this.dedupe=e}serialize(e){const t=new Map,n=H4(e,t,this,this.dedupe),a={json:n.transformedValue};n.annotations&&(a.meta={...a.meta,values:n.annotations});const o=Ire(t,this.dedupe);return o&&(a.meta={...a.meta,referentialEqualities:o}),a.meta&&(a.meta.v=1),a}deserialize(e,t){const{json:n,meta:a}=e;let o=t?.inPlace?n:Dy(n);return a?.values&&(o=Ere(o,a.values,a.v??0,this)),a?.referentialEqualities&&(o=Rre(o,a.referentialEqualities,a.v??0)),o}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)}};Gt.defaultInstance=new Gt;Gt.serialize=Gt.defaultInstance.serialize.bind(Gt.defaultInstance);Gt.deserialize=Gt.defaultInstance.deserialize.bind(Gt.defaultInstance);Gt.stringify=Gt.defaultInstance.stringify.bind(Gt.defaultInstance);Gt.parse=Gt.defaultInstance.parse.bind(Gt.defaultInstance);Gt.registerClass=Gt.defaultInstance.registerClass.bind(Gt.defaultInstance);Gt.registerSymbol=Gt.defaultInstance.registerSymbol.bind(Gt.defaultInstance);Gt.registerCustom=Gt.defaultInstance.registerCustom.bind(Gt.defaultInstance);Gt.allowErrorProps=Gt.defaultInstance.allowErrorProps.bind(Gt.defaultInstance);T.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 jre=Object.freeze([...new Set(Object.values(Ke))].toSorted()),Pre=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]),Dre=new Set(Pre);Object.freeze(jre.filter(e=>!Dre.has(e)));Object.freeze([...new Set(YY.filter(e=>e.scope==="device").map(e=>e.name))].toSorted());function Q4({value:e,unit:t,onDelta:n}){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:()=>n(-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:()=>n(1),children:"+"})]})}function zre({on:e,targetLabel:t,onConfirm:n}){const a=T.useRef(null),o=T.useRef(!1);return v.jsxs("div",{className:se("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:p=>{p.currentTarget.setPointerCapture?.(p.pointerId),a.current=p.clientX,o.current=!1},onPointerMove:p=>{a.current!==null&&Math.abs(p.clientX-a.current)>40&&(o.current=!0)},onPointerUp:()=>{o.current&&n(),o.current=!1,a.current=null},onPointerCancel:()=>{o.current=!1,a.current=null}})]})}var Lre=2,gC=270,qre=315;function Bre(e){const t=(e-135+360)%360;return t>gC?t<=qre?1:0:t/gC}function Mp({fraction:e,color:t,knobTopPx:n,onDragFraction:a}){const o=-135+e*270,p=T.useRef(null),[f,m]=T.useState(!1),h=a!==void 0,u=n??Lre,x=A=>{a!==void 0&&(A.preventDefault(),A.stopPropagation(),A.currentTarget.setPointerCapture?.(A.pointerId),m(!0))},w=A=>{if(a===void 0||!f)return;const R=p.current;if(R===null)return;const I=R.getBoundingClientRect(),O=I.left+I.width/2,D=I.top+I.height/2;a(Bre(Math.atan2(A.clientY-D,A.clientX-O)*180/Math.PI))},C=A=>{a!==void 0&&(A.currentTarget.releasePointerCapture?.(A.pointerId),m(!1))};return v.jsx("div",{ref:p,className:"absolute inset-0",style:{transform:`rotate(${o}deg)`},children:v.jsx("div",{className:se("absolute left-1/2 h-5 w-5 -translate-x-1/2 rounded-full bg-white shadow",h&&(f?"cursor-grabbing":"cursor-grab")),style:{top:u,border:`3px solid ${t}`},...h?{onPointerDown:x,onPointerMove:w,onPointerUp:C,onPointerCancel:C}:{}})})}function zy({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 $i=150,Cp=64,Ure=$i/2,Ly=2*Math.PI*Cp,Ug=Ly*(270/360);function V4({fraction:e,color:t,children:n,onDragFraction:a}){const o=Math.min(1,Math.max(0,e)),p=$i/2,f=$i/2,m=Ly-Ug,h=o*Ug;return v.jsxs("div",{className:"relative",style:{width:$i,height:$i},children:[v.jsxs("svg",{width:$i,height:$i,viewBox:`0 0 ${$i} ${$i}`,"aria-hidden":"true",className:"absolute inset-0",style:{transform:"rotate(135deg)"},children:[v.jsx("circle",{cx:p,cy:f,r:Cp,fill:"none",stroke:"var(--color-border)",strokeWidth:11,strokeDasharray:`${Ug} ${m}`,strokeLinecap:"round"}),v.jsx("circle",{cx:p,cy:f,r:Cp,fill:"none",stroke:t,strokeWidth:11,strokeDasharray:`${h} ${Ly-h}`,strokeLinecap:"round"})]}),v.jsx("div",{"data-testid":"arc-knob",children:v.jsx(Mp,{fraction:o,color:t,knobTopPx:Ure-Cp-10,...a!==void 0?{onDragFraction:a}:{}})}),v.jsx("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-0.5 pointer-events-none",children:n})]})}function h0({on:e,busy:t,onToggle:n}){const a={transform:e?"translateX(30px)":"translateX(3px)"};return v.jsx("button",{type:"button","aria-pressed":e,title:e?"Turn off":"Turn on",disabled:t,onClick:o=>{o.stopPropagation(),n()},className:se("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:se("absolute h-6 w-6 rounded-full transition-all",e?"bg-success":"bg-foreground-subtle"),style:a})})}function Fre({trpc:e,deviceId:t}){const n=mu(e,t),a=n!==null?n.button:void 0;if(a===void 0)return null;const o=()=>{a.press({deviceId:t})};return v.jsxs("button",{type:"button","aria-label":"Press",title:"Press",onClick:p=>{p.stopPropagation(),o()},className:se("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(WT,{className:"h-3 w-3"}),v.jsx("span",{children:"Press"})]})}function Hre({trpc:e,deviceId:t}){const n=mu(e,t),a=n!==null?n.button:void 0;if(a===void 0)return null;const o=()=>{a.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:o,className:se("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(WT,{className:"h-6 w-6"})}),v.jsx("span",{className:"text-sm font-medium text-foreground",children:"Press"})]})}var $re=4e3;function vC(e){if(e!==void 0)return e!==null&&typeof e=="object"&&"lastChangedAt"in e&&typeof e.lastChangedAt=="number"?e.lastChangedAt:e}function Lt(e,t){const n=t?.enabled!==!1,a=t?.timeoutMs??$re,[o,p]=T.useState(void 0),f=T.useRef(void 0),m=T.useRef(void 0),h=T.useRef(!1),u=T.useRef(void 0),x=T.useCallback(()=>{u.current!==void 0&&(clearTimeout(u.current),u.current=void 0),f.current=void 0,h.current=!1,m.current=void 0,p(void 0)},[]);T.useEffect(()=>{if(!n||!h.current)return;const C=vC(e),A=m.current;C!==void 0&&C!==A&&x()}),T.useEffect(()=>()=>{u.current!==void 0&&clearTimeout(u.current)},[]);const w=T.useCallback(C=>{if(!n)return;u.current!==void 0&&(clearTimeout(u.current),u.current=void 0);const A=f.current??e;if(A!==void 0){const R={...A,...C};f.current=R,p(R)}m.current=vC(e),h.current=!0,u.current=setTimeout(x,a)},[n,e,x,a]);return n?{display:o!==void 0?o:e,applyOptimistic:w}:{display:e,applyOptimistic:()=>{}}}function Qre(e){return e instanceof Error?e.message:String(e)}function Vre({trpc:e,deviceId:t,layout:n,optimistic:a,features:o}){const{cap:p,slice:f,available:m}=ft({trpc:e,deviceId:t,cap:F=>F.lockControl,slice:F=>F.state.lockControl}),{display:h,applyOptimistic:u}=Lt(f,{enabled:a??!0}),[x,w]=T.useState(null),[C,A]=T.useState(!1),[R,I]=T.useState(null);if(h===void 0)return null;const O=h.state==="locked"||h.state==="locking",D=!m||h.state==="jammed",z=o?.includes(la.LockOpen)===!0,B=n==="compact",q=()=>{u({state:"locking"}),p?.lock({})},G=()=>{u({state:"unlocking"}),p?.unlock({})},ae=()=>{p?.open({})},Q=()=>{if(!D){if(!O){q();return}if(B){I(null),w("unlock");return}G()}},H=()=>{if(!D){if(B){I(null),w("open");return}ae()}},oe=()=>{C||w(null)},we=async()=>{if(!(C||x===null)){I(null),A(!0);try{x==="unlock"?(u({state:"unlocking"}),await p?.unlock({})):await p?.open({}),w(null)}catch(F){I(Qre(F))}finally{A(!1)}}},Me=O?"Unlock":"Lock",Ae=x==="open"?"Open door?":"Unlock device?",Ce=x==="open"?"This will release the latch and open the door.":"This will unlock the device.",re=x==="open"?"Confirm open":"Confirm unlock",Te=x==="open"?v.jsx(il,{className:"h-4 w-4 text-amber-400"}):v.jsx(yy,{className:"h-4 w-4 text-amber-400"});return v.jsxs("div",{className:se("inline-flex items-center",n==="full"?"gap-2":"gap-1"),children:[v.jsxs("button",{type:"button","aria-label":Me,title:h.state==="jammed"?"Jammed":Me,disabled:D,onClick:F=>{F.stopPropagation(),Q()},className:se("inline-flex items-center justify-center rounded transition-colors",n==="full"?"h-7 gap-1.5 px-2 text-xs":"h-5 w-5",O?"text-success":"text-warning",D&&"opacity-40 cursor-not-allowed","hover:bg-surface-hover"),children:[O?v.jsx(lu,{className:"h-3.5 w-3.5"}):v.jsx(yy,{className:"h-3.5 w-3.5"}),n==="full"&&v.jsx("span",{children:h.state})]}),z&&v.jsxs("button",{type:"button","aria-label":"Open door",title:"Open door",disabled:D,onClick:F=>{F.stopPropagation(),H()},className:se("inline-flex items-center justify-center rounded transition-colors",n==="full"?"h-7 gap-1.5 px-2 text-xs":"h-5 w-5","text-foreground-muted",D&&"opacity-40 cursor-not-allowed","hover:bg-surface-hover"),children:[v.jsx(il,{className:"h-3.5 w-3.5"}),n==="full"&&v.jsx("span",{children:"Open"})]}),B&&v.jsx(E4,{open:x!==null,onOpenChange:F=>{F||oe()},children:v.jsxs(f0,{width:"sm",onClick:F=>F.stopPropagation(),children:[v.jsxs(Lie,{children:[v.jsxs(Bie,{className:"flex items-center gap-2",children:[Te,Ae]}),v.jsx(Uie,{children:Ce})]}),R!==null&&v.jsx("div",{className:"mt-2 px-3 py-2 rounded border border-danger/40 bg-danger/10 text-xs text-danger",children:R}),v.jsxs(qie,{children:[v.jsx(Iy,{type:"button",variant:"ghost",size:"sm",disabled:C,onClick:()=>oe(),children:"Cancel"}),v.jsxs(Iy,{type:"button",variant:"danger",size:"sm","aria-label":re,disabled:C,onClick:()=>{we()},children:[C&&v.jsx(e0,{className:"h-3.5 w-3.5 animate-spin"}),re]})]})]})})]})}function g0({trpc:e,deviceId:t,optimistic:n}){const{cap:a,slice:o,available:p}=ft({trpc:e,deviceId:t,cap:R=>R.switch,slice:R=>R.state.switch}),{display:f,applyOptimistic:m}=Lt(o,{enabled:n??!0}),[h,u]=T.useState(!1);if(f===void 0)return null;const x=f.on===!0,w=h||!p,C={transform:x?"translateX(14px)":"translateX(2px)"},A=async()=>{if(w||!a)return;const R=!x;m({on:R}),u(!0);try{await a.setState({on:R})}finally{u(!1)}};return v.jsx("button",{type:"button","aria-pressed":x,title:x?"Turn off":"Turn on",disabled:w,onClick:R=>{R.stopPropagation(),A()},className:se("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",w&&"opacity-60"),children:v.jsx("span",{className:se("absolute h-3 w-3 rounded-full transition-all",x?"bg-success":"bg-foreground-subtle"),style:C})})}function Gre({trpc:e,deviceId:t,layout:n,optimistic:a}){const{cap:o,slice:p,available:f}=ft({trpc:e,deviceId:t,cap:x=>x.brightness,slice:x=>x.state.brightness}),{display:m,applyOptimistic:h}=Lt(p,{enabled:a??!0});if(m===void 0)return null;const u=!f;return v.jsxs("label",{className:se("flex items-center gap-2 text-xs text-foreground-subtle",n==="compact"&&"min-w-[140px]"),children:[v.jsx("input",{"aria-label":"Brightness",type:"range",min:0,max:100,step:1,value:m.percentage,disabled:u,onChange:x=>{const w=Number(x.target.value);h({percentage:w}),u||o?.setBrightness({percentage:w})}}),v.jsxs("span",{className:"tabular-nums w-8 text-right",children:[m.percentage,"%"]})]})}function Zre({trpc:e,deviceId:t,features:n,layout:a,optimistic:o}){const{cap:p,slice:f,available:m}=ft({trpc:e,deviceId:t,cap:I=>I.fanControl,slice:I=>I.state.fanControl}),{display:h,applyOptimistic:u}=Lt(f,{enabled:o??!0});if(h===void 0)return null;const x=!m,w=n??[],C=w.includes("fan-speed"),A=w.includes("fan-preset"),R=f?.percentageStep!=null&&f.percentageStep>0?f.percentageStep:1;return v.jsxs("div",{className:se("inline-flex items-center gap-2",a==="full"&&"flex-col items-stretch"),children:[C&&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:R,value:h.percentage??0,disabled:x,onChange:I=>{const O=Number(I.target.value),D=Math.min(100,Math.max(0,Math.round(O/R)*R));u({percentage:D}),x||p?.setPercentage({percentage:D})}}),v.jsxs("span",{className:"tabular-nums w-8 text-right",children:[h.percentage??"—","%"]})]}),A&&h.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:h.preset,disabled:x,onChange:I=>{const O=I.target.value;!x&&O&&(u({preset:O}),p?.setPreset({preset:O}))},className:"bg-surface border border-border rounded px-1 py-0.5",children:[v.jsx("option",{value:"",disabled:!0,children:"—"}),h.availablePresets.map(I=>v.jsx("option",{value:I,children:I},I))]})})]})}var v0={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"},G4={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"},Kre={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 Wre({trpc:e,deviceId:t,features:n,layout:a,optimistic:o}){const{cap:p,slice:f,available:m}=ft({trpc:e,deviceId:t,cap:A=>A.climateControl,slice:A=>A.state.climateControl}),{display:h,applyOptimistic:u}=Lt(f,{enabled:o??!0});if(p===void 0||h===void 0)return null;const x=!m;if(a==="compact")return v.jsxs("div",{"data-mode":h.mode,className:"inline-flex items-center gap-1",children:[v.jsx("span",{className:se("text-xs tabular-nums font-medium",G4[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:x,onClick:A=>{if(A.stopPropagation(),!x&&h.target!==null){const R=h.target-1;u({target:R}),p.setTarget({target:R})}},className:se("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:A=>{if(A.stopPropagation(),!x&&h.target!==null){const R=h.target+1;u({target:R}),p.setTarget({target:R})}},className:se("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:h.mode,disabled:x,onChange:A=>{A.stopPropagation();const R=A.target.value;x||(u({mode:R}),p.setMode({mode:R}))},className:se("bg-transparent px-0.5 text-xs text-foreground-subtle hover:text-foreground cursor-pointer",x&&"opacity-40 cursor-not-allowed"),children:h.availableModes.map(A=>v.jsx("option",{value:A,children:A},A))})]});const w=h.mode==="heat_cool"||h.targetLow!==null&&h.targetHigh!==null,C=!w&&h.target!==null;return v.jsxs("div",{"data-mode":h.mode,className:se("inline-flex items-center gap-2 rounded border px-2 py-1 transition-colors",v0[h.mode],"flex-col items-stretch gap-3"),children:[v.jsxs("div",{className:"inline-flex items-center gap-1 text-xs tabular-nums",children:[h.currentTemp!==null&&v.jsxs("span",{className:"text-foreground-subtle",children:[h.currentTemp,"°"]}),C&&v.jsxs(v.Fragment,{children:[v.jsx("span",{className:"text-foreground-subtle",children:"→"}),v.jsxs("span",{className:"font-medium",children:[h.target,"°"]}),v.jsx("button",{type:"button","aria-label":"Decrease target",disabled:x,onClick:A=>{if(A.stopPropagation(),!x&&h.target!==null){const R=h.target-1;u({target:R}),p.setTarget({target:R})}},className:se("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:A=>{if(A.stopPropagation(),!x&&h.target!==null){const R=h.target+1;u({target:R}),p.setTarget({target:R})}},className:se("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:h.availableModes.map(A=>v.jsx("button",{type:"button","aria-label":A,disabled:x,onClick:R=>{R.stopPropagation(),x||(u({mode:A}),p.setMode({mode:A}))},className:se("rounded px-1.5 py-0.5 text-xs transition-colors",A===h.mode?Kre[A]:"text-foreground-subtle hover:text-foreground hover:bg-surface-hover",x&&"opacity-40 cursor-not-allowed"),children:A},A))}),w&&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:h.targetLow??"",disabled:x,onChange:A=>{if(!x){const R=Number(A.target.value),I=h.targetHigh??R;u({targetLow:R}),p.setTargetRange({targetLow:R,targetHigh:I})}},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:h.targetHigh??"",disabled:x,onChange:A=>{if(!x){const R=Number(A.target.value),I=h.targetLow??R;u({targetHigh:R}),p.setTargetRange({targetLow:I,targetHigh:R})}},className:"w-14 rounded border border-border bg-surface px-1 py-0.5 tabular-nums"})]})]}),h.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:h.fanMode,disabled:x,onChange:A=>{const R=A.target.value;!x&&R&&(u({fanMode:R}),p.setFanMode({fanMode:R}))},className:"rounded border border-border bg-surface px-1 py-0.5",children:[v.jsx("option",{value:"",disabled:!0,children:"—"}),h.availableFanModes.map(A=>v.jsx("option",{value:A,children:A},A))]})]}),h.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:h.preset,disabled:x,onChange:A=>{const R=A.target.value;!x&&R&&(u({preset:R}),p.setPreset({preset:R}))},className:"rounded border border-border bg-surface px-1 py-0.5",children:[v.jsx("option",{value:"",disabled:!0,children:"—"}),h.availablePresets.map(A=>v.jsx("option",{value:A,children:A},A))]})]}),h.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:h.targetHumidity,disabled:x,onChange:A=>{const R=Number(A.target.value);u({targetHumidity:R}),x||p.setTargetHumidity({targetHumidity:R})}}),v.jsxs("span",{className:"tabular-nums w-8 text-right",children:[h.targetHumidity,"%"]})]})]})}var Yre={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"},Xre={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"},Z4=["off","all","one"];function Jre(e){return Z4.includes(e)}var eoe={off:"Off",all:"All",one:"One"};function toe(e){return e==="playing"||e==="buffering"?"pause":"play"}function noe({trpc:e,deviceId:t,features:n,layout:a,optimistic:o}){const{cap:p,slice:f,available:m}=ft({trpc:e,deviceId:t,cap:C=>C.mediaPlayer,slice:C=>C.state.mediaPlayer}),{display:h,applyOptimistic:u}=Lt(f,{enabled:o??!0});if(h===void 0)return null;const x=!m,w=toe(h.state);return v.jsxs("div",{"data-state":h.state,className:se("inline-flex items-center gap-2 rounded border px-2 py-1 transition-colors",Yre[h.state],a==="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":h.state,className:se("inline-block h-2 w-2 rounded-full flex-shrink-0",Xre[h.state])}),v.jsx("button",{type:"button","aria-label":w==="play"?"Play":"Pause",disabled:x,onClick:C=>{C.stopPropagation(),!x&&(w==="play"?(u({state:"playing"}),p?.play({})):(u({state:"paused"}),p?.pause({})))},className:se("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:w==="play"?"▶":"⏸"})]}),a==="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:C=>{C.stopPropagation(),x||p?.previous({})},className:se("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:C=>{C.stopPropagation(),x||p?.next({})},className:se("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:"⏭"})]}),h.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:h.volumeLevel,disabled:x,onChange:C=>{const A=Number(C.target.value);u({volumeLevel:A}),x||p?.setVolume({volumeLevel:A})}}),v.jsxs("span",{className:"tabular-nums w-8 text-right",children:[h.volumeLevel,"%"]})]}),h.isMuted!==null&&v.jsx("button",{type:"button","aria-label":h.isMuted?"Unmute":"Mute",disabled:x,onClick:C=>{if(C.stopPropagation(),!x&&h.isMuted!==null){const A=!h.isMuted;u({isMuted:A}),p?.setMute({muted:A})}},className:se("inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs transition-colors",h.isMuted?"bg-amber-400 text-amber-950":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover",x&&"opacity-40 cursor-not-allowed"),children:h.isMuted?"🔇":"🔊"}),h.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:h.source,disabled:x,onChange:C=>{const A=C.target.value;!x&&A&&(u({source:A}),p?.selectSource({source:A}))},className:"rounded border border-border bg-surface px-1 py-0.5",children:[v.jsx("option",{value:"",disabled:!0,children:"—"}),h.availableSources.map(C=>v.jsx("option",{value:C,children:C},C))]})]}),h.shuffle!==null&&v.jsx("button",{type:"button","aria-label":"Shuffle",disabled:x,onClick:C=>{if(C.stopPropagation(),!x&&h.shuffle!==null){const A=!h.shuffle;u({shuffle:A}),p?.setShuffle({shuffle:A})}},className:se("inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs transition-colors",h.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"}),h.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:h.repeat,disabled:x,onChange:C=>{const A=C.target.value;!x&&Jre(A)&&(u({repeat:A}),p?.setRepeat({repeat:A}))},className:"rounded border border-border bg-surface px-1 py-0.5",children:Z4.map(C=>v.jsx("option",{value:C,children:eoe[C]},C))})]})]})]})}function Tc(e,t){return t!==void 0?e.toFixed(t):Number.isInteger(e)?String(e):e.toFixed(1)}var aoe=/^(\d{4})-(\d{2})-(\d{2})/,ioe=/^(\d{2}):(\d{2})(?::(\d{2}))?$/;function roe(e,t){const n=aoe.exec(e);if(n===null)return e;const a=Number(n[1]),o=Number(n[2]),p=Number(n[3]),f=new Date(a,o-1,p);if(Number.isNaN(f.getTime()))return e;try{return f.toLocaleDateString(t)}catch{return e}}function ooe(e,t){const n=ioe.exec(e);if(n===null)return e;const a=new Date(1970,0,1,Number(n[1]),Number(n[2]),n[3]!==void 0?Number(n[3]):0);if(Number.isNaN(a.getTime()))return e;try{return a.toLocaleTimeString(t,{hour:"2-digit",minute:"2-digit"})}catch{return e}}function soe(e,t){const n=e.includes("T")?e:e.replace(" ","T"),a=new Date(n);if(Number.isNaN(a.getTime()))return e;try{return a.toLocaleString(t,{dateStyle:"medium",timeStyle:"short"})}catch{return e}}function y0(e,t,n){return e===""?e:t==="date"?roe(e,n):t==="time"?ooe(e,n):soe(e,n)}function loe(e){return e.slice(0,10)}function coe(e){return e.slice(0,5)}function uoe(e){return(e.includes("T")?e:e.replace(" ","T")).slice(0,16)}function doe({value:e,busy:t,onCommit:n,unit:a,min:o,max:p,step:f,precision:m}){const[h,u]=T.useState(Tc(e,m)),x=Number(h),w=h!==""&&!Number.isNaN(x),C=f??1,A=I=>{let O=I;return o!==void 0&&(O=Math.max(o,O)),p!==void 0&&(O=Math.min(p,O)),O},R=()=>{!t&&w&&n(A(x))};return v.jsxs("div",{className:"inline-flex items-center gap-1",children:[v.jsx("button",{type:"button","aria-label":"Decrement",disabled:t,onClick:I=>{if(I.stopPropagation(),!t){const O=A(e-C);u(Tc(O,m)),n(O)}},className:se("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:h,onChange:I=>{u(I.target.value);const O=Number(I.target.value);I.target.value!==""&&!Number.isNaN(O)&&(t||n(A(O)))},onBlur:R,onKeyDown:I=>{I.key==="Enter"&&R()},className:se("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")}),a!==void 0&&v.jsx("span",{className:"text-foreground-subtle text-xs",children:a}),v.jsx("button",{type:"button","aria-label":"Increment",disabled:t,onClick:I=>{if(I.stopPropagation(),!t){const O=A(e+C);u(Tc(O,m)),n(O)}},className:se("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 poe({value:e,busy:t,onCommit:n}){const[a,o]=T.useState(e);return v.jsx("input",{type:"text",disabled:t,value:a,onChange:p=>o(p.target.value),onBlur:()=>{t||n(a)},onKeyDown:p=>{p.key==="Enter"&&!t&&n(a)},className:se("rounded border border-border bg-surface px-2 py-0.5 text-xs",t&&"opacity-40 cursor-not-allowed")})}function moe({slice:e,busy:t,setValueFn:n,layout:a}){switch(e.kind){case"numeric":return v.jsx(doe,{value:typeof e.value=="number"?e.value:Number(e.value),busy:t,onCommit:o=>{n({control:{kind:"numeric",value:o}})},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:o=>{o.stopPropagation(),t||n({control:{kind:"select",value:o.target.value}})},className:se("w-full max-w-full min-w-0 truncate rounded border border-border bg-surface px-1 py-0.5 text-xs",t&&"opacity-40 cursor-not-allowed"),children:e.options.map(o=>v.jsx("option",{value:o,children:o},o))});case"text":return v.jsx(poe,{value:String(e.value),busy:t,onCommit:o=>{n({control:{kind:"text",value:o}})}});case"datetime":{const o=String(e.value),p=e.format??"datetime";return a==="compact"?o===""?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:y0(o,p)}):v.jsx("input",{type:p==="date"?"date":p==="time"?"time":"datetime-local","aria-label":"Control value",disabled:t,value:p==="date"?loe(o):p==="time"?coe(o):uoe(o),onChange:f=>{f.stopPropagation(),t||n({control:{kind:"datetime",value:f.target.value}})},className:se("rounded border border-border bg-surface px-1 py-0.5 text-xs",t&&"opacity-40 cursor-not-allowed")})}default:return null}}function K4({trpc:e,deviceId:t,features:n,layout:a,optimistic:o}){const{cap:p,slice:f,available:m}=ft({trpc:e,deviceId:t,cap:C=>C.control,slice:C=>C.state.control}),{display:h,applyOptimistic:u}=Lt(f,{enabled:o??!0});if(h===void 0)return null;const x=!m,w=C=>{!x&&p&&(u({value:C.control.value}),p.setValue(C))};return v.jsx("div",{"data-kind":h.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(moe,{slice:h,busy:x,setValueFn:w,layout:a})})}var foe=e=>e;function W4(e){const t=e.capName!==void 0?e.display?.perCap?.[e.capName]:void 0,n=t?.precision??e.display?.precision??e.roleDefault?.precision??e.slicePrecision,a=e.sliceUnit??e.canonicalUnit,o=t?.unit??e.display?.unit??e.roleDefault?.unit;return o!==void 0&&a!==void 0&&o!==a&&uX(a,o)?{unit:o,precision:n,toDisplayValue:p=>cX(p,a,o)??p}:{unit:a??"",precision:n,toDisplayValue:foe}}var Y4={kind:"binary",field:"on",onLabel:"Low",offLabel:"Normal"};function X4(e){return e==="battery-sensor"}function J4(e,t){if(!tN(e))return!1;const n=e[t];if(typeof n!="number")return!1;const a=e.lastFetchedAt;return!(n===0&&a===0)}var eN={"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 tN(e){return typeof e=="object"&&e!==null}function hoe(e){return typeof e=="object"&&e!==null}function goe(e){return typeof e=="object"&&e!==null&&"state"in e&&typeof e.state=="string"}function Ic(e){return typeof e=="object"&&e!==null&&"value"in e&&typeof e.value=="string"}function nN(e){if(typeof e!="object"||e===null)return;const t=e.format;if(t==="date"||t==="time"||t==="datetime")return t}function voe(e){return e==="home"?"Home":e==="not_home"?"Away":e.charAt(0).toUpperCase()+e.slice(1)}function yoe({trpc:e,device:t}){const n=t.role!=null?eN[t.role]:void 0,a=X4(t.role),{data:o}=lI({},{staleTime:6e4}),p=mu(e,t.id),f=To(p!==null&&n!==void 0?n.getSliceHandle(p.state):void 0),m=To(p!==null&&n?.kind==="numeric"?p.state.enumSensor:void 0),h=To(p!==null&&a?p.state.binary:void 0),u=a&&n?.kind==="numeric"&&!J4(f,n.field)&&h!==void 0,x=u?Y4:n,w=u?h:f;if(x===void 0||w===void 0)return null;if(x.kind==="numeric"){if(!tN(w))return null;const A=w[x.field];if(typeof A!="number")return null;const R=w.lastFetchedAt,I=A===0&&R===0;if(I&&Ic(m)&&m.value!=="")return v.jsx("span",{className:se("inline-flex items-baseline text-xs text-foreground"),children:m.value});if(I)return null;const O=w,D=typeof O.unit=="string"?O.unit:void 0,z=typeof O.precision=="number"?O.precision:void 0,B=W4({display:t.display,capName:t.role==="numeric-sensor"?"numeric-sensor":void 0,roleDefault:t.role!=null?o?.defaults[t.role]:void 0,sliceUnit:D,slicePrecision:z,canonicalUnit:x.canonicalUnit}),q=B.unit,G=Tc(B.toDisplayValue(A),B.precision);return v.jsxs("span",{className:se("inline-flex items-baseline gap-0.5 tabular-nums text-xs text-foreground"),children:[v.jsx("span",{children:G}),q&&v.jsx("span",{className:"text-foreground-subtle",children:q})]})}if(x.kind==="binary"){if(!hoe(w))return null;const R=!!w[x.field],I=R?x.onLabel:x.offLabel;return v.jsx("span",{className:se("inline-flex items-center rounded px-1.5 py-0.5 text-xs font-medium",R?"bg-warning/15 text-warning":"bg-surface-subtle text-foreground-subtle"),children:I})}if(x.kind==="string")return!Ic(w)||w.value===""?null:v.jsx("span",{className:se("inline-flex items-baseline text-xs text-foreground"),children:w.value});if(x.kind==="datetime"){if(!Ic(w)||w.value==="")return null;const A=nN(w)??x.format,R=y0(w.value,A);return v.jsx("span",{className:se("inline-flex items-baseline text-xs text-foreground"),children:R})}if(!goe(w))return null;const C=voe(w.state);return v.jsx("span",{className:se("inline-flex items-center rounded px-1.5 py-0.5 text-xs font-medium",w.state==="home"?"bg-success/15 text-success":"bg-surface-subtle text-foreground-subtle"),children:C})}function Rm(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 boe(e){switch(e){case"accent":return"bg-primary text-primary-foreground";case"filled":return"bg-primary/15 text-primary";case"neutral":return""}}function Fg({label:e,busy:t,variant:n,onClick:a,children:o}){return v.jsx("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:p=>{p.stopPropagation(),a()},className:se("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",boe(n),t&&"opacity-40 cursor-not-allowed"),children:o})}function Soe({trpc:e,deviceId:t,optimistic:n}){const{cap:a,slice:o,available:p}=ft({trpc:e,deviceId:t,cap:w=>w.cover,slice:w=>w.state.cover}),{display:f,applyOptimistic:m}=Lt(o,{enabled:n??!0});if(a===void 0)return null;const h=Rm(f?.state),u=!p,x=(w,C)=>{u||!w||(C!==void 0&&m(C),w({}))};return v.jsxs("div",{className:"inline-flex items-center gap-1",children:[v.jsx(Fg,{label:"Open",busy:u,variant:h.up,onClick:()=>x(a?.open,{state:"opening"}),children:v.jsx(xm,{className:"h-3.5 w-3.5"})}),v.jsx(Fg,{label:"Stop",busy:u,variant:h.stop,onClick:()=>x(a?.stop,{state:"stopped"}),children:v.jsx(du,{className:"h-3 w-3"})}),v.jsx(Fg,{label:"Close",busy:u,variant:h.down,onClick:()=>x(a?.close,{state:"closing"}),children:v.jsx(zo,{className:"h-3.5 w-3.5"})}),f!==void 0&&f.position!==null&&v.jsxs("span",{className:"tabular-nums text-xs text-foreground-subtle ml-1",children:[f.position,"%"]})]})}function Hg({label:e,busy:t,variant:n,onClick:a,children:o}){return v.jsx("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:p=>{p.stopPropagation(),a()},className:se("inline-flex h-10 w-10 items-center justify-center rounded-md text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",n==="accent"&&"bg-primary text-primary-foreground hover:bg-primary/90",n==="filled"&&"bg-primary/15 text-primary",t&&"opacity-40 cursor-not-allowed"),children:o})}function aN(){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 xoe({position:e,interactive:t,onSetPosition:n}){const a=(1-e/100)*100,o=T.useRef(null),p=T.useRef(!1),f=T.useRef(null),m=C=>{const A=o.current;if(A===null)return e;const R=A.getBoundingClientRect();if(R.height<=0)return e;const I=(C-R.top)/R.height,O=Math.round(100-I*100);return Math.min(100,Math.max(0,O))},h=C=>{if(n===void 0)return;const A=m(C);f.current!==A&&(f.current=A,n(A))},u=C=>{t&&(C.stopPropagation(),C.preventDefault(),p.current=!0,f.current=null,C.currentTarget.setPointerCapture(C.pointerId),h(C.clientY))},x=C=>{!t||!p.current||(C.stopPropagation(),h(C.clientY))},w=C=>{!t||!p.current||(C.stopPropagation(),p.current=!1,f.current=null,C.currentTarget.hasPointerCapture(C.pointerId)&&C.currentTarget.releasePointerCapture(C.pointerId))};return v.jsxs("div",{ref:o,"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?u:void 0,onPointerMove:t?x:void 0,onPointerUp:t?w:void 0,onPointerCancel:t?w:void 0,className:se("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(aN,{}),v.jsx("div",{className:"absolute inset-x-0 top-0 transition-all duration-200",style:{height:`${a}%`,background:"repeating-linear-gradient(#c9cdd2, #c9cdd2 6px, #b7bcc2 6px, #b7bcc2 8px)",borderBottom:a>0?"1px solid #9aa":"none"}}),v.jsxs("div",{"data-testid":"cover-lever",className:se("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(${a}% - 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 koe({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(aN,{}),!e&&v.jsx("div",{className:"absolute inset-0",style:{background:"repeating-linear-gradient(#c9cdd2, #c9cdd2 6px, #b7bcc2 6px, #b7bcc2 8px)"}})]})}function woe({trpc:e,deviceId:t,features:n,optimistic:a}){const{cap:o,slice:p,available:f}=ft({trpc:e,deviceId:t,cap:z=>z.cover,slice:z=>z.state.cover}),{display:m,applyOptimistic:h}=Lt(p,{enabled:a??!0});if(o===void 0)return null;const u=!f,x=(n??[]).includes(la.CoverPositionable),w=(n??[]).includes(la.CoverTilt),C=Rm(m?.state),A=m?.position??null,R=A!==null,I=m?.state==="open"||m?.state==="opening",O=(z,B)=>{u||!z||(B!==void 0&&h(B),z({}))},D=z=>{u||(h({position:z}),o?.setPosition({position:z}))};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:[R?v.jsx(xoe,{position:A,interactive:x,onSetPosition:x?D:void 0}):v.jsx(koe,{isOpen:I}),v.jsxs("div",{className:"flex flex-col gap-3 flex-1",children:[R&&v.jsxs("div",{className:"flex items-baseline gap-1",children:[v.jsx("span",{className:"text-3xl font-semibold tabular-nums text-foreground",children:A}),v.jsx("span",{className:"text-base text-foreground-subtle",children:"%"}),v.jsx("span",{className:"text-xs text-foreground-subtle ml-1",children:"open"})]}),!R&&v.jsx("div",{className:"flex items-baseline gap-1",children:v.jsx("span",{className:"text-3xl font-semibold capitalize text-foreground",children:m?.state??"—"})}),v.jsxs("div",{className:"flex items-center gap-2",children:[v.jsx(Hg,{label:"Open",busy:u,variant:C.up,onClick:()=>O(o?.open,{state:"opening"}),children:v.jsx(xm,{className:"h-5 w-5"})}),v.jsx(Hg,{label:"Stop",busy:u,variant:C.stop,onClick:()=>O(o?.stop,{state:"stopped"}),children:v.jsx(du,{className:"h-4 w-4"})}),v.jsx(Hg,{label:"Close",busy:u,variant:C.down,onClick:()=>O(o?.close,{state:"closing"}),children:v.jsx(zo,{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:A??0,disabled:u,className:"flex-1",onChange:z=>{D(Number(z.target.value))}}),v.jsxs("span",{className:"w-8 text-right tabular-nums",children:[A??"—","%"]})]}),!x&&A!==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:A,disabled:!0,readOnly:!0,className:"flex-1 opacity-60"}),v.jsxs("span",{className:"w-8 text-right tabular-nums",children:[A,"%"]})]}),w&&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:m?.tiltPosition??0,disabled:u,className:"flex-1",onChange:z=>{const B=Number(z.target.value);h({tiltPosition:B}),u||o?.setTiltPosition({tiltPosition:B})}}),v.jsxs("span",{className:"w-8 text-right tabular-nums",children:[m?.tiltPosition??"—","%"]})]})]})}function Moe(e){return v.jsx("span",{className:"text-foreground-subtle text-xs select-none","aria-hidden":"true",children:"—"})}function Coe(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 Aoe(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 Eoe({trpc:e,deviceId:t}){const{data:n}=cI({deviceId:t},{staleTime:6e4});return n===void 0?null:v.jsx(yoe,{trpc:e,device:Aoe(n)})}function Roe(e){return typeof e=="object"&&e!==null}function _oe(e){return typeof e=="object"&&e!==null}function Toe(e){return typeof e=="object"&&e!==null&&"state"in e&&typeof e.state=="string"}function Ioe(e){return e==="home"?"Home":e==="not_home"?"Away":e.charAt(0).toUpperCase()+e.slice(1)}var Noe={low:"bg-danger",medium:"bg-warning",high:"bg-success"};function Ooe(e){return e<=20?"low":e<=50?"medium":"high"}function joe({percent:e}){const t=Math.min(100,Math.max(0,e)),n=Ooe(t);return v.jsx("div",{"data-testid":"battery-bar","data-band":n,className:"h-2 w-24 overflow-hidden rounded-full bg-border",children:v.jsx("div",{className:se("h-full rounded-full transition-all",Noe[n]),style:{width:`${t}%`}})})}function Poe({trpc:e,device:t}){const n=t.role!=null?eN[t.role]:void 0,a=X4(t.role),{data:o}=lI({},{staleTime:6e4}),p=mu(e,t.id),f=To(p!==null&&n!==void 0?n.getSliceHandle(p.state):void 0),m=To(p!==null&&a?p.state.binary:void 0),h=a&&n?.kind==="numeric"&&!J4(f,n.field)&&m!==void 0,u=h?Y4:n,x=h?m:f;if(u===void 0||x===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(u.kind==="numeric"){if(!Roe(x))return null;const C=x[u.field];if(typeof C!="number")return null;const A=x,R=typeof A.unit=="string"?A.unit:void 0,I=typeof A.precision=="number"?A.precision:void 0,O=W4({display:t.display,capName:t.role==="numeric-sensor"?"numeric-sensor":void 0,roleDefault:t.role!=null?o?.defaults[t.role]:void 0,sliceUnit:R,slicePrecision:I,canonicalUnit:u.canonicalUnit}),D=O.unit;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:Tc(O.toDisplayValue(C),O.precision)}),D&&v.jsx("span",{className:"text-base text-foreground-subtle",children:D})]}),a&&v.jsx(joe,{percent:C}),v.jsx("span",{className:"text-sm text-foreground-subtle",children:t.name})]})}if(u.kind==="binary"){if(!_oe(x))return null;const A=!!x[u.field],R=A?u.onLabel:u.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:se("inline-flex items-center rounded px-3 py-1.5 text-lg font-semibold",A?"bg-warning/15 text-warning":"bg-surface-subtle text-foreground-subtle"),children:R}),v.jsx("span",{className:"text-sm text-foreground-subtle",children:t.name})]})}if(u.kind==="datetime"){if(!Ic(x))return null;if(x.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 C=nN(x)??u.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:y0(x.value,C)}),v.jsx("span",{className:"text-sm text-foreground-subtle",children:t.name})]})}if(u.kind==="string")return!Ic(x)||x.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:x.value}),v.jsx("span",{className:"text-sm text-foreground-subtle",children:t.name})]});if(!Toe(x))return null;const w=Ioe(x.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:se("inline-flex items-center rounded px-3 py-1.5 text-lg font-semibold",x.state==="home"?"bg-success/15 text-success":"bg-surface-subtle text-foreground-subtle"),children:w}),v.jsx("span",{className:"text-sm text-foreground-subtle",children:t.name})]})}function Doe({trpc:e,deviceId:t}){const{data:n}=cI({deviceId:t},{staleTime:6e4});return n===void 0?null:v.jsx(Poe,{trpc:e,device:n})}function iN(e){return e===void 0||e.inProgress?!1:e.availableVersion!==null&&e.currentVersion!==null&&e.availableVersion!==e.currentVersion}function rN(e,t){return ft({trpc:e,deviceId:t,cap:n=>n.update,slice:n=>n.state.update})}function zoe({trpc:e,deviceId:t}){const{cap:n,slice:a}=rN(e,t);return n===void 0?null:a?.inProgress?v.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-foreground-subtle",children:[v.jsx(e0,{className:"h-3.5 w-3.5 animate-spin"}),"Updating…"]}):iN(a)?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(QT,{className:"h-3 w-3"}),"Update"]}):v.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] text-foreground-subtle",children:[v.jsx(BT,{className:"h-3 w-3 text-success"}),a?.currentVersion??"Up to date"]})}function Loe({trpc:e,deviceId:t}){const{cap:n,slice:a,available:o}=rN(e,t);if(n===void 0)return null;const p=a?.inProgress===!0,f=iN(a),m=a?.currentVersion??"—",h=()=>{!o||n===void 0||!f||n.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:m}),f&&a?.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:a.availableVersion})]})]}),p?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(e0,{className:"h-4 w-4 animate-spin"}),"Installing…"]}):f?v.jsxs("button",{type:"button",onClick:u=>{u.stopPropagation(),h()},disabled:!o,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(QT,{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(BT,{className:"h-4 w-4"}),"Up to date"]}),a?.state!=null&&a.state!==""&&v.jsx("span",{className:"text-[10px] text-foreground-subtle",children:a.state})]})}function qoe(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 oN(e,t){return ft({trpc:e,deviceId:t,cap:n=>n.vacuumControl,slice:n=>n.state.vacuumControl})}function $g({label:e,busy:t,active:n,onClick:a,children:o}){return v.jsx("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:p=>{p.stopPropagation(),a()},className:se("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",n&&"bg-primary text-primary-foreground",t&&"opacity-40 cursor-not-allowed"),children:o})}function Boe(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 Uoe=`
83
83
  @keyframes rg-breathe { 0%,100%{opacity:.78;transform:scale(1)} 50%{opacity:1;transform:scale(1.05)} }
84
84
  @keyframes rg-zzz { 0%{opacity:0;transform:translateY(3px)} 30%{opacity:.85} 100%{opacity:0;transform:translateY(-9px)} }
@@ -112,4 +112,4 @@ ${n.slice(0,5).join(`
112
112
  @media (prefers-reduced-motion: reduce) {
113
113
  .acv-streak, .acv-fan, .acv-sway-wrap, .acv-glow, .acv-swing { animation: none !important; }
114
114
  }
115
- `;function kN({trpc:e,deviceId:t,layout:n,optimistic:a}){const{cap:o,slice:p,available:f}=ft({trpc:e,deviceId:t,cap:z=>z.climateControl,slice:z=>z.state.climateControl}),{display:m,applyOptimistic:h}=Lt(p,{enabled:a??!0});if(o===void 0||m===void 0)return null;const u=!f;if(n==="compact")return v.jsxs("div",{"data-mode":m.mode,className:"inline-flex items-center gap-1",children:[v.jsx("span",{className:se("text-xs tabular-nums font-medium",G4[m.mode]),children:m.target!==null?v.jsxs(v.Fragment,{children:[m.target,"°",m.currentTemp!==null&&v.jsxs("span",{className:"text-foreground-subtle font-normal",children:[" ","(",m.currentTemp,"°)"]})]}):m.currentTemp!==null?v.jsxs("span",{className:"text-foreground-subtle",children:[m.currentTemp,"°"]}):null}),m.target!==null&&v.jsxs(v.Fragment,{children:[v.jsx("button",{type:"button","aria-label":"Decrease target",disabled:u,onClick:z=>{if(z.stopPropagation(),!u&&m.target!==null){const B=m.target-1;h({target:B}),o.setTarget({target:B})}},className:se("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",u&&"opacity-40 cursor-not-allowed"),children:"−"}),v.jsx("button",{type:"button","aria-label":"Increase target",disabled:u,onClick:z=>{if(z.stopPropagation(),!u&&m.target!==null){const B=m.target+1;h({target:B}),o.setTarget({target:B})}},className:se("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",u&&"opacity-40 cursor-not-allowed"),children:"+"})]}),v.jsx("select",{"aria-label":"Mode",value:m.mode,disabled:u,onChange:z=>{z.stopPropagation();const B=m.availableModes.find(q=>q===z.target.value);!u&&B&&(h({mode:B}),o.setMode({mode:B}))},className:se("bg-transparent px-0.5 text-xs text-foreground-subtle hover:text-foreground cursor-pointer",u&&"opacity-40 cursor-not-allowed"),children:m.availableModes.map(z=>v.jsx("option",{value:z,children:Jg[z]},z))})]});const x=Ose[m.mode],w=m.mode!=="off",C=Dse(m.preset),A=m.preset==="turbo",R=Math.max(.55,zse(m.fanMode)*(A?.6:1)),I=m.swingVertical!==null,O=m.swingHorizontal!==null,D=w&&(m.swingVertical===!0||m.swingHorizontal===!0);return v.jsxs("div",{"data-mode":m.mode,className:se("relative flex flex-col items-stretch gap-2.5 overflow-hidden rounded-lg border p-3 transition-colors",v0[m.mode]),children:[v.jsx("style",{children:Lse}),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(Use,{mode:m.mode,accent:x,periodSec:R,swaying:D})}),v.jsx("div",{className:"pointer-events-none absolute inset-0 bg-gradient-to-b from-surface/50 via-transparent to-surface/50"}),w&&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(CC,{mode:m.mode,className:"h-3.5 w-3.5"}),Jg[m.mode],m.currentTemp!==null&&v.jsxs("span",{className:"normal-case text-foreground-subtle",children:["· ",m.currentTemp,"° now"]}),m.currentHumidity!==null&&v.jsxs("span",{className:"inline-flex items-center gap-0.5 normal-case text-foreground-subtle",children:[v.jsx(pl,{className:"h-3 w-3"}),m.currentHumidity,"%"]})]}),m.target!==null?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"relative z-10 flex items-center gap-3",children:[v.jsx(AC,{label:"Decrease target",symbol:"−",disabled:u,onClick:()=>{if(u||m.target===null)return;const z=m.target-1;h({target:z}),o.setTarget({target:z})}}),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:m.target}),v.jsx("span",{className:"text-lg text-foreground-subtle",children:"°"})]}),v.jsx(AC,{label:"Increase target",symbol:"+",disabled:u,onClick:()=>{if(u||m.target===null)return;const z=m.target+1;h({target:z}),o.setTarget({target:z})}})]}),v.jsx("div",{className:"relative z-10 w-36",children:v.jsx(Bse,{value:m.target,min:jse,max:Pse,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:m.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(ev,{label:"Mode",icon:v.jsx("span",{style:{color:x},className:"flex",children:v.jsx(CC,{mode:m.mode,className:"h-4 w-4"})}),value:m.mode,options:m.availableModes.map(z=>({value:z,label:Jg[z]})),disabled:u,onChange:z=>{const B=m.availableModes.find(q=>q===z);B&&(h({mode:B}),o.setMode({mode:B}))}}),m.availableFanModes.length>0&&v.jsx(ev,{label:"Fan",icon:v.jsx(Ki,{className:"h-4 w-4 text-sky-500"}),value:m.fanMode,options:m.availableFanModes.map(z=>({value:z,label:MC(z)})),disabled:u,onChange:z=>{h({fanMode:z}),o.setFanMode({fanMode:z})}}),m.availablePresets.length>0&&v.jsx(ev,{label:"Preset",icon:v.jsx(C,{className:"h-4 w-4 text-emerald-500"}),value:m.preset,options:m.availablePresets.map(z=>({value:z,label:MC(z)})),disabled:u,onChange:z=>{h({preset:z}),o.setPreset({preset:z})}})]}),(I||O)&&v.jsx(qse,{label:"Swing",children:v.jsxs("div",{className:"grid grid-cols-2 gap-1",children:[I&&v.jsx(EC,{axis:"vertical",on:m.swingVertical??!1,busy:u,onToggle:z=>{h({swingVertical:z}),o.setSwingVertical({on:z})}}),O&&v.jsx(EC,{axis:"horizontal",on:m.swingHorizontal??!1,busy:u,onToggle:z=>{h({swingHorizontal:z}),o.setSwingHorizontal({on:z})}})]})})]})}function qse({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 CC({mode:e,className:t}){const n=Nse[e];return v.jsx(n,{className:t,"aria-hidden":!0})}function ev({label:e,icon:t,value:n,options:a,disabled:o,onChange:p}){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:se("flex items-center gap-1 overflow-hidden rounded-lg border border-border/60 bg-surface-subtle px-1.5 py-1.5",o&&"opacity-40"),children:[v.jsx("span",{className:"flex shrink-0",children:t}),v.jsx("select",{"aria-label":e,value:n,disabled:o,onChange:f=>{f.stopPropagation(),o||p(f.target.value)},className:"min-w-0 flex-1 cursor-pointer appearance-none truncate bg-transparent text-xs font-medium text-foreground outline-none",children:a.map(f=>v.jsx("option",{value:f.value,children:f.label},f.value))}),v.jsx(zo,{className:"h-3 w-3 shrink-0 text-foreground-subtle"})]})]})}function AC({label:e,symbol:t,disabled:n,onClick:a}){return v.jsx("button",{type:"button","aria-label":e,disabled:n,onClick:a,className:se("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",n&&"opacity-40 cursor-not-allowed"),children:t})}function Bse({value:e,min:t,max:n,accent:a}){const o=`${Math.min(1,Math.max(0,(e-t)/(n-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:o,background:a}}),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:o,background:a}})]}),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:[n,"°"]})]})]})}function Use({mode:e,accent:t,periodSec:n,swaying:a}){const o=[0,1,2,3,4,5],p=e==="heat",f=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:o.map(m=>v.jsx("span",{className:"h-8 w-1 rounded-full bg-foreground-subtle opacity-40"},m))}):e==="fan_only"?v.jsx("div",{className:"flex h-full items-center justify-center",children:v.jsx(Fse,{color:t,periodSec:Math.max(.5,n*.7),size:56})}):v.jsx("div",{className:se("acv-sway-wrap absolute inset-0",a&&"acv-sway"),style:a?{animation:"acv-sway 2.6s ease-in-out infinite"}:void 0,children:o.map(m=>v.jsx("span",{className:"acv-streak absolute rounded-full",style:{left:`${8+m*15}%`,width:f?"0.4rem":"0.3rem",height:f?"0.4rem":"1.9rem",background:t,boxShadow:`0 0 6px ${t}`,animationName:p?"acv-rise":"acv-fall",animationTimingFunction:"linear",animationIterationCount:"infinite",animationDuration:`${n}s`,animationDelay:`${m%3*(n/3)+m*.05}s`}},m))})})}function Fse({color:e,periodSec:t,size:n}){return v.jsxs("svg",{width:n,height:n,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(a=>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(${a} 50 50)`},a)),v.jsx("circle",{cx:"50",cy:"50",r:"7",fill:e})]})}function EC({axis:e,on:t,busy:n,onToggle:a}){const o=e==="vertical"?"Vertical":"Horizontal",p=e==="vertical"?tte:ete,f=e==="vertical"?"acv-swing-v":"acv-swing-h";return v.jsxs("button",{type:"button","aria-label":`${o} swing`,"aria-pressed":t,disabled:n,onClick:()=>{n||a(!t)},className:se("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",n&&"opacity-40 cursor-not-allowed"),children:[v.jsx(p,{className:"acv-swing h-4 w-4","aria-hidden":!0,style:t?{animation:`${f} 1.4s ease-in-out infinite`}:void 0}),o]})}var Hse=5,$se=35;function tv(e,t,n){return Math.min(1,Math.max(0,(e-t)/(n-t)))}function nv(e,t,n){return Math.round(t+e*(n-t))}var Qi=176,em=76,Ap=2*Math.PI*em,yc=Ap*(270/360),av=Qi/2-em-10;function RC(e){const t=Qi/2,n=Qi/2,a=Ap-yc,o=e.mode==="band"?(()=>{const p=e.band.from*yc,f=Math.max(0,(e.band.to-e.band.from)*yc);return{dasharray:`${f} ${Ap-f}`,dashoffset:-p}})():(()=>{const p=e.fraction*yc;return{dasharray:`${p} ${Ap-p}`,dashoffset:void 0}})();return v.jsxs("svg",{width:Qi,height:Qi,viewBox:`0 0 ${Qi} ${Qi}`,"aria-hidden":"true",className:"absolute inset-0",style:{transform:"rotate(135deg)"},children:[v.jsx("circle",{cx:t,cy:n,r:em,fill:"none",stroke:"var(--color-border)",strokeWidth:12,strokeDasharray:`${yc} ${a}`,strokeLinecap:"round"}),v.jsx("circle",{cx:t,cy:n,r:em,fill:"none",stroke:e.color,strokeWidth:12,strokeDasharray:o.dasharray,...o.dashoffset!==void 0?{strokeDashoffset:o.dashoffset}:{},strokeLinecap:"round"})]})}var Qse={heat:"#f59e0b",cool:"#60a5fa",auto:"#c084fc",heat_cool:"#e879f9",fan_only:"#94a3b8",dry:"#22d3ee",off:"#d4d4d8"};function Vse({trpc:e,deviceId:t,features:n,optimistic:a}){const{cap:o,slice:p,available:f}=ft({trpc:e,deviceId:t,cap:D=>D.climateControl,slice:D=>D.state.climateControl}),{display:m,applyOptimistic:h}=Lt(p,{enabled:a??!0});if(o===void 0||m===void 0)return null;const u=!f,x=Qse[m.mode],w=m.mode==="heat_cool"||m.targetLow!==null&&m.targetHigh!==null,C=Hse,A=$se,R=!w&&m.target!==null?tv(m.target,C,A):0,I=w&&m.targetLow!==null?tv(m.targetLow,C,A):0,O=w&&m.targetHigh!==null?tv(m.targetHigh,C,A):0;return v.jsxs("div",{"data-mode":m.mode,className:se("flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4 transition-colors",v0[m.mode]),children:[v.jsxs("div",{className:"flex flex-col items-center gap-3",children:[v.jsxs("div",{className:"relative",style:{width:Qi,height:Qi},children:[w?v.jsx(RC,{mode:"band",band:{from:I,to:O},color:x}):v.jsx(RC,{mode:"fill",fraction:R,color:x}),w?v.jsxs(v.Fragment,{children:[v.jsx("div",{"data-testid":"arc-knob",children:v.jsx(Mp,{fraction:I,color:x,knobTopPx:av,onDragFraction:D=>{if(u||m.targetHigh===null)return;const z=Math.min(nv(D,C,A),m.targetHigh);h({targetLow:z}),o.setTargetRange({targetLow:z,targetHigh:m.targetHigh})}})}),v.jsx("div",{"data-testid":"arc-knob",children:v.jsx(Mp,{fraction:O,color:x,knobTopPx:av,onDragFraction:D=>{if(u||m.targetLow===null)return;const z=Math.max(nv(D,C,A),m.targetLow);h({targetHigh:z}),o.setTargetRange({targetLow:m.targetLow,targetHigh:z})}})})]}):v.jsx("div",{"data-testid":"arc-knob",children:v.jsx(Mp,{fraction:R,color:x,knobTopPx:av,onDragFraction:D=>{if(u)return;const z=nv(D,C,A);h({target:z}),o.setTarget({target:z})}})}),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:[m.currentTemp!==null?m.currentTemp:"—",v.jsx("span",{className:"text-lg text-foreground-subtle font-normal ml-0.5",children:"°"})]}),!w&&m.target!==null&&v.jsxs("div",{className:"text-xs font-semibold",style:{color:x},children:["set ",m.target,"°"]}),w&&m.targetLow!==null&&m.targetHigh!==null&&v.jsxs("div",{className:"text-xs font-semibold",style:{color:x},children:[m.targetLow,"° – ",m.targetHigh,"°"]})]})]}),!w&&m.target!==null&&v.jsx("div",{className:"w-[200px]",children:v.jsx(Q4,{value:`${m.target}°`,onDelta:D=>{if(u||m.target===null)return;const z=m.target+D;h({target:z}),o.setTarget({target:z})}})})]}),v.jsx("select",{"aria-label":"Mode",value:m.mode,disabled:u,onChange:D=>{D.stopPropagation();const z=D.target.value;!u&&z&&(h({mode:m.availableModes.find(B=>B===z)??m.mode}),o.setMode({mode:m.availableModes.find(B=>B===z)??m.mode}))},className:se("w-full rounded border border-border bg-surface px-3 py-1.5 text-sm",u&&"opacity-40 cursor-not-allowed"),children:m.availableModes.map(D=>v.jsx("option",{value:D,children:D},D))})]})}function Gse(e){return e==="locked"||e==="locking"}function wN(e){return e==="jammed"}var Zse={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 Kse({state:e}){const t=Zse[e];return v.jsx("div",{"data-testid":"lock-glyph","data-state":e,className:se("flex h-16 w-16 items-center justify-center rounded-full border-2",t.colorClass),children:t.icon==="locked"?v.jsx(lu,{className:"h-8 w-8","aria-hidden":"true"}):v.jsx(yy,{className:"h-8 w-8","aria-hidden":"true"})})}function Wse({state:e}){return v.jsx("span",{className:se("text-sm font-medium capitalize",wN(e)?"text-danger":"text-foreground-muted"),children:e})}function Yse({busy:e,onOpen:t}){return v.jsxs("button",{type:"button","aria-label":"Open (unlatch)",title:"Open (unlatch)",disabled:e,onClick:n=>{n.stopPropagation(),t()},className:se("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(il,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Open"]})}function Xse({trpc:e,deviceId:t,features:n,optimistic:a}){const{cap:o,slice:p,available:f}=ft({trpc:e,deviceId:t,cap:I=>I.lockControl,slice:I=>I.state.lockControl}),{display:m,applyOptimistic:h}=Lt(p,{enabled:a??!0});if(o===void 0||m===void 0)return null;const u=Gse(m.state),x=wN(m.state)||!f,w=n?.includes(la.LockOpen)===!0,C=()=>{x||(u?(h({state:"unlocking"}),o.unlock({})):(h({state:"locking"}),o.lock({})))},A=()=>{x||o.open({})},R=u?"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(Kse,{state:m.state}),v.jsx(Wse,{state:m.state})]}),v.jsx("div",{className:se(x&&"pointer-events-none opacity-40"),children:v.jsx(zre,{on:u,targetLabel:R,onConfirm:C})}),w&&v.jsx("div",{className:"flex justify-center",children:v.jsx(Yse,{busy:x,onOpen:A})})]})}var qy=500,MN=150,Jse="linear-gradient(90deg, #9ec9ff, #ffffff, #ffb24d)";function ele(e,t,n){return Math.min(1,Math.max(0,(e-t)/(n-t)))}function tle(e){return ele(e,MN,qy)}var nle="#f4b740",ale="#d4d4d8";function ile({trpc:e,deviceId:t,features:n,optimistic:a}){const o=ft({trpc:e,deviceId:t,cap:q=>q.switch,slice:q=>q.state.switch}),p=ft({trpc:e,deviceId:t,cap:q=>q.brightness,slice:q=>q.state.brightness}),f=ft({trpc:e,deviceId:t,cap:q=>q.color,slice:q=>q.state.color}),m=Lt(o.slice,{enabled:a??!0}),h=Lt(p.slice,{enabled:a??!0}),u=Lt(f.slice,{enabled:a??!0});if(o.cap===void 0||m.display===void 0)return null;const x=m.display.on===!0,w=!o.available,C=h.display?.percentage??0,A=!p.available,R=x?C/100:0,I=x?nle:ale,O=(n?.includes(la.LightColorMired)??!1)&&f.cap!==void 0,D=u.display?.mireds,z=!f.available,B=()=>{if(w)return;const q=!x;m.applyOptimistic({on:q}),o.cap?.setState({on:q})};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(V4,{fraction:R,color:I,children:[v.jsxs("div",{"data-testid":"brightness-readout",className:"text-3xl font-bold tabular-nums text-foreground leading-none",children:[C,v.jsx("span",{className:"text-base text-foreground-subtle font-normal ml-0.5",children:"%"})]}),v.jsx(wm,{className:"h-5 w-5 text-foreground-subtle","aria-hidden":"true"})]}),p.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:C,disabled:A||!x,onChange:q=>{const G=Number(q.target.value);h.applyOptimistic({percentage:G}),A||p.cap?.setBrightness({percentage:G})}}),v.jsxs("span",{className:"tabular-nums w-9 text-right",children:[C,"%"]})]})]}),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(h0,{on:x,busy:w,onToggle:B})]}),O&&v.jsxs("div",{className:"flex items-center gap-2","data-testid":"color-temp-strip",children:[v.jsx(Cm,{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:MN,max:qy,step:1,className:"w-full",value:D??qy,disabled:z||!x,onChange:q=>{const G=Number(q.target.value);u.applyOptimistic({mode:"mired",mireds:G}),z||f.cap?.setColor({color:{mode:"mired",mireds:G}})}}),v.jsx("div",{className:"pointer-events-none mt-1",children:v.jsx(zy,{fraction:D!==void 0?tle(D):.5,color:Jse})})]})]})]})}var rle="#3aa6a0",ole="#d4d4d8";function sle({trpc:e,deviceId:t,features:n,optimistic:a}){const o=ft({trpc:e,deviceId:t,cap:H=>H.switch,slice:H=>H.state.switch}),p=ft({trpc:e,deviceId:t,cap:H=>H.fanControl,slice:H=>H.state.fanControl}),f=Lt(o.slice,{enabled:a??!0}),m=Lt(p.slice,{enabled:a??!0});if(o.cap===void 0||f.display===void 0)return null;const h=f.display.on===!0,u=!o.available,x=m.display?.percentage??0,w=!p.available,C=h?x/100:0,A=h?rle:ole,R=n?.includes(la.FanSpeed)??!1,I=(n?.includes(la.FanOscillating)??!1)&&p.cap!==void 0,O=m.display?.availablePresets??[],D=(n?.includes(la.FanPreset)??!1)&&p.cap!==void 0&&O.length>0,z=m.display?.preset??"",B=m.display?.oscillating===!0,q=()=>{if(u)return;const H=!h;f.applyOptimistic({on:H}),o.cap?.setState({on:H})},G=()=>{if(w)return;const H=!B;m.applyOptimistic({oscillating:H}),p.cap?.setOscillating({oscillating:H})},ae=H=>{if(w)return;const oe=m.display;if(oe===void 0)return;const we=oe.percentageStep!==void 0&&oe.percentageStep>0?oe.percentageStep:1,Me=Math.min(100,Math.max(0,Math.round(H*100/we)*we));m.applyOptimistic({percentage:Me}),p.cap?.setPercentage({percentage:Me})},Q=H=>{w||H===""||(m.applyOptimistic({preset:H}),p.cap?.setPreset({preset:H}))};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:R?v.jsxs(V4,{fraction:C,color:A,onDragFraction:ae,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(Vp,{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(Vp,{className:"h-16 w-16",style:{color:A},"aria-hidden":"true"})})}),D&&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:z,disabled:w,onChange:H=>{H.stopPropagation(),Q(H.target.value)},className:se("bg-surface border border-border rounded px-1 py-0.5",w&&"opacity-40 cursor-not-allowed"),children:[v.jsx("option",{value:"",disabled:!0,children:"—"}),O.map(H=>v.jsx("option",{value:H,children:H},H))]})]})}),v.jsxs("div",{className:"flex items-center justify-between gap-2",children:[I?v.jsxs("button",{type:"button","aria-label":"Oscillate","aria-pressed":B,disabled:w,onClick:H=>{H.stopPropagation(),G()},className:se("inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs font-medium transition-colors",B?"border-success/50 bg-success/10 text-success":"border-border text-foreground-muted hover:bg-surface-hover",w&&"opacity-40 cursor-not-allowed"),children:[v.jsx(n0,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Oscillate"]}):v.jsx("span",{className:"text-sm font-medium text-foreground-muted",children:h?"On":"Off"}),v.jsx(h0,{on:h,busy:u,onToggle:q})]})]})}function lle({trpc:e,deviceId:t,optimistic:n}){const{cap:a,slice:o,available:p}=ft({trpc:e,deviceId:t,cap:w=>w.switch,slice:w=>w.state.switch}),{display:f,applyOptimistic:m}=Lt(o,{enabled:n??!0});if(a===void 0||f===void 0)return null;const h=f.on===!0,u=!p,x=()=>{if(u)return;const w=!h;m({on:w}),a.setState({on:w})};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":h?"on":"off",className:se("flex h-16 w-16 items-center justify-center rounded-full border-2 transition-colors",h?"border-success/30 bg-success/10 text-success":"border-border bg-surface-subtle text-foreground-subtle"),children:v.jsx(uu,{className:"h-8 w-8","aria-hidden":"true"})}),v.jsx("span",{className:"text-sm font-medium text-foreground-muted",children:h?"On":"Off"}),v.jsx(h0,{on:h,busy:u,onToggle:x})]})}function cle(e){return e==="playing"||e==="buffering"?"pause":"play"}function ule(e,t){return e===null||t===null||t<=0?0:Math.min(1,Math.max(0,e/t))}function _C(e){if(e===null)return"--:--";const t=Math.floor(e/1e3);return`${Math.floor(t/60)}:${(t%60).toString().padStart(2,"0")}`}function dle({title:e,subtitle:t}){return v.jsxs("div",{className:"flex flex-col items-center gap-1 text-center",children:[v.jsx(YT,{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 iv({label:e,busy:t,onPress:n,children:a,primary:o}){return v.jsx("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:p=>{p.stopPropagation(),t||n()},className:se("inline-flex items-center justify-center rounded-full transition-colors",o?"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:a})}function ple({trpc:e,deviceId:t,features:n,optimistic:a}){const{cap:o,slice:p,available:f}=ft({trpc:e,deviceId:t,cap:B=>B.mediaPlayer,slice:B=>B.state.mediaPlayer}),{display:m,applyOptimistic:h}=Lt(p,{enabled:a??!0});if(o===void 0||m===void 0)return null;const u=!f,x=cle(m.state),w=(n?.includes(la.MediaPlayerSeek)??!1)&&m.durationMs!==null&&m.durationMs>0,C=n?.includes(la.MediaPlayerNext)??!1,A=n?.includes(la.MediaPlayerPrevious)??!1,R=(n?.includes(la.MediaPlayerVolume)??!1)&&m.volumeLevel!==null,I=()=>{u||(x==="play"?(h({state:"playing"}),o.play({})):(h({state:"paused"}),o.pause({})))},O=m.currentMedia?.artist??m.currentMedia?.album??null,D=ule(m.positionMs,m.durationMs),z=m.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(dle,{title:m.currentMedia?.title??null,subtitle:O}),w&&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:m.durationMs??0,step:1e3,className:"absolute inset-0 h-4 w-full cursor-pointer opacity-0",value:m.positionMs??0,disabled:u,onChange:B=>{if(u)return;const q=Number(B.target.value);h({positionMs:q}),o.seek({positionMs:q})}}),v.jsx("div",{className:"pointer-events-none",children:v.jsx(zy,{fraction:D})})]}),v.jsxs("div",{className:"flex justify-between text-[11px] tabular-nums text-foreground-subtle",children:[v.jsx("span",{children:_C(m.positionMs)}),v.jsx("span",{children:_C(m.durationMs)})]})]}),v.jsxs("div",{className:"flex items-center justify-center gap-4",children:[A&&v.jsx(iv,{label:"Previous",busy:u,onPress:()=>{o.previous({})},children:v.jsx(hte,{className:"h-5 w-5","aria-hidden":"true"})}),v.jsx(iv,{label:x==="play"?"Play":"Pause",busy:u,onPress:I,primary:!0,children:x==="play"?v.jsx(Lo,{className:"h-6 w-6","aria-hidden":"true"}):v.jsx(cu,{className:"h-6 w-6","aria-hidden":"true"})}),C&&v.jsx(iv,{label:"Next",busy:u,onPress:()=>{o.next({})},children:v.jsx(gte,{className:"h-5 w-5","aria-hidden":"true"})})]}),R&&v.jsxs("div",{"data-testid":"media-volume",className:"flex items-center gap-2",children:[v.jsx("button",{type:"button","aria-label":m.isMuted===!0?"Unmute":"Mute",title:m.isMuted===!0?"Unmute":"Mute",disabled:u,onClick:B=>{if(B.stopPropagation(),u||m.isMuted===null)return;const q=!m.isMuted;h({isMuted:q}),o.setMute({muted:q})},className:se("inline-flex h-7 w-7 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",u&&"opacity-40 cursor-not-allowed"),children:m.isMuted===!0?v.jsx(iI,{className:"h-4 w-4","aria-hidden":"true"}):v.jsx(pu,{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:z,disabled:u,onChange:B=>{if(u)return;const q=Number(B.target.value);h({volumeLevel:q}),o.setVolume({volumeLevel:q})}}),v.jsx("div",{className:"pointer-events-none",children:v.jsx(zy,{fraction:z/100})})]}),v.jsxs("span",{className:"w-9 text-right text-[11px] tabular-nums text-foreground-subtle",children:[z,"%"]})]})]})}var CN={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"}},AN={home:"Home",away:"Away",night:"Night",vacation:"Vacation",custom_bypass:"Bypass"};function EN(e){return e.startsWith("armed_")}function b0(e){return e==="arming"||e==="disarming"}function RN({icon:e,sizeClass:t="h-8 w-8"}){return e==="disarmed"?v.jsx(mte,{className:t,"aria-hidden":"true"}):e==="triggered"?v.jsx(Mm,{className:t,"aria-hidden":"true"}):e==="pending"?v.jsx(fte,{className:t,"aria-hidden":"true"}):v.jsx(pte,{className:t,"aria-hidden":"true"})}function TC({label:e,active:t,busy:n,onSelect:a}){return v.jsx("button",{type:"button","aria-label":e,"aria-pressed":t,disabled:n,onClick:o=>{o.stopPropagation(),n||a()},className:se("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",n&&"opacity-40 cursor-not-allowed"),children:e})}function mle({state:e,availableModes:t,busy:n,onDisarm:a,onArm:o}){const p=EN(e),f=b0(e);return v.jsxs("div",{className:se("flex min-w-0 items-stretch gap-1 rounded-lg border border-border bg-surface-subtle p-1"),children:[v.jsx(TC,{label:"Disarm",active:!p&&!f,busy:n,onSelect:a}),t.map(m=>v.jsx(TC,{label:AN[m],active:!f&&e===`armed_${m}`,busy:n,onSelect:()=>o(m)},m))]})}function _N(e,t,n){const{cap:a,slice:o,available:p}=ft({trpc:e,deviceId:t,cap:w=>w.alarmPanel,slice:w=>w.state.alarmPanel}),{display:f,applyOptimistic:m}=Lt(o,{enabled:n??!0}),h=!p;return{display:f,capPresent:a!==void 0,busy:h,handleDisarm:()=>{a===void 0||h||(m({state:"disarming"}),a.disarm({}))},handleArm:w=>{a===void 0||h||(m({state:"arming"}),a.arm({mode:w}))}}}function fle({trpc:e,deviceId:t,optimistic:n}){const{display:a,capPresent:o,busy:p,handleDisarm:f,handleArm:m}=_N(e,t,n);if(!o||a===void 0)return null;const h=CN[a.state],u=EN(a.state)?a.state.replace("armed_",""):"";return v.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[v.jsxs("span",{className:se("inline-flex shrink-0 items-center gap-1 rounded-md border px-1.5 py-0.5 text-[11px] font-medium whitespace-nowrap",h.colorClass,b0(a.state)&&"animate-pulse"),children:[v.jsx(RN,{icon:h.icon,sizeClass:"h-3 w-3"}),h.label]}),v.jsxs("select",{"aria-label":"Alarm mode",disabled:p,value:u,onClick:x=>x.stopPropagation(),onChange:x=>{x.stopPropagation();const w=x.target.value;w===""?f():m(w)},className:se("min-w-0 shrink rounded-md border border-border bg-surface-subtle px-1.5 py-0.5 text-xs text-foreground-muted",p&&"cursor-not-allowed opacity-40"),children:[v.jsx("option",{value:"",children:"Disarm"}),a.availableModes.map(x=>v.jsx("option",{value:x,children:AN[x]},x))]})]})}function hle({trpc:e,deviceId:t,optimistic:n}){const{display:a,capPresent:o,busy:p,handleDisarm:f,handleArm:m}=_N(e,t,n);if(!o||a===void 0)return null;const h=CN[a.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":a.state,className:se("flex h-16 w-16 items-center justify-center rounded-full border-2",h.colorClass,b0(a.state)&&"animate-pulse"),children:v.jsx(RN,{icon:h.icon})}),v.jsx("span",{className:se("text-sm font-medium",h.colorClass,"border-0 bg-transparent"),children:h.label})]}),v.jsx(mle,{state:a.state,availableModes:a.availableModes,busy:p,onDisarm:f,onArm:m})]})}function gle(e,t){if(e<=0)return null;const n=Math.max(0,Math.round((t-e)/1e3));return n<60?"just now":n<3600?`${Math.floor(n/60)} min ago`:n<86400?`${Math.floor(n/3600)} h ago`:new Date(e).toLocaleDateString()}function S0({atMs:e,neverLabel:t}){const n=gle(e,Date.now());return v.jsx("span",{className:"text-xs text-foreground-subtle","data-testid":"last-run",children:n===null?t:n})}function TN({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(rl,{className:"h-3 w-3 shrink-0","aria-hidden":"true"}),v.jsx("span",{className:"truncate",children:e})]})}function IN(e,t,n){const{cap:a,slice:o,available:p}=ft({trpc:e,deviceId:t,cap:x=>x.scriptRunner,slice:x=>x.state.scriptRunner}),{display:f,applyOptimistic:m}=Lt(o,{enabled:n??!0}),h=!p,u=f?.isRunning===!0;return{display:f,capPresent:a!==void 0,busy:h,running:u,run:()=>{a===void 0||h||u||(m({isRunning:!0}),a.run({}))},stop:()=>{a===void 0||h||!u||(m({isRunning:!1}),a.stop({}))}}}function NN({running:e,busy:t,large:n,onRun:a,onStop:o}){const p=e?"Stop":"Run";return v.jsxs("button",{type:"button","aria-label":p,title:p,disabled:t,"data-testid":"script-run","data-running":e?"true":"false",onClick:f=>{f.stopPropagation(),e?o():a()},className:se("inline-flex items-center gap-1 rounded transition-colors",n?"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(jee,{className:n?"h-4 w-4":"h-3 w-3","aria-hidden":"true"}):v.jsx(Lo,{className:n?"h-4 w-4":"h-3 w-3","aria-hidden":"true"}),v.jsx("span",{children:p})]})}function vle({trpc:e,deviceId:t,optimistic:n}){const{display:a,capPresent:o,busy:p,running:f,run:m,stop:h}=IN(e,t,n);return!o||a===void 0?null:v.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[v.jsx(NN,{running:f,busy:p,large:!1,onRun:m,onStop:h}),v.jsx(S0,{atMs:a.lastRunAt,neverLabel:"never run"})]})}function yle({trpc:e,deviceId:t,optimistic:n}){const{display:a,capPresent:o,busy:p,running:f,run:m,stop:h}=IN(e,t,n);return!o||a===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":f?"true":"false",className:se("flex h-16 w-16 items-center justify-center rounded-full border-2",f?"border-primary text-primary animate-pulse":"border-border text-foreground-subtle"),children:v.jsx(Lo,{className:"h-8 w-8","aria-hidden":"true"})}),v.jsx("span",{className:"text-sm font-medium",children:f?"Running":"Idle"}),v.jsx(S0,{atMs:a.lastRunAt,neverLabel:"never run"}),v.jsx(TN,{error:a.lastError})]}),v.jsx("div",{className:"flex justify-center",children:v.jsx(NN,{running:f,busy:p,large:!0,onRun:m,onStop:h})})]})}function ON(e,t,n){const{cap:a,slice:o,available:p}=ft({trpc:e,deviceId:t,cap:u=>u.automationControl,slice:u=>u.state.automationControl}),{display:f,applyOptimistic:m}=Lt(o,{enabled:n??!0}),h=!p;return{display:f,capPresent:a!==void 0,busy:h,setEnabled:u=>{a===void 0||h||(m({enabled:u}),u?a.enable({}):a.disable({}))},trigger:()=>{a===void 0||h||a.trigger({})}}}function jN({enabled:e,busy:t,onToggle:n}){return v.jsx("button",{type:"button",role:"switch","aria-checked":e,"aria-label":"Automation enabled",disabled:t,"data-testid":"automation-enabled",onClick:a=>{a.stopPropagation(),n(!e)},className:se("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 PN({busy:e,large:t,onTrigger:n}){return v.jsxs("button",{type:"button","aria-label":"Trigger",title:"Run this automation now",disabled:e,"data-testid":"automation-trigger",onClick:a=>{a.stopPropagation(),n()},className:se("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(Pr,{className:t?"h-4 w-4":"h-3 w-3","aria-hidden":"true"}),v.jsx("span",{children:"Trigger"})]})}function ble({trpc:e,deviceId:t,optimistic:n}){const{display:a,capPresent:o,busy:p,setEnabled:f,trigger:m}=ON(e,t,n);return!o||a===void 0?null:v.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[v.jsx(jN,{enabled:a.enabled,busy:p,onToggle:f}),v.jsx(PN,{busy:p,large:!1,onTrigger:m})]})}function Sle({trpc:e,deviceId:t,optimistic:n}){const{display:a,capPresent:o,busy:p,setEnabled:f,trigger:m}=ON(e,t,n);return!o||a===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":a.enabled?"true":"false",className:se("flex h-16 w-16 items-center justify-center rounded-full border-2",a.enabled?"border-success text-success":"border-border text-foreground-subtle"),children:v.jsx(Pr,{className:"h-8 w-8","aria-hidden":"true"})}),v.jsx("span",{className:"text-sm font-medium",children:a.enabled?"Enabled":"Disabled"}),v.jsx(S0,{atMs:a.lastTriggeredAt,neverLabel:"never triggered"}),v.jsx(TN,{error:a.lastError})]}),v.jsxs("div",{className:"flex items-center justify-center gap-3",children:[v.jsx(jN,{enabled:a.enabled,busy:p,onToggle:f}),v.jsx(PN,{busy:p,large:!0,onTrigger:m})]})]})}function xle({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 DN(e,t){const{cap:n}=ft({trpc:e,deviceId:t,cap:a=>a.switch,slice:a=>a.state.switch});return n!==void 0}function kle({trpc:e,deviceId:t,features:n,optimistic:a}){return DN(e,t)?v.jsx(g0,{trpc:e,deviceId:t,features:n,layout:"compact",optimistic:a}):null}function wle(e,t){const{cap:n}=ft({trpc:e,deviceId:t,cap:a=>a.lockControl,slice:a=>a.state.lockControl});return n!==void 0}function Mle({trpc:e,deviceId:t,features:n,optimistic:a}){return wle(e,t)?v.jsx(Vre,{trpc:e,deviceId:t,features:n,layout:"compact",optimistic:a}):null}function Cle({trpc:e,deviceId:t,features:n,optimistic:a}){return DN(e,t)?v.jsxs("div",{className:"inline-flex items-center gap-2",children:[v.jsx(g0,{trpc:e,deviceId:t,features:n,layout:"compact",optimistic:a}),v.jsx(Gre,{trpc:e,deviceId:t,features:n,layout:"compact",optimistic:a})]}):null}function Ale(e,t){const{cap:n}=ft({trpc:e,deviceId:t,cap:a=>a.fanControl,slice:a=>a.state.fanControl});return n!==void 0}function Ele({trpc:e,deviceId:t,features:n,optimistic:a}){return Ale(e,t)?v.jsxs("div",{className:"inline-flex items-center gap-2",children:[v.jsx(g0,{trpc:e,deviceId:t,features:n,layout:"compact",optimistic:a}),v.jsx(Zre,{trpc:e,deviceId:t,features:n,layout:"compact",optimistic:a})]}):null}function x0(e,t){const{cap:n}=ft({trpc:e,deviceId:t,cap:a=>a.climateControl,slice:a=>a.state.climateControl});return n!==void 0}function Rle({trpc:e,deviceId:t,features:n,optimistic:a}){return x0(e,t)?v.jsx(Wre,{trpc:e,deviceId:t,features:n,layout:"compact",optimistic:a}):null}function _le({trpc:e,deviceId:t,features:n,optimistic:a}){return x0(e,t)?v.jsx(kN,{trpc:e,deviceId:t,features:n,layout:"compact",optimistic:a}):null}function Tle({trpc:e,deviceId:t,features:n,optimistic:a}){return x0(e,t)?v.jsx(kN,{trpc:e,deviceId:t,features:n,layout:"full",optimistic:a}):null}function Ile(e,t){const{cap:n}=ft({trpc:e,deviceId:t,cap:a=>a.mediaPlayer,slice:a=>a.state.mediaPlayer});return n!==void 0}function Nle({trpc:e,deviceId:t,features:n,optimistic:a}){return Ile(e,t)?v.jsx(noe,{trpc:e,deviceId:t,features:n,layout:"compact",optimistic:a}):null}function zN(e,t){const{cap:n}=ft({trpc:e,deviceId:t,cap:a=>a.control,slice:a=>a.state.control});return n!==void 0}function Ole({trpc:e,deviceId:t,features:n,optimistic:a}){return zN(e,t)?v.jsx(K4,{trpc:e,deviceId:t,features:n,layout:"compact",optimistic:a}):null}function jle({trpc:e,deviceId:t,features:n,optimistic:a}){return zN(e,t)?v.jsx(xle,{children:v.jsx(K4,{trpc:e,deviceId:t,features:n,layout:"full",optimistic:a})}):null}var Ple={cover:{InlineControl:Soe,HeroCard:woe},valve:{InlineControl:ose,HeroCard:use},humidifier:{InlineControl:pse,HeroCard:fse},"water-heater":{InlineControl:vse,HeroCard:bse},switch:{InlineControl:kle,HeroCard:lle},light:{InlineControl:Cle,HeroCard:ile},fan:{InlineControl:Ele,HeroCard:sle},sensor:{InlineControl:Eoe,HeroCard:Doe},thermostat:{InlineControl:Rle,HeroCard:Vse},climate:{InlineControl:_le,HeroCard:Tle},button:{InlineControl:Fre,HeroCard:Hre},update:{InlineControl:zoe,HeroCard:Loe},lock:{InlineControl:Mle,HeroCard:Xse},"media-player":{InlineControl:Nle,HeroCard:ple},alarm:{InlineControl:fle,HeroCard:hle},control:{InlineControl:Ole,HeroCard:jle},weather:{InlineControl:kse,HeroCard:Cse},vacuum:{InlineControl:Zoe,HeroCard:Koe},"lawn-mower":{InlineControl:ase,HeroCard:ise},image:{InlineControl:Ase,HeroCard:Ese},"pet-feeder":{InlineControl:Tse,HeroCard:Ise},script:{InlineControl:vle,HeroCard:yle},automation:{InlineControl:ble,HeroCard:Sle},dummy:{InlineControl:Moe,HeroCard:Coe}};Object.fromEntries(Object.values($).map(e=>[e,Ple[HY[e]]]));$.Cover+"",$.Valve+"",$.Thermostat+"",$.Climate+"",$.Control+"",$.Button+"",$.MediaPlayer+"",$.AlarmPanel+"",$.Lock+"",$.Vacuum+"",$.LawnMower+"",$.Humidifier+"",$.Switch+"",$.Siren+"",$.Light+"",$.Fan+"",$.WaterHeater+"",$.Sensor+"",$.Presence+"",$.EventEmitter+"",$.Notifier+"",$.Script+"",$.Automation+"",$.Camera+"",$.Hub+"",$.Update+"",$.Generic+"",$.Weather+"",$.Container+"",$.Image+"",$.PetFeeder+"";new Set(Object.values($));var LN={[$.Camera]:{icon:Iee,label:"Camera"},[$.Hub]:{icon:ate,label:"Hub"},[$.Light]:{icon:wm,label:"Light"},[$.Siren]:{icon:Zp,label:"Siren"},[$.Switch]:{icon:by,label:"Switch"},[$.Sensor]:{icon:qT,label:"Sensor"},[$.Thermostat]:{icon:Cm,label:"Thermostat"},[$.Climate]:{icon:kee,label:"Air conditioner"},[$.Button]:{icon:UT,label:"Button"},[$.EventEmitter]:{icon:Pr,label:"Event Emitter"},[$.Update]:{icon:n0,label:"Update"},[$.Generic]:{icon:j2,label:"Generic"},[$.Notifier]:{icon:Qp,label:"Notifier"},[$.Script]:{icon:dte,label:"Script"},[$.Automation]:{icon:Nte,label:"Automation"},[$.Lock]:{icon:lu,label:"Lock"},[$.Cover]:{icon:Eee,label:"Cover"},[$.Valve]:{icon:ote,label:"Valve"},[$.Humidifier]:{icon:Tte,label:"Humidifier"},[$.WaterHeater]:{icon:Cee,label:"Water heater"},[$.Fan]:{icon:Vp,label:"Fan"},[$.MediaPlayer]:{icon:Jee,label:"Media player"},[$.AlarmPanel]:{icon:Mm,label:"Alarm panel"},[$.Control]:{icon:a0,label:"Control"},[$.Presence]:{icon:Xee,label:"Presence"},[$.Weather]:{icon:HT,label:"Weather"},[$.Vacuum]:{icon:_ee,label:"Vacuum"},[$.LawnMower]:{icon:kte,label:"Lawn mower"},[$.Container]:{icon:j2,label:"Container"},[$.Image]:{icon:Vee,label:"Image"},[$.PetFeeder]:{icon:Ree,label:"Pet feeder"}},Dle={[Qe.Siren]:{icon:Zp,label:"Siren"},[Qe.Floodlight]:{icon:wm,label:"Floodlight"},[Qe.Spotlight]:{icon:Fee,label:"Spotlight"},[Qe.PirSensor]:{icon:XT,label:"PIR sensor"},[Qe.Chime]:{icon:Qp,label:"Chime"},[Qe.Autotrack]:{icon:$T,label:"Auto-track"},[Qe.Nightvision]:{icon:t0,label:"Night vision"},[Qe.PrivacyMask]:{icon:Bee,label:"Privacy mask"},[Qe.Doorbell]:{icon:qee,label:"Doorbell"},[Qe.BinaryHelper]:{icon:by,label:"Binary helper"},[Qe.MotionSensor]:{icon:VT,label:"Motion sensor"},[Qe.ContactSensor]:{icon:il,label:"Contact sensor"},[Qe.LeakSensor]:{icon:Jb,label:"Leak sensor"},[Qe.SmokeSensor]:{icon:wee,label:"Smoke sensor"},[Qe.COSensor]:{icon:Ki,label:"CO sensor"},[Qe.GasSensor]:{icon:Gp,label:"Gas sensor"},[Qe.TamperSensor]:{icon:Mm,label:"Tamper sensor"},[Qe.VibrationSensor]:{icon:aI,label:"Vibration sensor"},[Qe.ConnectivitySensor]:{icon:Ite,label:"Connectivity"},[Qe.SoundSensor]:{icon:pu,label:"Sound sensor"},[Qe.BinarySensor]:{icon:by,label:"Binary sensor"},[Qe.TemperatureSensor]:{icon:Cm,label:"Temperature"},[Qe.HumiditySensor]:{icon:pl,label:"Humidity"},[Qe.AmbientLightSensor]:{icon:tI,label:"Ambient light"},[Qe.PressureSensor]:{icon:fp,label:"Pressure"},[Qe.WindSensor]:{icon:Ki,label:"Wind"},[Qe.RainSensor]:{icon:FT,label:"Rain"},[Qe.UvSensor]:{icon:bte,label:"UV index"},[Qe.SolarRadiationSensor]:{icon:Ste,label:"Solar radiation"},[Qe.SoilMoistureSensor]:{icon:yte,label:"Soil moisture"},[Qe.PowerSensor]:{icon:Pr,label:"Power"},[Qe.EnergySensor]:{icon:Pr,label:"Energy"},[Qe.VoltageSensor]:{icon:Pr,label:"Voltage"},[Qe.CurrentSensor]:{icon:Pr,label:"Current"},[Qe.AirQualitySensor]:{icon:Ki,label:"Air quality"},[Qe.BatterySensor]:{icon:fp,label:"Battery"},[Qe.NumericSensor]:{icon:Qee,label:"Numeric sensor"},[Qe.EnumSensor]:{icon:Wee,label:"Enum sensor"},[Qe.DateTimeSensor]:{icon:D2,label:"Date / time"},[Qe.GenericSensor]:{icon:fp,label:"Sensor"},[Qe.NumericControl]:{icon:a0,label:"Numeric control"},[Qe.SelectControl]:{icon:Kee,label:"Select control"},[Qe.TextControl]:{icon:Ate,label:"Text control"},[Qe.DateTimeControl]:{icon:D2,label:"Date / time control"},[Qe.MobilePushNotifier]:{icon:vte,label:"Mobile push"},[Qe.MessagingNotifier]:{icon:KT,label:"Messaging"},[Qe.EmailNotifier]:{icon:Yee,label:"Email"},[Qe.GenericNotifier]:{icon:Qp,label:"Notifier"}},zle=new Set(Object.values($));new Set(Object.values(Qe));function Lle(e){return zle.has(e)}var IC=LN[$.Generic];Dle[Qe.GenericSensor];function qle(e){return Lle(e)?LN[e]??IC:IC}Object.values($).map(e=>{const t=qle(e);return{id:e,label:t.label,icon:t.icon}});T.createContext(null);$.Sensor,$.Presence;var Ble="/addon/snapshot/media";function che(e,t={}){const{width:n,baseUrl:a}=t,[o,p]=T.useState(0);return{src:T.useMemo(()=>{if(e===null||e<=0)return null;const f=a!==void 0?a.replace(/\/+$/,""):"",m=new URLSearchParams;n!==void 0&&Number.isInteger(n)&&n>0&&m.set("w",String(n)),o>0&&(m.set("force","1"),m.set("r",String(o)));const h=m.toString();return`${f}${Ble}/${String(e)}.jpg${h.length>0?`?${h}`:""}`},[e,n,a,o]),loading:!1,refresh:T.useCallback(()=>{p(f=>f+1)},[])}}d({id:l(),stableId:s(),addonId:s(),type:s(),name:s(),online:E(),disabled:E(),parentDeviceId:l().nullable(),role:s().nullable().optional(),features:M(s()).optional(),isCamera:E().optional()});gi("camstack:player-overlays-state",null);var Ule=gi("camstack:player-overlays-actions",null);function uhe(e){const t=T.useContext(Ule);T.useEffect(()=>{if(!(!t||!e))return t.setLayer(e),()=>t.removeLayer(e.id)},[t,e])}gi("camstack:zone-editing",null);var NC=500,rv=800;function bc(e,t,n){try{const a=e.live;if(!a)return null;const o=a.onEvent;return!o||typeof o.subscribe!="function"?null:o.subscribe({category:t},{onData:n})}catch{return null}}function Wd(e,t){return e?.id===t}function Fle(e,t){const[n,a]=T.useState(null),[o,p]=T.useState(null),[f,m]=T.useState(null),[h,u]=T.useState("watching"),x=T.useRef(void 0),w=T.useRef(void 0),C=T.useRef(void 0),A=T.useRef(0);return T.useEffect(()=>{if(t===null)return;const R=bc(e,"detection.motion-analysis",I=>{const O=I;if(!Wd(O?.source,t))return;const D=O.data;!D?.regions||D.regions.length===0||(a({zones:D.regions.map(z=>({...z.bbox,intensity:z.intensity})),frameWidth:D.frameWidth,frameHeight:D.frameHeight}),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>a(null),NC))});return()=>{R?.unsubscribe(),x.current&&clearTimeout(x.current)}},[e,t]),T.useEffect(()=>{if(t===null)return;const R=bc(e,"detection.motion-zones-raw",I=>{const O=I;if(!Wd(O?.source,t))return;const D=O.data;D?.zones&&(p({boxes:D.zones.map(z=>({bbox:z.bbox,changeScore:z.changeScore})),frameWidth:D.frameSize?.width??0,frameHeight:D.frameSize?.height??0,motionScore:D.zones.length>0?D.zones.reduce((z,B)=>z+B.changeScore,0)/D.zones.length:0}),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>p(null),NC))});return()=>{R?.unsubscribe(),w.current&&clearTimeout(w.current)}},[e,t]),T.useEffect(()=>{if(A.current=0,t===null)return;const R=bc(e,"pipeline-analytics.frame-tracked",I=>{const O=I?.data;!O||O.deviceId!==t||O.detections?.length&&typeof O.detections[0]?.kind=="string"&&(A.current=Date.now(),m({detections:O.detections,frameWidth:O.frameWidth,frameHeight:O.frameHeight}),C.current&&clearTimeout(C.current),C.current=setTimeout(()=>m(null),rv))});return()=>{R?.unsubscribe(),C.current&&clearTimeout(C.current)}},[e,t]),T.useEffect(()=>{if(t===null)return;const R=bc(e,"detection.result",I=>{const O=I;if(!Wd(O?.source,t)||Date.now()-A.current<rv)return;const D=O.data?.frame;D?.detections?.length&&(m({detections:D.detections,frameWidth:D.width,frameHeight:D.height}),C.current&&clearTimeout(C.current),C.current=setTimeout(()=>m(null),rv))});return()=>{R?.unsubscribe(),C.current&&clearTimeout(C.current)}},[e,t]),T.useEffect(()=>{if(t===null)return;const R=bc(e,"detection.phase-transition",I=>{const O=I;Wd(O?.source,t)&&O.data?.to&&u(O.data.to)});return()=>{R?.unsubscribe()}},[e,t]),{motion:n,motionRaw:o,detection:f,phase:h}}var Hle=5*6e4,$le=720*6e4,Qle="camstack:turn-servers:v1";function Vle(){const e=globalThis;try{return e.localStorage??null}catch{return null}}function Gle(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(n=>{if(typeof n!="object"||n===null)return!1;const a=n;return!(!(typeof a.urls=="string"||Array.isArray(a.urls)&&a.urls.every(o=>typeof o=="string"))||a.username!==void 0&&typeof a.username!="string"||a.credential!==void 0&&typeof a.credential!="string")})}var Zle=class{freshTtlMs;staleCapMs;storage;now;storageKey;memory=new WeakMap;inflight=new WeakMap;constructor(e={}){this.freshTtlMs=e.freshTtlMs??Hle,this.staleCapMs=e.staleCapMs??$le,this.storage="storage"in e?e.storage??null:Vle(),this.now=e.now??(()=>Date.now()),this.storageKey=e.storageKey??Qle}async getOrFetch(e,t){const n=this.now(),a=this.memory.get(e)??this.readStorage();if(a){const o=n-a.fetchedAt;if(o<this.freshTtlMs)return a.servers;if(o<this.staleCapMs)return this.startFetch(e,t,a),a.servers}return this.startFetch(e,t,a)}startFetch(e,t,n){const a=this.inflight.get(e);if(a)return a;const o=(async()=>{try{const p=await t();if(p.length>0){const f={servers:p,fetchedAt:this.now()};this.memory.set(e,f),this.writeStorage(f)}return p}catch{return n?.servers}})().finally(()=>{this.inflight.delete(e)});return this.inflight.set(e,o),o}readStorage(){if(this.storage)try{const e=this.storage.getItem(this.storageKey);if(e===null)return;const t=JSON.parse(e);return Gle(t)?t:void 0}catch{return}}writeStorage(e){if(this.storage)try{this.storage.setItem(this.storageKey,JSON.stringify(e))}catch{}}},Kle=new Zle;function qN(e,t,n=5e3){const[a,o]=T.useState([]);T.useEffect(()=>{if(t===null)return;let A=!1;const R=()=>{e.webrtcSession.listStreams.query({deviceId:t}).then(O=>{A||o(O)}).catch(()=>{})};R();const I=setInterval(R,n);return()=>{A=!0,clearInterval(I)}},[e,t,n]);const[p,f]=T.useState(null);T.useEffect(()=>{if(t===null)return;let A=!1;return e.pipelineOrchestrator&&e.pipelineOrchestrator.getCameraMetrics.query({deviceId:t}).then(R=>{A||!R||f({phase:R.phase,detectionFps:R.actualFps,avgInferenceMs:R.avgInferenceTimeMs,droppedFrames:R.droppedFrames})}).catch(()=>{}),()=>{A=!0}},[e,t]),fi("pipeline.camera-metrics-snapshot",A=>{if(t===null)return;const R=A.data;R.deviceId!==t||!R.metrics||f({phase:R.metrics.phase,detectionFps:R.metrics.actualFps,avgInferenceMs:R.metrics.avgInferenceTimeMs,droppedFrames:R.metrics.droppedFrames})});const{streams:m,hasWebrtc:h}=T.useMemo(()=>t===null||a.length===0?{streams:[],hasWebrtc:!1}:{streams:a.map(A=>({id:A.id,label:A.label,target:A.target,status:A.status,inputFps:A.inputFps,decodeFps:A.decodeFps,bitrateKbps:A.bitrateKbps})),hasWebrtc:!0},[t,a]),u=T.useCallback(async()=>{const A=e.turnProvider;if(A)return Kle.getOrFetch(e,async()=>(await A.getTurnServers.query()).map(R=>({urls:typeof R.urls=="string"?R.urls:[...R.urls],...R.username!==void 0?{username:R.username}:{},...R.credential!==void 0?{credential:R.credential}:{}})))},[e]);T.useEffect(()=>{u()},[u]);const x=T.useCallback(async(A,R)=>{if(t===null)throw new Error("No device selected");const I=await e.webrtcSession.createSession.mutate({deviceId:t,target:A,hints:R}),O=await u();return{sessionId:I.sessionId,sdpOffer:I.sdpOffer,...O?{iceServers:O}:{}}},[e,t,u]),w=T.useCallback(async(A,R,I,O)=>{if(t===null)throw new Error("No device selected");return e.webrtcSession.handleOffer.mutate({deviceId:t,target:A,sdpOffer:R,...I!==void 0?{sessionId:I}:{},...O!==void 0?{hints:O}:{}})},[e,t]),C=T.useCallback(async(A,R)=>{if(t===null)throw new Error("No device selected");await e.webrtcSession.handleAnswer.mutate({deviceId:t,sessionId:A,sdpAnswer:R})},[e,t]);return{streams:m,hasWebrtc:h,pipelineMetrics:p,createSession:x,handleOffer:w,getIceServers:u,addIceCandidate:T.useCallback(async(A,R)=>{t!==null&&await e.webrtcSession.addIceCandidate.mutate({deviceId:t,sessionId:A,candidate:R.candidate??"",sdpMid:R.sdpMid??null,sdpMLineIndex:R.sdpMLineIndex??null}).catch(()=>{})},[e,t]),getIceCandidates:T.useCallback(async A=>t===null?{candidates:[],done:!0}:e.webrtcSession.getIceCandidates.query({deviceId:t,sessionId:A}),[e,t]),sendAnswer:C,closeSession:T.useCallback(async A=>{t!==null&&await e.webrtcSession.closeSession.mutate({deviceId:t,sessionId:A}).catch(()=>{})},[e,t]),getSessionState:T.useCallback(async A=>{if(t===null)return{pendingRenegotiation:null};try{return await e.webrtcSession.getSessionState.query({deviceId:t,sessionId:A})}catch{return{pendingRenegotiation:null}}},[e,t])}}T.lazy(()=>Ys(()=>import("./MaskShapeCanvas-DI4BY7W2-MTA0w1Gf.js"),[],import.meta.url).then(e=>({default:e.MaskShapeCanvas})));T.lazy(()=>Ys(()=>import("./MotionZonesSettings-DNdnFHso-2_mSC4yb.js"),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.MotionZonesSettings})));T.lazy(()=>Ys(()=>import("./SceneMonitorEditor-d_A4kO-M-B7egu1hV.js"),__vite__mapDeps([3,1]),import.meta.url).then(e=>({default:e.SceneMonitorEditor})));T.lazy(()=>Ys(()=>import("./PrivacyMaskSettings-DNSLc6ww-BjMyK6YA.js"),__vite__mapDeps([2,1]),import.meta.url).then(e=>({default:e.PrivacyMaskSettings})));const BN=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim();const Wle=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const Yle=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase());const OC=e=>{const t=Yle(e);return t.charAt(0).toUpperCase()+t.slice(1)};var Xle={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const Jle=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1};const ece=T.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:o="",children:p,iconNode:f,...m},h)=>T.createElement("svg",{ref:h,...Xle,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:BN("lucide",o),...!p&&!Jle(m)&&{"aria-hidden":"true"},...m},[...f.map(([u,x])=>T.createElement(u,x)),...Array.isArray(p)?p:[p]]));const tce=(e,t)=>{const n=T.forwardRef(({className:a,...o},p)=>T.createElement(ece,{ref:p,iconNode:t,className:BN(`lucide-${Wle(OC(e))}`,`lucide-${e}`,a),...o}));return n.displayName=OC(e),n};const nce=[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["path",{d:"M9 9h.01",key:"1q5me6"}],["path",{d:"M15 9h.01",key:"x1ddxp"}]],ace=tce("scan-face",nce),tm={unassignedFace:"unassigned face",reviewed:"reviewed",debug:"debug",train:"train",favourite:"favourite",active:"active",loadingMore:"Loading more events"},ice=Object.keys(tm),UN=Y(s(),s());function rce(e){if(e===null||typeof e!="object")return tm;const t=e,n={...tm};for(const a of ice){const o=t[a];typeof o=="string"&&o.trim()!==""&&(n[a]=o)}return{unassignedFace:n.unassignedFace,reviewed:n.reviewed,debug:n.debug,train:n.train,favourite:n.favourite,active:n.active,loadingMore:n.loadingMore}}const oce="/viewer/camstack/embed/index.html",sce=j(["reel","gallery"]),lce=j(["small","medium","large"]),cce=j(["time","importance"]),uce=j(["text","semantic"]),dce=["face","plate"],k0=j(dce),pce=j(["auto","dark","light"]),mce=nt([V("auto"),l().int().min(1).max(12)]),fce=d({label:E(),sublabel:E(),camera:E(),time:E(),badges:E()});d({view:sce,rows:l().int().min(1).max(6).optional(),columns:mce.optional(),thumb:lce,deviceIds:M(l().int().nonnegative()),classes:M(s()).optional(),attrs:M(k0).optional(),search:s().optional(),searchMode:uce.optional(),semanticLimit:l().int().min(1).max(200).optional(),semanticMinScore:l().min(0).max(1).optional(),sort:cce.optional(),sinceMs:l().int().nonnegative().optional(),untilMs:l().int().nonnegative().optional(),deviceNames:Y(s(),s()).optional(),fields:fce,pageSize:l().int().min(1).max(500).optional(),maxRows:l().int().min(1).max(5e3).optional(),refreshMs:l().int().min(0).max(6e5).optional(),maxAgeMs:l().int().min(6e4).optional(),theme:pce});function w0(e){return e.startsWith("/")&&!e.startsWith("//")}function hce(e){return e!==void 0&&e.length>0?{Authorization:`Bearer ${e}`}:{}}function gce(e,t,n){if(!t.endsWith(n))return e;const a=t.slice(0,t.length-n.length);return a.length>0?a:e}function FN(e,t){e.token===void 0&&(w0(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 HN=j(["reel","gallery"]),$N=j(["small","medium","large"]),QN=j(["auto","dark","light"]),VN=d({label:E(),sublabel:E(),camera:E(),time:E(),badges:E()}),GN={label:!0,sublabel:!0,camera:!0,time:!0,badges:!0},ZN=j(["time","importance"]),KN=j(["text","semantic"]),WN=nt([V("auto"),l().int().min(1).max(12)]),vce=60,yce=5e3,bce=600;function Sce(e){return e.view==="reel"?Math.min(e.maxRows,bce):e.maxRows}const xce=0,kce=720*60*60*1e3,wce=d({serverUrl:s().min(1),token:s().min(1).optional(),view:HN.default("reel"),rows:l().int().min(1).max(6).default(1),columns:WN.default("auto"),thumbSize:$N.default("medium"),fields:VN.default(GN),deviceIds:M(l().int().nonnegative()).default([]),classes:M(s()).default([]),attrs:M(k0).catch([]).default([]),deviceNames:Y(s(),s()).default({}),kindLabels:Y(s(),s()).default({}),labels:UN.default({}),strings:d({empty:s().optional(),error:s().optional(),retry:s().optional(),end:s().optional(),loadOlder:s().optional()}).default({}),search:s().default(""),searchMode:KN.default("text"),semanticLimit:l().int().min(1).max(200).default(50),semanticMinScore:l().min(0).max(1).default(.2),sort:ZN.default("time"),filterDebug:E().default(!1),filterTrain:E().default(!1),filterFavourited:E().default(!1),showStationary:E().default(!1),reviewedTrackIds:M(s()).default([]),showAdminFlags:E().default(!1),sinceMs:l().int().nonnegative().optional(),untilMs:l().int().nonnegative().optional(),pageSize:l().int().min(1).max(500).default(vce),maxRows:l().int().min(1).max(5e3).default(yce),refreshMs:l().int().min(0).max(6e5).default(xce),maxAgeMs:l().int().min(6e4).default(kce),theme:QN.default("auto"),nativePullToRefresh:E().default(!1)}).superRefine(FN),YN=d({view:HN.optional(),rows:l().int().min(1).max(6).optional(),columns:WN.optional(),thumbSize:$N.optional(),fields:VN.partial().optional(),deviceIds:M(l().int().nonnegative()).optional(),classes:M(s()).optional(),attrs:M(k0).optional(),deviceNames:Y(s(),s()).optional(),kindLabels:Y(s(),s()).optional(),labels:UN.optional(),strings:d({empty:s().optional(),error:s().optional(),retry:s().optional(),end:s().optional(),loadOlder:s().optional()}).optional(),search:s().optional(),searchMode:KN.optional(),semanticLimit:l().int().min(1).max(200).optional(),semanticMinScore:l().min(0).max(1).optional(),sort:ZN.optional(),filterDebug:E().optional(),filterTrain:E().optional(),filterFavourited:E().optional(),showStationary:E().optional(),reviewedTrackIds:M(s()).optional(),showAdminFlags:E().optional(),sinceMs:l().int().nonnegative().nullable().optional(),untilMs:l().int().nonnegative().nullable().optional(),pageSize:l().int().min(1).max(500).optional(),maxRows:l().int().min(1).max(5e3).optional(),refreshMs:l().int().min(0).max(6e5).optional(),maxAgeMs:l().int().min(6e4).optional(),theme:QN.optional(),nativePullToRefresh:E().optional()});function M0(e){return e==="small"?80:e==="large"?132:106}function Mce(e,t=1){const n=Number.isFinite(t)&&t>0?t:1,a=Math.round(M0(e)*n);return Math.max(Cce,Math.min(Ace,a))}const Cce=64,Ace=320,Ep=3,Rp=14,Ece=4;function Rce(e){return M0(e)+Ep*2+Rp}function XN(e){if(e==null)return{ok:!1,error:"config is required"};const t=wce.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(n=>`${n.path.join(".")||"(root)"}: ${n.message}`).join("; ")}}function By(e,t){const n=t.fields!==void 0?{...e.fields,...t.fields}:e.fields,{sinceMs:a,untilMs:o,...p}=t,{sinceMs:f,untilMs:m,...h}=e,u=jC(a,f),x=jC(o,m);return{...h,...p,fields:n,...u!==void 0?{sinceMs:u}:{},...x!==void 0?{untilMs:x}:{}}}function jC(e,t){if(e!==null)return e??t}function _ce(e,t,n){const a=n[String(e)];return a!==void 0&&a.trim().length>0?a:t}const Tce={empty:"No events",error:"Couldn't load events",retry:"Retry",end:"·",loadOlder:"Load older events"};function Is(e,t){const n=e.strings[t];return n!==void 0&&n.trim().length>0?n:Tce[t]}const Ice="/addon/pipeline-analytics/event-media",PC=64,Nce=320;function Oce(e){return e.replace(/\/+$/,"")}function jce(e){const t=Math.round(e);return Number.isFinite(t)?Math.max(PC,Math.min(Nce,t)):PC}function JN(e,t,n){return`${Oce(e)}${Ice}/${t}?kind=thumbnailSmall&variant=thumb&size=${jce(n)}`}const Pce="audio";function nm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Dce(e){const t=new Map;if(!Array.isArray(e))return t;for(const n of e){if(!nm(n))continue;const a=n.kinds;if(Array.isArray(a))for(const o of a){if(!nm(o))continue;const p=o.kind;if(typeof p!="string"||p.length===0)continue;const f=o.parentKind;t.set(p,typeof f=="string"&&f.length>0?f:p)}}return t}function e5(e,t){return t.get(e)??e}const DC="audio-",zC="audio";function fu(e){const t=e.toLowerCase();return t.startsWith(DC)?t:`${DC}${t}`}function zce(e){const t=new Map;if(!Array.isArray(e))return t;for(const n of e){if(!nm(n))continue;const a=n.kinds;if(Array.isArray(a))for(const o of a){if(!nm(o))continue;const p=o.kind,f=o.iconId;typeof p!="string"||p.length===0||typeof f!="string"||f.length===0||t.set(p,f)}}return t}function Lce(e,t,n=!1){if(n){const o=t.get(e);if(o!==void 0)return o;if(e.toLowerCase()===zC)return zC;const p=fu(e);return t.get(p)??p}const a=e.toLowerCase();return t.get(e)??t.get(a)??a}function qce(e){const t=new Map;for(const[n,a]of Object.entries(e)){if(n.length===0||a.length===0)continue;t.set(n,a);const o=n.toLowerCase();t.has(o)||t.set(o,a)}return t}const C0=new Map;function _p(e,t){return t.get(e)??t.get(e.toLowerCase())??e}function t5(e,t){const n=fu(e);return t.get(n)??t.get(e)??e}const LC={background:"#09090b",card:"#18181b",cardHover:"#27272a",border:"#27272a",text:"#fafafa",textMuted:"#a1a1aa",skeleton:"#27272a",chip:"#3f3f46",colorScheme:"dark"},qC={background:"#ffffff",card:"#f4f4f5",cardHover:"#e4e4e7",border:"#e4e4e7",text:"#18181b",textMuted:"#71717a",skeleton:"#e4e4e7",chip:"#d4d4d8",colorScheme:"light"};function n5(e,t){return e==="light"?qC:e==="dark"||t?LC:qC}const Uy="#f472b6";function Bce(e,t=!1){if(t)return Uy;const n=e.toLowerCase();return n.includes("person")||n.includes("face")?"#38bdf8":n.includes("vehicle")||n.includes("car")||n.includes("truck")||n.includes("plate")?"#a78bfa":n.includes("animal")||n.includes("dog")||n.includes("cat")||n.includes("bird")?"#fbbf24":n.includes("package")||n.includes("parcel")?"#34d399":n.includes("audio")||n.includes("sound")?Uy:n.includes("motion")?"#94a3b8":"#71717a"}function Uce(e){return new Date(e).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}function Fce(e,t){const n=new Date(e),a=new Date(t),o=String(n.getHours()).padStart(2,"0"),p=String(n.getMinutes()).padStart(2,"0");if(n.getFullYear()===a.getFullYear()&&n.getMonth()===a.getMonth()&&n.getDate()===a.getDate())return`${o}:${p}`;const m=String(n.getDate()).padStart(2,"0"),h=String(n.getMonth()+1).padStart(2,"0");return`${m}/${h} ${o}:${p}`}const Hce=/[_\-/.]+/g;function a5(e){return e.toLowerCase().replace(Hce," ").replace(/\s+/g," ").trim()}function $ce(e){if(e===void 0)return[];const t=e.trim().toLowerCase();if(t.length===0)return[];const n=a5(e);return n===t||n.length===0?[t]:[t,n]}const _m=new Map,Qce=new Set(["plate-detection","plate-ocr","operator:plate-gallery"]),BC=new Set(["face-recognizer","face-embedding","operator:face-gallery"]),Vce=[];function ov(e,t){if(!A0(e))return!1;const n=e.stepId;return typeof n=="string"&&t.has(n)}function i5(e){return e.source==="audio"}function A0(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Nr(e){return typeof e=="string"&&e.length>0?e:void 0}function sv(e){if(!Array.isArray(e))return[];const t=[];for(const n of e)typeof n=="string"&&n.length>0&&!t.includes(n)&&t.push(n);return t}function Gce(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const a=A0(n)?Nr(n.label):void 0;a!==void 0&&!t.includes(a)&&t.push(a)}return t}function Zce(e,t){if(!A0(e))return null;const n=Nr(e.trackId),a=Nr(e.className);if(n===void 0||a===void 0||typeof e.deviceId!="number"||typeof e.firstSeen!="number"||typeof e.lastSeen!="number")return null;const o=Nr(e.label),p=Nr(e.subLabel),f=Nr(e.producingDeviceName),m=Nr(e.source),h=sv(e.classes);return{trackId:n,deviceId:e.deviceId,cameraName:t.get(e.deviceId)??`Camera ${e.deviceId}`,className:a,...o!==void 0?{label:o}:{},...p!==void 0?{subLabel:p}:{},...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:sv(e.zonesVisited),zoneNames:sv(e.zoneNames),classes:h.includes(a)?h:[a,...h],audioLabels:Gce(e.audioLabels),bestEventId:Nr(e.bestEventId)??n,...f!==void 0?{producingDeviceName:f}:{},...m!==void 0?{source:m}:{},...e.hasEmbeddedFace===!0||ov(e.subLabelMeta,BC)?{hasAssignableFace:!0}:{},...e.hasEmbeddedFace===!0&&!ov(e.subLabelMeta,BC)?{hasUnassignedFace:!0}:{},...ov(e.subLabelMeta,Qce)?{hasPlate:!0}:{},...e.debug===!0?{debug:!0}:{},...e.markForTrain===!0?{markForTrain:!0}:{},...e.favourited===!0?{favourited:!0}:{}}}function UC(e,t){if(!Array.isArray(e))return[];const n=[];for(const a of e){const o=Zce(a,t);o!==null&&n.push(o)}return n}function Kce(e,t){const n=new Set;for(const a of[e.className,...e.classes])a.length!==0&&(n.add(a),n.add(e5(a,t)));if(e.audioLabels.length>0){n.add(Pce);for(const a of e.audioLabels)n.add(fu(a))}return n}function Wce(e,t,n=_m){if(t.size===0)return!0;const a=Kce(e,n);for(const o of t)if(a.has(o))return!0;return!1}function Yce(e,t=_m){const n=new Set,a=o=>{for(const p of $ce(o))n.add(p)};for(const o of[e.className,...e.classes])a(o),o.length>0&&a(e5(o,t));a(e.label),a(e.subLabel),a(e.cameraName),a(e.producingDeviceName);for(const o of e.audioLabels)a(o),a(fu(o));for(const o of e.zoneNames)a(o);for(const o of[e.label,e.subLabel]){if(o===void 0)continue;const p=t.get(o.trim().toLowerCase());p!==void 0&&a(p)}return n}function Xce(e,t,n=_m){const a=t.trim().toLowerCase();if(a.length===0)return!0;const o=a5(t);for(const p of Yce(e,n))if(p.includes(a)||o.length>0&&p.includes(o))return!0;return!1}function Jce(e,t){return!!(t.size===0||t.has("face")&&e.hasAssignableFace===!0||t.has("plate")&&e.hasPlate===!0)}function eue(e,t={}){const n=t.debug===!0,a=t.train===!0,o=t.favourited===!0;if(!n&&!a&&!o)return!0;const p=t.reviewedTrackIds?.includes(e.trackId)===!0;return!!(n&&e.debug===!0&&!p||a&&e.markForTrain===!0||o&&e.favourited===!0)}function FC(e,t,n,a=_m,o=Vce,p={}){const f=new Set(t),m=new Set(o);return e.filter(h=>Wce(h,f,a)&&Jce(h,m)&&Xce(h,n,a)&&eue(h,p))}function tue(e,t=C0){return e.producingDeviceName!==void 0?{text:_p(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:_p(e.label,t),tier:"kind"}:{text:_p(e.className,t),tier:"class"}}function nue(e,t,n,a=C0){if(t)return"";const o=[n];for(const p of e.audioLabels){if(p===e.className||p===e.label)continue;const f=t5(p,a);o.includes(f)||o.push(f)}return o.join(" · ")}function HC(e,t){let n=!1;const a=e.map(o=>{const p=t.get(o.deviceId);return p===void 0||p===o.cameraName?o:(n=!0,{...o,cameraName:p})});return n?a:e}function $C(e,t){if(Object.keys(t).length===0)return e;let a=!1;const o=e.map(p=>{const f=t[p.trackId];if(f===void 0)return p;const m=iue(p,f);return m!==p&&(a=!0),m});return a?o:e}function aue(e){const{debug:t,markForTrain:n,favourited:a,...o}=e;return o}function iue(e,t){const n=t.debug===!0?!0:t.debug===!1?void 0:e.debug,a=t.markForTrain===!0?!0:t.markForTrain===!1?void 0:e.markForTrain,o=t.favourited===!0?!0:t.favourited===!1?void 0:e.favourited;return n===e.debug&&a===e.markForTrain&&o===e.favourited?e:{...aue(e),...n===!0?{debug:!0}:{},...a===!0?{markForTrain:!0}:{},...o===!0?{favourited:!0}:{}}}function rue(e){const t=e.filter(n=>n.isCamera===!0).map(n=>n.id);return t.length>0?t:e.map(n=>n.id)}const Fy=11,QC=9,lv=3,oue=8,sue=12,lue=24,cue=.58,uue=.85;function due(e,t){return[...e].length*t*cue}function pue(e){return Math.max(lue,e-oue-sue)}function VC(e,t,n){const a=pue(t),o=n.maxLines===1?a:a*n.maxLines*uue;return due(e,n.fontSizePx)<=o}function mue(e,t){for(let n=1;n<=lv;n+=1){const a={fontSizePx:Fy,maxLines:n};if(VC(e,t,a))return a}for(let n=Fy-1;n>=QC;n-=1){const a={fontSizePx:n,maxLines:lv};if(VC(e,t,a))return a}return{fontSizePx:QC,maxLines:lv}}const fue=1e4;function r5(){try{return window.parent!==window}catch{return!0}}let Hy=null;function o5(e){Hy=e}function hue(e){if(Hy===null||typeof e!="object"||e===null)return e;const t=e;if(t.type!=="log")return e;const n=typeof t.data=="object"&&t.data!==null?t.data:{};return{...t,data:{deviceId:Hy,...n}}}function an(e){const t=hue(e),n=window.ReactNativeWebView;if(n){n.postMessage(JSON.stringify(t));return}r5()&&window.parent.postMessage(t,"*")}function hu(e){const t=n=>{const a=n.data;if(typeof a!="object"||a===null)return;const o=a;o.type!=="embed-command"||typeof o.command!="object"||o.command===null||e(o.command)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}function gue(e,t,n,a,o){const p=t();if(p!=null)return Promise.resolve(n(p));if(o?.urlFirst===!0){const f=a!==void 0?a():null;if(f!==null)return Promise.resolve(f)}if(!r5()){const f=a!==void 0?a():null;return f!==null?Promise.resolve(f):Promise.resolve({ok:!1,error:`config global for mode "${e}" is not set`})}return new Promise(f=>{let m;const h=u=>{const x=u.data;if(typeof x!="object"||x===null)return;const w=x;w.type==="embed-config"&&(clearTimeout(m),window.removeEventListener("message",h),f(n(w.config)))};window.addEventListener("message",h),m=setTimeout(()=>{window.removeEventListener("message",h),f({ok:!1,error:"config handshake timed out"})},fue),window.parent.postMessage({type:"embed-ready",mode:e},"*")})}function Tm(e,t,n,a,o){const[p,f]=T.useState(null),m=T.useRef(t);m.current=t;const h=T.useRef(n);h.current=n;const u=T.useRef(a);u.current=a;const x=o?.urlFirst===!0;return T.useEffect(()=>{let w=!0;return gue(e,()=>m.current(),C=>h.current(C),()=>u.current!==void 0?u.current():null,{urlFirst:x}).then(C=>{w&&f(C)}),()=>{w=!1}},[e,x]),p}const Ga=1,vue=["window","sort","semantic-search","macro-classes","device-names","kind-labels","heartbeat","track-list","attr-filters","flag-filters","debug-status","native-pull-refresh","track-list-delta"];function yue(e){return{v:Ga,type:"ready",view:e,features:[...vue]}}function bue(e){return{v:Ga,type:"error",message:e}}function Tp(e,t){return t!==void 0?{v:Ga,type:"state",state:e,message:t}:{v:Ga,type:"state",state:e}}function Sue(e){return{v:Ga,type:"trackClick",...e}}function xue(e,t){return{v:Ga,type:"trackList",tracks:e,seq:t}}function kue(e){return{v:Ga,type:"trackListDelta",...e}}function GC(e,t,n,a="feed"){return{v:Ga,type:"countChanged",loaded:e,shown:t,hasMore:n,mode:a}}function wue(){return{v:Ga,type:"heartbeat"}}function Mue(e){return{v:Ga,type:"scroll",atTop:e}}function Cue(){return{v:Ga,type:"refreshed"}}function Da(e){an(e)}function mi(e,t,n="feed"){an({type:"log",scope:n,msg:e,...t!==void 0?{data:t}:{}})}const Aue=j(["full","delta"]),Eue=d({debug:E().optional(),markForTrain:E().optional(),favourited:E().optional()}),Rue=Y(s(),Eue);function Sc(e){if(typeof e!="object"||e===null)return null;const t=e,n=t.type;if(n==="refresh"||n==="reload"||n==="loadMore"||n==="scrollToTop"||n==="ping")return{type:n};if(n==="setWindow"){const o=_ue.safeParse(t);return o.success?{type:"setWindow",...o.data.sinceMs!==void 0?{sinceMs:o.data.sinceMs}:{},...o.data.untilMs!==void 0?{untilMs:o.data.untilMs}:{}}:null}if(n==="setTrackListMode"){const o=Aue.safeParse(t.mode);return o.success?{type:"setTrackListMode",mode:o.data}:null}if(n==="setTrackFlagPatches"){const o=Rue.safeParse(t.patches);return o.success?{type:"setTrackFlagPatches",patches:o.data}:null}if(n!=="setConfig")return null;const a=YN.safeParse(t.patch);return a.success?{type:"setConfig",patch:a.data}:null}const _ue=d({sinceMs:l().int().nonnegative().nullable().optional(),untilMs:l().int().nonnegative().nullable().optional()});function Tue(e){return{...e.sinceMs!==void 0?{sinceMs:e.sinceMs}:{},...e.untilMs!==void 0?{untilMs:e.untilMs}:{}}}const Iue={blockedMs:0,maxLagMs:0,samples:0};function Nue(e,t,n){if(n<=t)return Iue;let a=0,o=0,p=0;for(const f of e){const m=f.at-f.lagMs,h=Math.min(f.at,n)-Math.max(m,t);h<=0||(a+=h,o=Math.max(o,f.lagMs),p+=1)}return{blockedMs:Math.round(a),maxLagMs:Math.round(o),samples:p}}function $y(e,t){const n=Math.min(Math.round(e),t.blockedMs);return{ms:Math.round(e),blockedMs:n,netMs:Math.max(0,Math.round(e)-n),maxLagMs:t.maxLagMs,lagSamples:t.samples}}const Oue=250,ZC=600,jue=8;let Ds=[],KC=null;function Pue(e){e.lagMs<jue||(Ds.push(e),Ds.length>ZC&&(Ds=Ds.slice(Ds.length-ZC)))}function Qy(e,t){return Nue(Ds,e,t)}function Due(e=Oue,t=()=>performance.now(),n=(a,o)=>{const p=setInterval(a,o);return()=>clearInterval(p)}){if(KC!==null)return;let a=t()+e;KC={stop:n(()=>{const p=t();Pue({at:p,lagMs:Math.max(0,p-a)}),a=p+e},e)}}function zue(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 Lue(e,t){let n=null;for(const a of e)a.startTime+1<t||(n===null||a.startTime<n.startTime)&&(n=a);return n}function que(){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:(n,a)=>t.call(performance,n,a)}}function Bue(e,t,n=que()){if(n===null)return null;try{const a=Lue(n.getEntriesByName(e,"resource"),t);return a===null?null:zue(a)}catch{return null}}const Uue=250,Gi=new Map,cv=new Map,Fue=6,Hue=1e4,$ue=5e3,uv=[250,750];let dv=40;const WC=32;function Que(e){try{const t=new URL(e),n=t.pathname.lastIndexOf("/"),a=n>=0?`${t.pathname.slice(0,n)}/<id>`:t.pathname;return{origin:t.origin,path:a,query:t.search}}catch{const t=e.slice(0,WC);return{origin:"(unparseable)",path:e.length>WC?`${t}…`:t,query:""}}}function Vue(e){return e instanceof Error?{errorName:e.name,errorMessage:e.message}:{errorName:"unknown",errorMessage:String(e)}}let am=0,s5=[];async function Gue(){if(am<Fue){am+=1;return}await new Promise(e=>{s5.push(e)})}function Zue(){const e=s5.shift();if(e!==void 0){e();return}am=Math.max(0,am-1)}function Kue(e,t){for(Gi.set(e,t);Gi.size>Uue;){const n=Gi.keys().next();if(n.done===!0)break;const a=Gi.get(n.value);Gi.delete(n.value),a!==void 0&&URL.revokeObjectURL(a)}}async function l5(e,t){const n=Gi.get(e);if(n!==void 0)return Gi.delete(e),Gi.set(e,n),{status:"ready",src:n};const a=cv.get(e);if(a!==void 0)return a;const o=(async()=>{const p=performance.now(),f=Que(e);let m={lastStatus:null,errorName:null,errorMessage:null},h=0;try{for(let u=0;u<=uv.length;u+=1){const x=performance.now();await Gue(),h+=performance.now()-x;const w=performance.now(),C=new AbortController,A=setTimeout(()=>C.abort(),Hue);try{const I=await fetch(e,{headers:hce(t),signal:C.signal});if(I.ok){const O=Math.round(performance.now()-w),D=await I.blob(),z=Math.round(performance.now()-p),B=Math.round(performance.now()-w),q=URL.createObjectURL(D);if(Kue(e,q),dv>0||z>=500){dv=Math.max(0,dv-1);const G=Bue(e,w),ae=$y(performance.now()-w,Qy(w,performance.now()));mi("thumbnail ready",{ms:z,queuedMs:Math.round(h),headersMs:O,blobMs:B-O,blockedMs:ae.blockedMs,maxLagMs:ae.maxLagMs,netTotalMs:G?.totalMs??null,netQueuedMs:G?.queuedMs??null,netTtfbMs:G?.ttfbMs??null,bytes:D.size,attempt:u+1,serverTiming:I.headers?.get("server-timing")??null},"media")}return{status:"ready",src:q}}if(I.status===401||I.status===403||I.status===404)return mi("thumbnail missing",{ms:Math.round(performance.now()-p),queuedMs:Math.round(h),status:I.status,attempt:u+1,...f},"media"),{status:"missing"};m={lastStatus:I.status,errorName:null,errorMessage:null}}catch(I){m={lastStatus:null,...Vue(I)}}finally{clearTimeout(A),Zue()}const R=uv[u];R!==void 0&&await new Promise(I=>setTimeout(I,R))}return mi("thumbnail transient failure",{ms:Math.round(performance.now()-p),queuedMs:Math.round(h),attempts:uv.length+1,...m,...f},"media"),{status:"transient-failure"}}finally{cv.delete(e)}})();return cv.set(e,o),o}async function Wue(e,t){const n=await l5(e,t);return n.status==="ready"?n.src:null}function Yue(e,t){const[n,a]=T.useState({status:"loading"}),[o,p]=T.useState(0);return T.useEffect(()=>{if(e===null){a({status:"loading"});return}const f=Gi.get(e);if(f!==void 0){a({status:"ready",src:f});return}let m=!0,h;return a({status:"loading"}),l5(e,t).then(u=>{if(m){if(u.status==="ready"){a({status:"ready",src:u.src});return}if(u.status==="missing"){a({status:"failed"});return}h=setTimeout(()=>p(x=>x+1),$ue)}}),()=>{m=!1,h!==void 0&&clearTimeout(h)}},[e,t,o]),n}function Xue(e){const t=e?.clientHeight??0;return t>0?t:600}function Jue(e,t){const{root:n,disabled:a}=t,[o,p]=T.useState(a===!0),f=T.useRef(o);return f.current=o,T.useEffect(()=>{if(f.current)return;if(a===!0){p(!0);return}const m=e.current;if(!m||typeof IntersectionObserver!="function"){p(!0);return}const h=new IntersectionObserver(u=>{u.some(x=>x.isIntersecting)&&(p(!0),h.disconnect())},{root:n,rootMargin:`${Xue(n)}px`});return h.observe(m),()=>h.disconnect()},[e,n,a]),o}const Yd={display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:14,height:14,padding:"0 3px",borderRadius:4,background:"#000000B3",color:"#fff",fontSize:9,fontWeight:700,lineHeight:"14px",letterSpacing:.2},ede=T.memo(function({row:t,serverUrl:n,token:a,thumbPx:o,width:p,heroPx:f,fields:m,palette:h,nowMs:u,variant:x,iconId:w,kindLabels:C=C0,labels:A=tm,scrollRoot:R,eagerImages:I,showAdminFlags:O,onClick:D}){const z=T.useRef(null),q=Jue(z,{root:R,...I===!0?{disabled:!0}:{}})?JN(n,t.bestEventId,o):null,G=Yue(q,a),ae=Bce(t.className,i5(t)),Q=x==="reel",H=f+Ep*2+Rp,oe=tue(t,C),we=oe.tier!=="class",Me=!we,Ae=mue(oe.text,f),Ce=m.label,re=nue(t,Ce,oe.text,C),Te=F2(w),F=v.jsxs("div",{style:{position:"relative",width:Q?f:"100%",height:Q?f:void 0,aspectRatio:Q?void 0:"1 / 1",borderRadius:10,overflow:"hidden",background:h.skeleton,border:`1px solid ${h.border}`,boxSizing:"border-box",flex:"0 0 auto"},children:[v.jsx("div",{className:G.status==="loading"?"events-skeleton":void 0,"data-testid":"card-image-backing",style:{position:"absolute",inset:0,background:G.status==="failed"?`${ae}22`:h.skeleton,boxShadow:`inset 0 0 0 1px ${h.border}`}}),G.status==="ready"?v.jsx("img",{src:G.src,alt:"",draggable:!1,style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover",display:"block"}}):null,m.label&&v.jsxs("div",{style:{position:"absolute",left:4,right:4,bottom:4,display:"flex",flexWrap:Q?"nowrap":"wrap",gap:3,alignItems:"center",pointerEvents:"none"},children:[Me&&v.jsx("span",{"data-testid":"card-class-glyph",title:_p(t.className,C),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",background:`${ae}E6`,color:"#fff",borderRadius:4,padding:"2px 4px",flex:"0 0 auto"},children:v.jsx(Te,{size:13,color:"#fff"})}),we&&v.jsx("span",{"data-testid":"card-title",title:oe.fullText??oe.text,style:{background:"#000000B3",color:"#fff",fontSize:Q?Fy:Ae.fontSizePx,fontWeight:700,lineHeight:1.35,padding:"2px 6px",borderRadius:4,overflow:"hidden",minWidth:0,...Q?{textOverflow:"ellipsis",whiteSpace:"nowrap"}:{display:"-webkit-box",WebkitLineClamp:Ae.maxLines,WebkitBoxOrient:"vertical",whiteSpace:"normal",overflowWrap:"anywhere"}},children:oe.text}),t.hasUnassignedFace===!0&&v.jsxs("span",{"data-testid":"card-face-unassigned",title:A.unassignedFace,style:{display:"inline-flex",alignItems:"center",gap:3,background:"#000000B3",color:"#fff",fontSize:11,fontWeight:700,lineHeight:1.35,padding:"2px 6px",borderRadius:4,flex:"0 0 auto"},children:[v.jsx(ace,{size:13,color:"#fff"}),"?"]}),!Q&&t.audioLabels.filter(fe=>fe!==t.className&&fe!==t.label).map(fe=>{const L=fu(fe),ee=F2(L);return v.jsx("span",{title:t5(fe,C),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",background:`${Uy}E6`,color:"#fff",borderRadius:4,padding:"2px 4px",flex:"0 0 auto"},children:v.jsx(ee,{size:13,color:"#fff"})},`audio-${fe}`)})]}),(O===!0&&(t.debug===!0||t.reviewed===!0||t.markForTrain===!0)||t.favourited===!0)&&v.jsxs("span",{"data-testid":"card-flags",style:{position:"absolute",top:4,right:m.badges&&t.active?16:4,display:"inline-flex",gap:2,zIndex:2},children:[O===!0&&t.reviewed===!0&&v.jsx("span",{title:A.reviewed,style:Yd,children:"✓"}),O===!0&&t.debug===!0&&t.reviewed!==!0&&v.jsx("span",{title:A.debug,style:Yd,children:"D"}),O===!0&&t.markForTrain===!0&&v.jsx("span",{title:A.train,style:Yd,children:"T"}),t.favourited===!0&&v.jsx("span",{title:A.favourite,style:{...Yd,color:"#fbbf24"},children:"★"})]}),m.badges&&t.active&&v.jsx("span",{title:A.active,style:{position:"absolute",top:4,right:4,width:8,height:8,borderRadius:999,background:"#22c55e",boxShadow:"0 0 0 2px rgba(0,0,0,0.35)"}}),m.badges&&!Q&&t.importance!==void 0&&v.jsxs("span",{"data-testid":"card-importance",style:{position:"absolute",top:4,left:4,display:"inline-flex",alignItems:"center",gap:2,background:"#000000B3",color:"#fff",fontSize:10,fontWeight:700,fontVariantNumeric:"tabular-nums",padding:"1px 5px",borderRadius:8},children:["★",Math.round(t.importance*100)]})]});if(Q)return v.jsxs("button",{ref:z,type:"button",onClick:()=>D(t),"data-track-id":t.trackId,"data-device-id":t.deviceId,style:{width:p,height:H,minWidth:p,minHeight:H,display:"flex",flexDirection:"column",alignItems:"center",padding:0,border:"none",background:"transparent",cursor:"pointer",font:"inherit",color:h.text,boxSizing:"border-box",contain:"layout paint",overflow:"hidden"},children:[F,v.jsxs("div",{style:{paddingTop:Ep,paddingBottom:Ep,paddingLeft:4,paddingRight:4,display:"flex",flexDirection:"column",alignItems:"center",maxWidth:"100%",boxSizing:"border-box"},children:[m.camera&&t.producingDeviceName!==void 0&&v.jsx("span",{style:{fontSize:11,lineHeight:`${Rp}px`,fontWeight:600,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.producingDeviceName}),m.time&&v.jsx("span",{"data-testid":"card-time",style:{fontSize:11,lineHeight:`${Rp}px`,color:h.textMuted,fontVariantNumeric:"tabular-nums",whiteSpace:"nowrap"},children:Uce(t.lastSeen)})]})]});const ue=m.camera,ke=t.cameraName,Ee=ue||m.time||m.sublabel&&re.length>0;return v.jsxs("button",{ref:z,type:"button",onClick:()=>D(t),"data-track-id":t.trackId,"data-device-id":t.deviceId,style:{width:p,display:"flex",flexDirection:"column",gap:4,padding:0,border:"none",background:"transparent",cursor:"pointer",textAlign:"left",font:"inherit",color:h.text,boxSizing:"border-box"},children:[F,Ee&&v.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:1,minWidth:0,paddingTop:2,paddingBottom:2},children:[m.sublabel&&re.length>0&&v.jsx("span",{style:{fontSize:11,color:h.textMuted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:re}),ue&&v.jsx("span",{"data-testid":"card-camera",title:ke,style:{fontSize:12,fontWeight:600,lineHeight:"15px",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:ke}),m.time&&v.jsx("span",{"data-testid":"card-time",style:{fontSize:11,lineHeight:"14px",color:h.textMuted,fontVariantNumeric:"tabular-nums",whiteSpace:"nowrap",flex:"0 0 auto"},children:Fce(t.lastSeen,u)}),m.badges&&t.zonesVisited.length>0&&v.jsx("span",{style:{fontSize:10,color:h.textMuted,background:h.chip,borderRadius:5,padding:"1px 5px",alignSelf:"flex-start",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"100%"},children:t.zonesVisited.join(" · ")})]})]})});function tde(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 nde=2e3,ade=1e3;function YC(e,t){const n=Math.max(1,Math.floor(e)),a=Math.max(1,Math.floor(t)),o=Math.max(1,Math.floor(nde/a));return Math.min(n,ade,o)}function E0(e,t){return e.lastSeen!==t.lastSeen?t.lastSeen-e.lastSeen:e.trackId===t.trackId?0:e.trackId<t.trackId?1:-1}const Mc={rows:[],cursor:null,exhausted:!1,rebuild:null},ide=8;function Vy(e,t){const n=new Map;for(const a of e)n.set(a.trackId,a);for(const a of t)n.set(a.trackId,a);return[...n.values()].sort(E0)}function rde(e,t,n){const a=e.rebuild;if(a===null)return{rows:Vy(e.rows,t),cursor:n,exhausted:n===null,rebuild:null};const o=Vy(a.rows,t),p=a.pages+1,f=o.length>=a.floor;return n===null||f||p>=ide?{rows:o,cursor:n,exhausted:n===null,rebuild:null}:{...e,rebuild:{rows:o,cursor:n,exhausted:!1,floor:a.floor,pages:p}}}function ode(e){return e.rows.length===0?Mc:{...e,rebuild:{rows:[],cursor:null,exhausted:!1,floor:e.rows.length,pages:0}}}function sde(e){return e.rebuild===null?e:{...e,rebuild:null}}function lde(e){return e.rebuild!==null}function XC(e){return e.rebuild!==null?e.rebuild.cursor:e.cursor}function cde(e,t,n){const a=new Set(e.rows.map(p=>p.trackId));let o=0;for(const p of t)a.has(p.trackId)||(o+=1);return{state:{...e,rows:Vy(e.rows,t)},gap:n!==null,deltaCursor:n,added:o}}function ude(e){const t=e.rows[0];return t!==void 0?t.lastSeen:null}function c5(e,t){const n=e.rebuild??e;return n.exhausted?"exhausted":n.rows.length<Math.max(1,t)?"more":"ceiling"}function JC(e,t){return c5(e,t)==="more"}function dde(e,t){return Math.max(0,e-Math.max(0,t))}function pde(e){const t=e.sinceMs??dde(e.anchorMs,e.maxAgeMs);return e.untilMs!==void 0?{since:t,until:e.untilMs}:{since:t}}function mde(e,t){return e===void 0||e>t}function u5(e,t){return t==="time"?e:[...e].sort((n,a)=>{const o=n.importance??-1,p=a.importance??-1;return o!==p?p-o:E0(n,a)})}const eA=200,fde=45;function Gy(e){return{trackId:e.trackId,deviceId:e.deviceId,bestEventId:e.bestEventId,className:e.className,firstSeen:e.firstSeen,lastSeen:e.lastSeen}}function Zy(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function hde(e,t){const n=t.map(A=>A.trackId);if(Zy(e,n))return{kind:"unchanged"};if(e.length===0)return{kind:"reset"};const a=new Set(e);let o=n.length-1,p=e.length-1,f=n.length;for(;o>=0&&!a.has(n[o]);)f=o,o-=1;const m=[];for(;o>=0&&p>=0;){if(n[o]===e[p]){o-=1,p-=1;continue}m.push(e[p]),p-=1}const h=o+1;for(;p>=0;)m.push(e[p]),p-=1;const u=new Set(m),x=[...n.slice(0,h),...e.filter(A=>!u.has(A)),...n.slice(f)];if(!Zy(x,n))return{kind:"reset"};const w=h+(n.length-f);return eA*w+fde*m.length>=eA*n.length?{kind:"reset"}:{kind:"delta",prepend:t.slice(0,h).map(Gy),append:f===n.length?[]:t.slice(f).map(Gy),removeIds:m}}const gde={seq:0,sentIds:null,mode:"full"};function Ip(e,t,n){const a=e.seq+1;return{state:{seq:a,sentIds:n,mode:e.mode},message:xue(t.map(Gy),a)}}function vde(e,t){const n=t.map(p=>p.trackId);if(e.sentIds===null)return Ip(e,t,n);if(e.mode==="full")return Zy(e.sentIds,n)?{state:e,message:null}:Ip(e,t,n);const a=hde(e.sentIds,t);if(a.kind==="unchanged")return{state:e,message:null};if(a.kind==="reset")return Ip(e,t,n);const o=e.seq+1;return{state:{seq:o,sentIds:n,mode:e.mode},message:kue({seq:o,baseSeq:e.seq,prepend:a.prepend,append:a.append,removeIds:a.removeIds,count:n.length})}}function yde(e,t,n){const a=n.map(o=>o.trackId);return Ip({...e,mode:t},n,a)}function bde(e){let t=gde,n=[];const a=o=>{t=o.state,o.message!==null&&e(o.message)};return{report:o=>{n=o,a(vde(t,o))},setMode:o=>{a(yde(t,o,n))}}}function Sde(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ns(e){return typeof e=="string"&&e.length>0?e:void 0}function xde(e,t){if(!Sde(e))return null;const n=Ns(e.id),a=Ns(e.className);if(n===void 0||a===void 0||typeof e.deviceId!="number"||typeof e.timestamp!="number"||typeof e.score!="number")return null;const o=Ns(e.trackId),p=Ns(e.mediaKey),f=Ns(e.label),m=Ns(e.subLabel);return{trackId:o??n,deviceId:e.deviceId,cameraName:t.get(e.deviceId)??`Camera ${e.deviceId}`,className:a,...f!==void 0?{label:f}:{},...m!==void 0?{subLabel:m}:{},...typeof e.importance=="number"?{importance:e.importance}:{},firstSeen:e.timestamp,lastSeen:e.timestamp,state:"idle",active:!1,zonesVisited:[],zoneNames:[],classes:[a],audioLabels:[],bestEventId:p??o??n,score:e.score}}function kde(e,t){if(!Array.isArray(e))return[];const n=new Map;for(const a of e){const o=xde(a,t);if(o===null)continue;const p=n.get(o.trackId);(p===void 0||o.score>p.score)&&n.set(o.trackId,o)}return[...n.values()].sort((a,o)=>a.score!==o.score?o.score-a.score:o.lastSeen-a.lastSeen)}function wde(e,t,n){const a=new Map;for(const o of e)a.set(o.trackId,o);for(const o of t)a.set(o.trackId,o);return u5([...a.values()].sort(E0),n)}function Mde(e,t){if(e.length===0)return e;const n=Math.max(1,Math.floor(t.rowsPerColumn)),a=Math.max(1,t.cardWidth+t.gap),o=Math.max(0,Math.floor(Math.max(0,t.scrollLeft)/a)),p=t.viewportWidth>0?t.viewportWidth:t.cardWidth,f=Math.max(o+1,Math.ceil((Math.max(0,t.scrollLeft)+p*2)/a));return e.slice(o*n,Math.min(e.length,f*n))}const Cde=34;function Ade(e){const t=Math.max(0,e.gap),n=Math.max(1,e.cardWidth),a=Math.max(0,e.viewportWidth),o=e.columns??"auto",p=o==="auto"?Math.max(1,Math.floor((a+t)/(n+t))):Math.max(1,Math.floor(o)),f=a>0?(a-(p-1)*t)/p:n;return{columns:p,columnWidth:f,rowStridePx:Math.max(1,f+Cde+t)}}const Ede=2,Rde={startRow:0,endRow:0,padTopPx:0,padBottomPx:0,totalPx:0};function _de(e){const t=Math.max(0,Math.floor(e.rowCount));if(t===0)return Rde;const n=e.estimatedRowPx>0?e.estimatedRowPx:1,a=O=>{const D=e.measuredPx.get(O);return D!==void 0&&D>0?D:n};let o=0;for(let O=0;O<t;O+=1)o+=a(O);if(e.viewportHeight<=0)return{startRow:0,endRow:t,padTopPx:0,padBottomPx:0,totalPx:o};const p=Math.max(0,e.scrollTop),f=p+e.viewportHeight;let m=0,h=0;for(;m<t-1&&h+a(m)<=p;)h+=a(m),m+=1;let u=m,x=h;for(;u<t&&x<f;)x+=a(u),u+=1;const w=Math.max(0,Math.floor(e.overscanRows??Ede)),C=Math.max(0,m-w),A=Math.min(t,u+w);let R=0;for(let O=0;O<C;O+=1)R+=a(O);let I=0;for(let O=C;O<A;O+=1)I+=a(O);return{startRow:C,endRow:A,padTopPx:R,padBottomPx:Math.max(0,o-R-I),totalPx:o}}function Tde(e,t){let n=0,a=0;for(const o of e.values())o>0&&(n+=o,a+=1);return a===0?Math.max(1,t):Math.max(1,n/a)}const Ide=24,Nde=2;function Ode(e,t,n){if(e.length===0)return e;const a=Math.max(1,Math.floor(n)),o=Math.max(0,t.startRow)*a,p=Math.max(1,t.endRow-t.startRow+Nde),f=Math.min(e.length,o+Math.min(p*a,Ide));return e.slice(o,f)}function jde(e){const{rowCount:t,scrollTop:n,viewportHeight:a,fallbackRowPx:o,geometryKey:p}=e,f=T.useRef(new Map),m=T.useRef(new Map),[h,u]=T.useState(()=>new Map),x=T.useRef(p);T.useEffect(()=>{x.current!==p&&(x.current=p,m.current=new Map,u(new Map))},[p]);const w=T.useCallback(A=>{const R=m.current.get(A);if(R!==void 0)return R;const I=O=>{O===null?f.current.delete(A):f.current.set(A,O)};return m.current.set(A,I),I},[]);return T.useLayoutEffect(()=>{let A=null;for(const[R,I]of f.current){const O=Math.round(I.getBoundingClientRect().height);O<=0||h.get(R)!==O&&(A??=new Map(h),A.set(R,O))}A!==null&&u(A)}),{window:T.useMemo(()=>_de({rowCount:t,scrollTop:n,viewportHeight:a,estimatedRowPx:Tde(h,o),measuredPx:h}),[t,n,a,o,h]),measureRow:w}}const Pde=1,Dde=oce,zde=["label","sublabel","camera","time","badges"];function Os(e,t){const n=e.get(t);if(n===null||n.trim()==="")return;const a=Number.parseInt(n,10);return Number.isFinite(a)?a:void 0}function Lde(e){if(e===null)return;if(e.trim()==="")return[];const t=[];for(const n of e.split(",")){const a=Number.parseInt(n.trim(),10);Number.isFinite(a)&&a>=0&&t.push(a)}return t}function Ky(e){if(e!==null)return e.trim()===""?[]:e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function qde(e){if(e===null)return;const t=new Set((Ky(e)??[]).map(a=>a.toLowerCase())),n={};for(const a of zde)n[a]=t.has(a.toLowerCase());return n}function Bde(e,t){const n=e.startsWith("?")?e.slice(1):e;for(const a of n.split("&")){if(a.length===0)continue;const o=a.indexOf("=");if((o===-1?a:a.slice(0,o))===t)return o===-1?"":a.slice(o+1)}return null}function Ude(e){if(e===null)return;const t={};if(e.trim()==="")return t;for(const n of e.split(",")){const a=n.indexOf(":");if(a<=0)continue;const o=n.slice(0,a).trim();if(!/^\d+$/.test(o))continue;let p;try{p=decodeURIComponent(n.slice(a+1))}catch{continue}p.trim().length!==0&&(t[o]=p)}return t}function tA(e,t){const n=e.get(t);if(n===null)return;if(n.trim()==="")return null;const a=Number.parseInt(n,10);return Number.isFinite(a)&&a>=0?a:void 0}function Fde(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 Hde(e){const t=e.startsWith("#")?e.slice(1):e;if(t.length===0)return null;const n=new URLSearchParams(t).get("t");return n!==null&&n.length>0?n:null}function d5(e){const t=new URLSearchParams(e.startsWith("?")?e.slice(1):e),n=t.get("v");if(n===null)return null;if(Number.parseInt(n,10)!==Pde)return{ok:!1,error:`unsupported events URL version "${n}"`};const o={},p=t.get("view");p!==null&&(o.view=p);const f=Os(t,"rows");f!==void 0&&(o.rows=f);const m=Fde(t.get("cols"));m!==void 0&&(o.columns=m);const h=t.get("thumb");h!==null&&(o.thumbSize=h);const u=qde(t.get("fields"));u!==void 0&&(o.fields=u);const x=Lde(t.get("devices"));x!==void 0&&(o.deviceIds=x);const w=Ky(t.get("classes"));w!==void 0&&(o.classes=w);const C=Ky(t.get("attrs"));C!==void 0&&(o.attrs=C);const A=t.get("q");A!==null&&(o.search=A);const R=Os(t,"page");R!==void 0&&(o.pageSize=R);const I=Os(t,"max");I!==void 0&&(o.maxRows=I);const O=Os(t,"refresh");O!==void 0&&(o.refreshMs=O);const D=Os(t,"age");D!==void 0&&(o.maxAgeMs=D);const z=t.get("theme");z!==null&&(o.theme=z);const B=t.get("sort");B!==null&&(o.sort=B);const q=t.get("smode");q!==null&&(o.searchMode=q);const G=Os(t,"slimit");G!==void 0&&(o.semanticLimit=G);const ae=t.get("sscore");if(ae!==null&&ae.trim()!==""){const Me=Number.parseFloat(ae);Number.isFinite(Me)&&(o.semanticMinScore=Me)}const Q=tA(t,"since");Q!==void 0&&(o.sinceMs=Q);const H=tA(t,"until");H!==void 0&&(o.untilMs=H);const oe=Ude(Bde(e,"names"));oe!==void 0&&(o.deviceNames=oe);const we=YN.safeParse(o);return we.success?{ok:!0,patch:we.data}:{ok:!1,error:we.error.issues.map(Me=>`${Me.path.join(".")||"(root)"}: ${Me.message}`).join("; ")}}function $de(e,t,n,a=""){const o=d5(e);if(o===null)return null;if(!o.ok)return{ok:!1,error:o.error};const p=gce(n,a,Dde),f=Hde(t);return f===null&&!w0(p)?null:XN({serverUrl:p,...f!==null?{token:f}:{},fields:GN,...o.patch})}function Qde(){const e=$de(location.search,location.hash,location.origin,location.pathname);return e!==null&&location.hash!==""&&history.replaceState(null,"",location.pathname+location.search),e}function Vde(){const e=d5(location.search);return e===null||!e.ok?null:e.patch}function Gde(e,t){return!e.ok||t===null?e:{ok:!0,config:By(e.config,t)}}const nA=5,aA=3,Zde=[300,900];let Kde=0;function Wde(e){if(typeof e!="object"||e===null)return!1;const t=e;return"tracks"in t&&(t.nextCursor===null||typeof t.nextCursor=="string")}const Yde=/^(10\.|127\.|192\.168\.|169\.254\.|172\.(1[6-9]|2\d|3[01])\.)/;function Xde(e){let t;try{const p=w0(e)&&typeof location<"u"?location.href:void 0;t=new URL(e,p).host}catch{return"unknown:(unparseable)"}const n=t.trim().toLowerCase().replace(/^\[([^\]]*)\].*$/,"$1"),a=n.lastIndexOf(":"),o=a!==-1&&n.indexOf(":")===a?n.slice(0,a):n;return o==="localhost"||o==="::1"||o.startsWith("127.")?`loopback:${t}`:Yde.test(o)||/^f[cd][0-9a-f]{2}:/.test(o)||o.startsWith("fe80:")||o.endsWith(".local")?`lan:${t}`:o.includes(".")?`public:${t}`:`unknown:${t}`}function Jde(e){const{client:t,deviceIds:n,nameById:a,pageSize:o,maxRows:p,refreshMs:f,maxAgeMs:m}=e,{sinceMs:h,untilMs:u,devicesResolved:x}=e,w=e.includeStationary===!0,[C,A]=T.useState(Mc),[R,I]=T.useState(!1),[O,D]=T.useState(!1),[z,B]=T.useState(null),[q,G]=T.useState(0),[ae,Q]=T.useState(p),H=T.useRef(p);H.current=ae;const oe=T.useRef(Mc);oe.current=C;const we=T.useRef(!1),Me=T.useRef(!1),Ae=T.useRef(0),Ce=T.useRef(null),re=T.useRef(Date.now()),Te=T.useRef(a);Te.current=a;const F=T.useRef(e.channel);F.current=e.channel;const ue=T.useRef(null);T.useEffect(()=>{Due()},[]);const ke=n.join(","),Ee=T.useCallback(async(Ve,Ie=0)=>{const bt=`feed-${String(++Kde)}`,Re=performance.now();try{const Le=await t.listRecentTracks(Ve),lt=performance.now(),st=$y(lt-Re,Qy(Re,lt)),Pt={requestId:bt,waitMs:Math.round(Ie),...st};return Wde(Le)?{ok:!0,page:Le,timing:Pt}:(mi("request invalid",{...Pt,channel:F.current}),{ok:!1,message:"unexpected response shape"})}catch(Le){const lt=Le instanceof Error?Le.message:String(Le),st=performance.now();return mi("listRecentTracks failed",{error:lt,devices:Ve.deviceIds.length,limit:Ve.limit,since:Ve.since,cursor:Ve.cursor??null,requestId:bt,channel:F.current,waitMs:Math.round(Ie),...$y(st-Re,Qy(Re,st))}),{ok:!1,message:lt}}},[t]),fe=T.useCallback((Ve,Ie)=>{mi("request complete",{...Ve,channel:F.current,...Ie})},[]),L=T.useCallback(()=>{if(we.current){Me.current=!0,ue.current===null&&(ue.current=performance.now());return}const Ve=oe.current;if(!JC(Ve,H.current)||n.length===0)return;const Ie=ue.current;ue.current=null;const bt=Ie===null?0:performance.now()-Ie;we.current=!0,D(!0);const Re=YC(o,n.length),Le=pde({anchorMs:re.current,maxAgeMs:m,...h!==void 0?{sinceMs:h}:{},...u!==void 0?{untilMs:u}:{}}),lt=XC(Ve)!==null;Ee({deviceIds:[...n],since:Le.since,limit:Re,projection:"slim",...w?{includeStationary:!0}:{},...Le.until!==void 0?{until:Le.until}:{},...(()=>{const st=XC(Ve);return st!==null?{cursor:st}:{}})()},bt).then(st=>{if(st.ok){const Ca=performance.now(),Wa=UC(st.page.tracks,Te.current),$t=rde(oe.current,Wa,st.page.nextCursor);oe.current=$t,A($t),fe(st.timing,{rows:Wa.length,devices:n.length,limit:Re,paged:lt,parseMs:Math.round(performance.now()-Ca)}),Ae.current=0,B(null),I(!0);return}const Pt=Ae.current,Rt=Zde[Pt];if(Pt+1<aA&&Rt!==void 0){Ae.current=Pt+1,mi("page failed — retrying",{attempt:Pt+1,of:aA,backoffMs:Rt}),Ce.current=setTimeout(()=>{Ce.current=null,ee.current()},Rt);return}Ae.current=0;const gn=sde(oe.current);oe.current=gn,A(gn),B(st.message),I(!0)}).finally(()=>{if(we.current=!1,D(!1),lde(oe.current)){ee.current();return}Me.current&&(Me.current=!1,ee.current())})},[Ee,fe,n,ke,o,m,h,u,w]),ee=T.useRef(L);ee.current=L;const me=T.useCallback(()=>{if(we.current||n.length===0)return Promise.resolve();const Ve=ude(oe.current);if(Ve===null)return Oe.current(),Promise.resolve();we.current=!0;const Ie=YC(o,n.length);return(async()=>{let bt=null,Re=0,Le=!0;for(;Le&&Re<nA;){const lt=await Ee({deviceIds:[...n],since:Ve,limit:Ie,projection:"slim",...w?{includeStationary:!0}:{},...u!==void 0?{until:u}:{},...bt!==null?{cursor:bt}:{}});if(!lt.ok)return;const st=lt.page,Pt=performance.now(),Rt=UC(st.tracks,Te.current),gn=cde(oe.current,Rt,st.nextCursor);oe.current=gn.state,A(gn.state),fe(lt.timing,{rows:Rt.length,devices:n.length,limit:Ie,paged:bt!==null,delta:!0,parseMs:Math.round(performance.now()-Pt)}),B(null),Le=gn.gap,bt=gn.deltaCursor,Re+=1}Le&&mi("delta drain hit its page bound — newer rows may be missing",{since:Ve,pages:Re,bound:nA})})().finally(()=>{we.current=!1,Me.current&&(Me.current=!1,ee.current())})},[Ee,fe,n,ke,o,L,u,w]),be=T.useCallback(()=>{Ce.current!==null&&(clearTimeout(Ce.current),Ce.current=null),Ae.current=0},[]),X=T.useCallback(()=>{const Ve=H.current+Math.max(1,p);H.current=Ve,Q(Ve),ee.current()},[p]),xe=T.useCallback(()=>{be(),B(null),I(!1),ee.current()},[be]),Oe=T.useRef(()=>{}),le=T.useCallback(()=>{be(),re.current=Date.now(),Me.current=!1,oe.current=Mc,A(Mc),I(!1),D(!1),B(null),H.current=p,Q(p),G(Ve=>Ve+1)},[be,p]),ye=T.useCallback(()=>{be(),re.current=Date.now(),Me.current=!1;const Ve=ode(oe.current);oe.current=Ve,A(Ve),Ve.rows.length===0&&I(!1),D(!1),B(null),G(Ie=>Ie+1)},[be]),Be=`${ke}|${m}|${h??""}|${u??""}|${w?"1":"0"}`,ot=T.useRef(Be);return T.useEffect(()=>{ot.current!==Be&&(ot.current=Be,!(oe.current.rows.length===0&&!R)&&le())},[Be,le,R]),T.useEffect(()=>{if(n.length===0){x&&I(!0);return}L()},[q,ke,x]),T.useEffect(()=>{if(f<=0||n.length===0||!mde(u,Date.now()))return;const Ve=setInterval(()=>{me()},f);return()=>clearInterval(Ve)},[f,me,n.length,u]),Oe.current=xe,T.useEffect(()=>be,[be]),{rows:C.rows,retry:xe,loading:!R,loadingMore:O&&R,error:z,hasMore:JC(C,ae),tail:c5(C,ae),loadMore:L,loadOlder:X,refresh:me,reload:ye}}const epe=3,tpe=250;function npe(e){const{urls:t,token:n,paused:a,enabled:o}=e,p=T.useRef(0),f=T.useRef(0),m=T.useRef(!1),h=T.useRef(t),u=T.useRef(t[0]??"");h.current=t;const x=t[0]??"";u.current!==x&&(u.current=x,p.current=0),T.useEffect(()=>{if(m.current=!1,!o||a)return;let w=!1;const C=()=>{if(!(w||m.current))for(;f.current<epe;){const A=h.current,R=p.current;if(R>=A.length)return;p.current=R+1;const I=A[R];I===void 0||I.length===0||(f.current+=1,Wue(I,n).finally(()=>{f.current=Math.max(0,f.current-1),C()}))}};return C(),()=>{w=!0,m.current=!0}},[o,a,n,t.length])}const ape=.5,p5=56,ipe=88;function rpe(e){return e<=0?0:Math.min(e*ape,ipe)}function iA(e){return e>=p5}function ope(e,t,n){return e==="gallery"&&!t&&!n}function spe(e){const{root:t,onRefresh:n,enabled:a}=e,[o,p]=T.useState(0),f=T.useRef(null),m=T.useRef(0);m.current=o;const h=T.useRef(n);h.current=n;const u=T.useCallback(()=>{f.current=null,p(0)},[]);return T.useEffect(()=>{if(!a||t===null)return;const x=R=>{if(t.scrollTop>0){f.current=null;return}const I=R.touches[0];f.current=I!==void 0?I.clientY:null},w=R=>{const I=f.current;if(I===null)return;const O=R.touches[0];if(O!==void 0){if(t.scrollTop>0){f.current=null,p(0);return}p(rpe(O.clientY-I))}},C=()=>{if(f.current===null)return;const R=m.current;u(),iA(R)&&h.current()},A={passive:!0};return t.addEventListener("touchstart",x,A),t.addEventListener("touchmove",w,A),t.addEventListener("touchend",C,A),t.addEventListener("touchcancel",u,A),()=>{t.removeEventListener("touchstart",x),t.removeEventListener("touchmove",w),t.removeEventListener("touchend",C),t.removeEventListener("touchcancel",u)}},[t,a,u]),{distance:o,armed:iA(o)}}const js=8,rA=10,lpe=400;function cpe(e){return Math.max(lpe,Math.round(e))}function m5(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 oA(e,t,n){return{...m5(e,t),font:"inherit",fontSize:12,color:n.text,background:n.card,border:`1px solid ${n.border}`,borderRadius:8,cursor:"pointer"}}const upe=8;function sA({message:e,palette:t}){return T.useEffect(()=>{Da(bue(e)),Da(Tp("error",e))},[e]),v.jsxs("div",{style:{position:"fixed",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:t.background,color:"#f87171",fontFamily:"system-ui, sans-serif",fontSize:13,padding:16,textAlign:"center"},children:["Events embed config error: ",e]})}function dpe({client:e,initialConfig:t}){const[n,a]=T.useState(t),[o,p]=T.useState({}),[f,m]=T.useState(()=>window.matchMedia?.("(prefers-color-scheme: dark)").matches??!0),[h,u]=T.useState(()=>Date.now()),[x,w]=T.useState(null);T.useEffect(()=>{let ge=!1;return e.listDevices().then(_e=>{ge||w(_e)}).catch(()=>{ge||w([])}),()=>{ge=!0}},[e]);const C=T.useMemo(()=>{const ge=new Map;for(const _e of x??[])ge.set(_e.id,_ce(_e.id,_e.name??`Camera ${_e.id}`,n.deviceNames));for(const[_e,_t]of Object.entries(n.deviceNames)){const tn=Number(_e);Number.isInteger(tn)&&!ge.has(tn)&&_t.trim().length>0&&ge.set(tn,_t)}return ge},[x,n.deviceNames]),[A,R]=T.useState(()=>new Map),[I,O]=T.useState(()=>new Map),D=T.useMemo(()=>qce(n.kindLabels),[n.kindLabels]),z=T.useMemo(()=>rce(n.labels),[n.labels]),B=T.useMemo(()=>n.deviceIds.length>0?n.deviceIds:x===null?[]:rue(x),[n.deviceIds,x]);T.useEffect(()=>{if(B.length===0)return;let ge=!1;return e.listEventKinds([...B]).then(_e=>{ge||(R(Dce(_e)),O(zce(_e)))}).catch(()=>{mi("event-kind taxonomy unavailable — class filter is exact-id only")}),()=>{ge=!0}},[e,B]);const q=Jde({client:e,deviceIds:B,nameById:C,pageSize:n.pageSize,maxRows:Sce(n),refreshMs:n.refreshMs,maxAgeMs:n.maxAgeMs,channel:Xde(n.serverUrl),devicesResolved:n.deviceIds.length>0||x!==null,...n.showStationary?{includeStationary:!0}:{},...n.sinceMs!==void 0?{sinceMs:n.sinceMs}:{},...n.untilMs!==void 0?{untilMs:n.untilMs}:{}}),G=n.searchMode==="semantic"?n.search.trim():"",[ae,Q]=T.useState({query:"",rows:[],loading:!1});T.useEffect(()=>{if(G.length===0||B.length===0){Q({query:"",rows:[],loading:!1});return}let ge=!1;return Q(_e=>({..._e,query:G,loading:!0})),e.searchObjectEvents({text:G,limit:n.semanticLimit,minScore:n.semanticMinScore,...B.length===1&&B[0]!==void 0?{deviceId:B[0]}:{},...n.sinceMs!==void 0?{since:n.sinceMs}:{},...n.untilMs!==void 0?{until:n.untilMs}:{}}).then(_e=>{ge||Q({query:G,rows:kde(_e,C),loading:!1})}).catch(_e=>{ge||(mi("searchObjectEvents failed",{error:_e instanceof Error?_e.message:String(_e)}),Q({query:G,rows:[],loading:!1}))}),()=>{ge=!0}},[e,G,B,C,n.semanticLimit,n.semanticMinScore,n.sinceMs,n.untilMs]);const H=G.length>0,oe=T.useMemo(()=>new Set(n.reviewedTrackIds),[n.reviewedTrackIds]),we=ge=>oe.size===0?[...ge]:ge.map(_e=>oe.has(_e.trackId)?{..._e,reviewed:!0}:_e),Me=T.useMemo(()=>we($C(HC(q.rows,C),o)),[q.rows,C,oe,o]),Ae=T.useMemo(()=>we($C(HC(ae.rows,C),o)),[ae.rows,C,oe,o]),Ce=T.useMemo(()=>{const ge={debug:n.filterDebug,train:n.filterTrain,favourited:n.filterFavourited,reviewedTrackIds:n.reviewedTrackIds},_e=FC(Me,n.classes,n.search,A,n.attrs,ge);if(H){const _t=FC(Ae,n.classes,"",A,n.attrs,ge);return wde(_t,_e,n.sort)}return u5(_e,n.sort)},[H,Ae,Me,n.classes,n.attrs,n.filterDebug,n.filterTrain,n.filterFavourited,n.reviewedTrackIds,n.search,n.sort,A]),re=n5(n.theme,f),Te=T.useRef(null),[F,ue]=T.useState(null),ke=T.useRef(null),Ee=T.useRef(q.loadMore);Ee.current=q.loadMore;const fe=T.useRef(q.refresh);fe.current=q.refresh;const L=T.useRef(q.reload);L.current=q.reload;const[ee]=T.useState(()=>bde(Da)),me=T.useCallback(ge=>{if(ge.type==="setConfig"){a(_e=>By(_e,ge.patch));return}if(ge.type==="setWindow"){a(_e=>By(_e,Tue(ge)));return}if(ge.type==="setTrackFlagPatches"){p(ge.patches);return}if(ge.type==="setTrackListMode"){ee.setMode(ge.mode);return}if(ge.type==="refresh"){fe.current().finally(()=>Da(Cue()));return}if(ge.type==="reload"){L.current();return}if(ge.type==="loadMore"){Ee.current();return}if(ge.type==="ping"){Da(wue());return}Te.current?.scrollTo({top:0,left:0,behavior:"smooth"})},[ee]);T.useEffect(()=>(window.__camstackEvents={setConfig:ge=>{const _e=Sc({type:"setConfig",patch:ge});_e!==null&&me(_e)},setWindow:ge=>{const _e=Sc({type:"setWindow",...ge});_e!==null&&me(_e)},setTrackFlagPatches:ge=>{const _e=Sc({type:"setTrackFlagPatches",patches:ge});_e!==null&&me(_e)},setTrackListMode:ge=>{const _e=Sc({type:"setTrackListMode",mode:ge});_e!==null&&me(_e)},refresh:()=>me({type:"refresh"}),reload:()=>me({type:"reload"}),loadMore:()=>me({type:"loadMore"}),scrollToTop:()=>me({type:"scrollToTop"}),ping:()=>me({type:"ping"})},hu(ge=>{const _e=Sc(ge);_e!==null&&me(_e)})),[me]),T.useEffect(()=>{Da(yue(n.view))},[]),T.useEffect(()=>{Da(H?GC(ae.rows.length,Ce.length,!1,"semantic"):GC(q.rows.length,Ce.length,q.hasMore,"feed"))},[q.rows.length,Ce.length,q.hasMore,H,ae.rows.length]),T.useEffect(()=>{ee.report(Ce)},[ee,Ce]),T.useEffect(()=>{if(q.error!==null&&!H){Da(Tp("error",q.error));return}if(H?ae.loading:q.loading){Da(Tp("loading"));return}Da(Tp(Ce.length===0?"empty":"ready"))},[q.loading,q.error,Ce.length,H,ae.loading]),T.useEffect(()=>{const ge=window.matchMedia?.("(prefers-color-scheme: dark)");if(!ge)return;const _e=_t=>m(_t.matches);return ge.addEventListener("change",_e),()=>ge.removeEventListener("change",_e)},[]),T.useEffect(()=>{document.documentElement.style.colorScheme=re.colorScheme,document.body.style.background=re.background},[re]),T.useEffect(()=>{const ge="camstack-events-keyframes";if(document.getElementById(ge)!==null)return;const _e=document.createElement("style");_e.id=ge,_e.textContent="@keyframes camstack-spin{to{transform:rotate(360deg)}}",document.head.appendChild(_e)},[]),T.useEffect(()=>{const ge=setInterval(()=>u(Date.now()),6e4);return()=>clearInterval(ge)},[]);const[be,X]=T.useState(0);T.useEffect(()=>{const ge=F;if(ge===null)return;const _e=()=>{const tn=n.view==="reel"?ge.clientWidth:ge.clientHeight;X(Tt=>Tt===tn?Tt:tn)};if(_e(),typeof ResizeObserver!="function")return;const _t=new ResizeObserver(_e);return _t.observe(ge),()=>_t.disconnect()},[F,n.view]);const xe=Ce.length>0;T.useEffect(()=>{const ge=Te.current,_e=ke.current;if(!ge||!_e||H||!xe)return;const _t=cpe(n.view==="reel"?ge.clientWidth:ge.clientHeight),tn=new IntersectionObserver(Tt=>{Tt.some(In=>In.isIntersecting)&&Ee.current()},{root:ge,rootMargin:`${_t}px`});return tn.observe(_e),()=>tn.disconnect()},[n.view,q.hasMore,H,xe,be]);const Oe=T.useRef(0);T.useEffect(()=>{if(H||q.loading||q.loadingMore||!q.hasMore)return;const ge=Te.current;if(!ge||Ce.length===0)return;const _e=n.view==="reel";if((_e?ge.clientWidth:ge.clientHeight)===0)return;if(_e?ge.scrollWidth>ge.clientWidth+1:ge.scrollHeight>ge.clientHeight+1){Oe.current=0;return}Oe.current>=upe||(Oe.current+=1,Ee.current())},[Ce.length,q.loading,q.loadingMore,q.hasMore,H,n.view]);const le=spe({root:F,enabled:ope(n.view,H,n.nativePullToRefresh),onRefresh:()=>{fe.current()}}),ye=T.useRef(null);T.useEffect(()=>{const ge=F;if(!n.nativePullToRefresh||ge===null){ye.current=null;return}const _e=()=>{const _t=n.view==="gallery"&&!H&&ge.scrollTop<=0;ye.current!==_t&&(ye.current=_t,Da(Mue(_t)))};return _e(),ge.addEventListener("scroll",_e,{passive:!0}),()=>ge.removeEventListener("scroll",_e)},[F,n.nativePullToRefresh,n.view,H]);const Be=M0(n.thumbSize),ot=Rce(n.thumbSize),Ve=Mce(n.thumbSize,window.devicePixelRatio||1),Ie=n.view==="reel",[bt,Re]=T.useState(!1),[Le,lt]=T.useState({scrollLeft:0,scrollTop:0,viewportWidth:0,viewportHeight:0});T.useEffect(()=>{const ge=F;if(ge===null)return;let _e=null;const _t=()=>{lt({scrollLeft:ge.scrollLeft,scrollTop:ge.scrollTop,viewportWidth:ge.clientWidth,viewportHeight:ge.clientHeight})},tn=()=>{_t(),Re(!0),_e!==null&&clearTimeout(_e),_e=setTimeout(()=>Re(!1),tpe)};return _t(),ge.addEventListener("scroll",tn,{passive:!0}),window.addEventListener("resize",_t),()=>{ge.removeEventListener("scroll",tn),window.removeEventListener("resize",_t),_e!==null&&clearTimeout(_e)}},[F]);const st=T.useMemo(()=>Ade({viewportWidth:Le.viewportWidth,cardWidth:Be,gap:js,columns:n.columns}),[Le.viewportWidth,Be,n.columns]),Pt=Ie?0:Math.ceil(Ce.length/st.columns),Rt=jde({rowCount:Pt,scrollTop:Le.scrollTop,viewportHeight:Le.viewportHeight,fallbackRowPx:st.rowStridePx,geometryKey:`${st.columns}|${Be}|${n.fields.sublabel?"s":""}${n.fields.camera?"c":""}${n.fields.time?"t":""}${n.fields.badges?"b":""}`}),gn=T.useMemo(()=>Ie?Mde(Ce,{scrollLeft:Le.scrollLeft,viewportWidth:Le.viewportWidth,cardWidth:Be,gap:js,rowsPerColumn:n.rows}):Ode(Ce,Rt.window,st.columns),[Ie,Ce,Le.scrollLeft,Le.viewportWidth,Be,n.rows,Rt.window,st.columns]),Ca=T.useMemo(()=>gn.map(ge=>JN(n.serverUrl,ge.bestEventId,Ve)),[gn,n.serverUrl,Ve]);npe({urls:Ca,token:n.token,paused:bt,enabled:!q.loading&&Ce.length>0});const Wa=T.useCallback(ge=>{Da(Sue({trackId:ge.trackId,deviceId:ge.deviceId,bestEventId:ge.bestEventId,className:ge.className,firstSeen:ge.firstSeen,lastSeen:ge.lastSeen}))},[]),$t=Ie?{display:"grid",gridTemplateRows:`repeat(${n.rows}, ${ot}px)`,gridAutoFlow:"column",gridAutoColumns:`${Be}px`,gap:js,alignContent:"start"}:{display:"grid",gridTemplateColumns:`repeat(${st.columns}, minmax(0, 1fr))`,columnGap:js,rowGap:js,paddingBottom:js,alignContent:"start"},Ya=H?ae.loading:q.loading,Xa=!H&&q.loadingMore&&Ce.length>0,zn=!H&&q.error!==null,Kn=!H&&!q.loadingMore&&Ce.length>0,We=Kn&&zn,_n=Kn&&!zn&&q.tail==="exhausted",Aa=Kn&&!zn&&q.tail==="ceiling",Ja=zn&&Ce.length===0,yi=!Ya&&!zn&&Ce.length===0,vn=(ge,_e)=>v.jsx(ede,{row:ge,eagerImages:!Ie&&_e<8,serverUrl:n.serverUrl,token:n.token,thumbPx:Ve,width:Ie?`${Be}px`:"100%",heroPx:Be,variant:Ie?"reel":"gallery",iconId:Lce(ge.className,I,i5(ge)),kindLabels:D,labels:z,scrollRoot:F,fields:n.fields,showAdminFlags:n.showAdminFlags===!0,palette:re,nowMs:h,onClick:Wa},ge.trackId),Wn=v.jsxs(v.Fragment,{children:[Xa&&v.jsx("div",{"data-testid":"tail-loading","aria-label":z.loadingMore,style:{width:Ie?Be:"100%",height:Ie?ot:void 0,aspectRatio:Ie?void 0:"1 / 1",borderRadius:10,background:re.skeleton,border:`1px solid ${re.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 ${re.chip}`,borderTopColor:re.textMuted,animation:"camstack-spin 700ms linear infinite"}})}),_n&&v.jsx("div",{"data-testid":"tail-end",style:{...m5(Ie,Be),color:re.textMuted,fontSize:11,opacity:.75},children:Is(n,"end")}),Aa&&v.jsx("button",{type:"button","data-testid":"tail-more",onClick:()=>q.loadOlder(),style:oA(Ie,Be,re),children:Is(n,"loadOlder")}),We&&v.jsx("button",{type:"button","data-testid":"tail-error",onClick:()=>q.retry(),style:{...oA(Ie,Be,re),color:"#f87171"},children:Is(n,"retry")}),v.jsx("div",{ref:ke,style:{width:1,height:1,gridRow:Ie?1:"auto"},"aria-hidden":!0})]});return v.jsxs("div",{ref:ge=>{Te.current=ge,ue(_e=>_e===ge?_e:ge)},"data-testid":"events-scroller",className:Ie?"events-reel-scroller":void 0,style:{position:"fixed",inset:0,background:re.background,color:re.text,fontFamily:"system-ui, -apple-system, sans-serif",overflowX:Ie?"auto":"hidden",overflowY:Ie?"hidden":"auto",padding:Ie?`${Ece}px ${rA}px`:rA,boxSizing:"border-box",WebkitOverflowScrolling:"touch"},children:[le.distance>0&&v.jsx("div",{"data-testid":"pull-indicator","data-armed":le.armed?"true":"false","aria-hidden":!0,style:{position:"absolute",top:Math.max(0,le.distance-28),left:0,right:0,display:"flex",justifyContent:"center",pointerEvents:"none",zIndex:2,opacity:Math.min(1,le.distance/p5)},children:v.jsx("span",{style:{width:22,height:22,borderRadius:999,border:`2px solid ${re.chip}`,borderTopColor:re.textMuted,background:re.card,boxShadow:"0 1px 4px rgba(0,0,0,0.25)",transform:`rotate(${le.distance*4}deg)`,animation:q.loadingMore?"camstack-spin 700ms linear infinite":void 0}})}),Ja&&v.jsxs("div",{"data-testid":"state-error",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",color:"#f87171",fontSize:13,padding:16,textAlign:"center"},children:[v.jsx("span",{children:Is(n,"error")}),v.jsx("button",{type:"button","data-testid":"state-retry",onClick:()=>q.retry(),style:{marginTop:10,font:"inherit",fontSize:12,color:re.text,background:re.card,border:`1px solid ${re.border}`,borderRadius:8,padding:"5px 14px",cursor:"pointer"},children:Is(n,"retry")})]}),yi&&v.jsx("div",{"data-testid":"state-empty",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:re.textMuted,fontSize:13},children:Is(n,"empty")}),Ya&&Ce.length===0&&v.jsx("div",{"data-testid":"state-loading",style:$t,children:Array.from({length:Ie?8:12},(ge,_e)=>v.jsx("div",{style:{width:Ie?Be:"100%",height:Ie?ot:void 0,aspectRatio:Ie?void 0:"1 / 1",borderRadius:10,background:re.skeleton,border:`1px solid ${re.border}`,boxSizing:"border-box",opacity:.6}},`skeleton-${_e}`))}),Ie?v.jsxs("div",{style:$t,children:[Ce.map(vn),Wn]}):v.jsxs("div",{"data-testid":"events-gallery",children:[v.jsx("div",{"data-testid":"gallery-pad-top",style:{height:Rt.window.padTopPx},"aria-hidden":!0}),Array.from({length:Rt.window.endRow-Rt.window.startRow},(ge,_e)=>{const _t=Rt.window.startRow+_e,tn=_t*st.columns;return v.jsx("div",{"data-row-index":_t,ref:Rt.measureRow(_t),style:$t,children:Ce.slice(tn,tn+st.columns).map((Tt,In)=>vn(Tt,tn+In))},_t)}),v.jsx("div",{"data-testid":"gallery-pad-bottom",style:{height:Rt.window.padBottomPx},"aria-hidden":!0}),Wn]})]})}function ppe(){const e=Tm("events",()=>window.__CAMSTACK_EVENTS__,XN,Qde,{urlFirst:!0}),t=T.useMemo(()=>Vde(),[]),n=T.useMemo(()=>e===null?null:Gde(e,t),[e,t]),a=T.useMemo(()=>{if(n===null||!n.ok)return null;const p=bm({serverUrl:n.config.serverUrl,token:n.config.token});return{system:p,client:tde(p)}},[n]);T.useEffect(()=>{if(a)return()=>a.system.close()},[a]);const o=n5(n!==null&&n.ok?n.config.theme:"auto",window.matchMedia?.("(prefers-color-scheme: dark)").matches??!0);return n===null?null:n.ok?a?v.jsx(dpe,{client:a.client,initialConfig:n.config}):v.jsx(sA,{message:"Failed to initialise the events embed",palette:o}):v.jsx(sA,{message:n.error,palette:o})}const im={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"},mpe=Object.keys(im),fpe=Y(s(),s()).optional();function hpe(e){if(e===null||typeof e!="object")return im;const t=e,n={...im};for(const a of mpe){const o=t[a];typeof o=="string"&&o.trim()!==""&&(n[a]=o)}return n}const f5=j(["auto","high","mid","low"]).catch("auto"),gpe=nt([V("auto"),l().int().min(1)]),h5=d({enabled:E(),motion:E(),motionHoldSec:l().optional(),audio:j(["off","sensor","level"]),audioDb:l(),audioHoldSec:l(),detection:E(),detectionHoldSec:l(),detectionClasses:M(s()).optional(),appearance:d({motionColor:s(),audioColor:s(),detectionColor:s(),thickness:l()}).optional()}),pv=j(["off","top-left","top-center","top-right","left-center","right-center","bottom-left","bottom-center","bottom-right"]),vpe=d({motionBoxes:E().optional(),motionBadge:pv.optional(),audioMeter:pv.optional(),occupancy:pv.optional(),stats:E().optional()}),ype=d({cw:l(),ch:l()}),bpe=d({serverUrl:s().min(1),token:s().min(1).optional(),devices:M(l().int().nonnegative()).min(1),layout:gpe,quality:f5,showName:E(),showBadges:E(),muted:E(),paused:E(),highlight:h5.optional(),activeOnly:E().optional(),showBoxes:E().optional(),audioOnIds:M(l().int().nonnegative()).optional(),pausedIds:M(l().int().nonnegative()).optional(),snapshots:Y(s(),s()).optional(),ptzIds:M(l().int().nonnegative()).optional(),overlays:Y(s(),vpe).optional(),editable:E().optional(),spans:Y(s(),ype).optional(),labels:fpe}).superRefine(FN);function g5(e){if(e==null)return{ok:!1,error:"config is required"};const t=bpe.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(n=>`${n.path.join(".")||"(root)"}: ${n.message}`).join("; ")}}const Spe=1,v5=j(["auto","high","mid","low"]),xpe=nt([V("auto"),l().int().min(1)]),y5=d({enabled:E(),motion:E(),audio:j(["off","sensor","level"]),audioDb:l(),audioHoldSec:l(),detection:E(),detectionHoldSec:l(),detectionClasses:M(s()).optional(),appearance:d({motionColor:s(),audioColor:s(),detectionColor:s(),thickness:l()}).optional()}),kpe=d({devices:M(l().int().nonnegative()).min(1),layout:xpe,quality:v5,showName:E(),audioOnIds:M(l().int().nonnegative()).optional(),activeOnly:E().optional(),boxes:E().optional(),highlight:y5.optional()}),wpe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function Mpe(e){let t="",n=0;for(;n<e.length;){const a=e[n];if(a===void 0)return null;let o,p;if(a<128)o=a,p=0;else if((a&224)===192)o=a&31,p=1;else if((a&240)===224)o=a&15,p=2;else if((a&248)===240)o=a&7,p=3;else return null;for(let f=1;f<=p;f++){const m=e[n+f];if(m===void 0||(m&192)!==128)return null;o=o<<6|m&63}n+=p+1,t+=String.fromCodePoint(o)}return t}function Cpe(e){if(e.length%4===1)return null;const t=[];for(const o of e){const p=wpe.indexOf(o);if(p<0)return null;t.push(p)}const n=[];for(let o=0;o<t.length;o+=4){const p=t[o],f=t[o+1];if(p===void 0||f===void 0)return null;const m=t[o+2],h=t[o+3];n.push(p<<2|f>>4),m!==void 0&&n.push((f&15)<<4|m>>2),h!==void 0&&m!==void 0&&n.push((m&3)<<6|h)}const a=Mpe(n);if(a===null)return null;try{return JSON.parse(a)}catch{return null}}function R0(e,t){return e.startsWith(t)?e.slice(t.length):e}function b5(e){const n=new URLSearchParams(R0(e,"#")).get("t");return n!==null&&n.length>0?n:null}function Ape(e,t){return new URLSearchParams(R0(e,"?")).has("v")||b5(t)!==null}function lA(e){if(e.length===0)return null;const t=[];for(const n of e.split(",")){if(!/^\d+$/.test(n))return null;t.push(Number(n))}return t}function $a(e){return{ok:!1,error:e}}function Epe(e,t){const n=new URLSearchParams(R0(e,"?")),a=n.get("mode");if(a!==null&&a!=="grid")return $a(`unsupported mode "${a}"`);const o=n.get("v");if(o===null)return $a("missing share-link version (v)");if(o!==String(Spe))return $a(`unsupported share-link version "${o}"`);const p=n.get("devices"),f=p===null?null:lA(p);if(f===null||f.length===0)return $a("invalid or missing devices list");const m=n.get("layout");let h;if(m===null||m==="auto")h="auto";else if(/^\d+$/.test(m)&&Number(m)>=1)h=Number(m);else return $a(`invalid layout "${m}"`);const u=n.get("q")??"auto",x=v5.safeParse(u),w=x.success?x.data:"auto",C=n.get("names")??"0";if(C!=="0"&&C!=="1")return $a(`invalid names flag "${C}"`);const A=n.get("audio");let R;if(A!==null){const Q=lA(A);if(Q===null)return $a(`invalid audio list "${A}"`);R=Q}const I=n.get("activeOnly");if(I!==null&&I!=="0"&&I!=="1")return $a(`invalid activeOnly flag "${I}"`);const O=I==="1",D=n.get("boxes");if(D!==null&&D!=="0"&&D!=="1")return $a(`invalid boxes flag "${D}"`);const z=D==="1",B=n.get("hl");let q;if(B!==null){const Q=Cpe(B),H=y5.safeParse(Q);if(Q===null||!H.success)return $a("invalid highlight config (hl)");q=H.data}const G={devices:[...f],layout:h,quality:w,showName:C==="1",...R!==void 0&&R.length>0?{audioOnIds:[...R]}:{},...O?{activeOnly:!0}:{},...z?{boxes:!0}:{},...q!==void 0?{highlight:q}:{}},ae=kpe.safeParse(G);return ae.success?{ok:!0,params:ae.data,token:b5(t)}:$a(ae.error.issues.map(Q=>`${Q.path.join(".")||"(root)"}: ${Q.message}`).join("; "))}function Rpe(e,t,n){if(!Ape(e,t))return null;const a=Epe(e,t);if(!a.ok)return{ok:!1,error:a.error};if(a.token===null)return{ok:!1,error:"share token missing — the link must end with #t=<token>"};const o=a.params,p={serverUrl:n,token:a.token,devices:[...o.devices],layout:o.layout,quality:o.quality,showName:o.showName,showBadges:!0,muted:!0,paused:!1,...o.highlight!==void 0?{highlight:o.highlight}:{},...o.activeOnly===!0?{activeOnly:!0}:{},...o.boxes===!0?{showBoxes:!0}:{},...o.audioOnIds!==void 0&&o.audioOnIds.length>0?{audioOnIds:[...o.audioOnIds]}:{}};return g5(p)}function _pe(){const e=Rpe(location.search,location.hash,location.origin);return e!==null&&location.hash!==""&&history.replaceState(null,"",location.pathname+location.search),e}const rm=16/9,cA={cols:0,rows:0,cellW:0,cellH:0,wallW:0,wallH:0};function uA(e,t,n,a,o){const p=Math.min(a/e,o/t*rm),f=p/rm;return{cols:e,rows:t,cellW:p,cellH:f,wallW:Math.min(e,n)*p,wallH:t*f,empty:e*t-n}}function dA(e){return{cols:e.cols,rows:e.rows,cellW:e.cellW,cellH:e.cellH,wallW:e.wallW,wallH:e.wallH}}const pA=1e-9;function Tpe(e,t){const n=e.cellW*e.cellH,a=t.cellW*t.cellH,o=Math.max(n,a,1);return n-a>o*pA?!0:a-n>o*pA?!1:e.empty!==t.empty?e.empty<t.empty:e.rows<t.rows}function Ipe(e,t,n,a){if(e<=0||t<=0||n<=0)return cA;if(typeof a=="number"&&a>=1){const p=Math.floor(a);return dA(uA(p,Math.ceil(e/p),e,t,n))}let o=null;for(let p=1;p<=e;p++){const f=Math.ceil(e/p);if(Math.ceil(e/f)!==p)continue;const m=uA(f,p,e,t,n);(o===null||Tpe(m,o))&&(o=m)}return o===null?cA:dA(o)}function Npe(e,t){if(e.length===0)return[];const n=t>=1?Math.floor(t):e.length,a=[];for(let o=0;o<e.length;o+=n)a.push(e.slice(o,o+n));return a}function Ope(e,t){if(e.length===0||t.cellW<=0||t.cellH<=0)return[];const n=[];return Npe(e,t.cols).forEach((o,p)=>{const f=(t.wallW-o.length*t.cellW)/2;o.forEach((m,h)=>{n.push({deviceId:m,x:f+h*t.cellW,y:p*t.cellH,w:t.cellW,h:t.cellH})})}),n}const mA={wallW:0,wallH:0,placements:[]};function jpe(e,t){const n=e!==void 0&&Number.isFinite(e.cw)?Math.round(e.cw):1,a=e!==void 0&&Number.isFinite(e.ch)?Math.round(e.ch):1;return{cw:Math.min(Math.max(n,1),Math.max(t,1)),ch:Math.max(a,1)}}function Ppe(e){if(e===void 0)return!1;for(const t of Object.keys(e)){const n=e[t];if(n!==void 0&&(n.cw!==1||n.ch!==1))return!0}return!1}function Dpe(e,t,n){const a=new Set,o=[];let p=0;const f=(m,h,u,x)=>{for(let w=m;w<m+x;w++)for(let C=h;C<h+u;C++)if(a.has(`${w}:${C}`))return!1;return!0};for(const m of e){const{cw:h,ch:u}=jpe(t[String(m)],n),x=p+u+e.length;let w=!1;for(let C=0;C<=x&&!w;C++)for(let A=0;A+h<=n;A++)if(f(C,A,h,u)){for(let R=C;R<C+u;R++)for(let I=A;I<A+h;I++)a.add(`${R}:${I}`);o.push({deviceId:m,col:A,row:C,cw:h,ch:u}),p=Math.max(p,C+u),w=!0;break}}return{cells:o,rows:p,cols:n}}function zpe(e,t,n,a,o){const p=Ipe(e.length,t,n,a);if(!Ppe(o)||p.cols<=0)return{wallW:p.wallW,wallH:p.wallH,placements:Ope(e,p)};if(e.length===0||t<=0||n<=0)return mA;const f=Dpe(e,o??{},p.cols);if(f.rows<=0)return mA;const m=Math.min(t/f.cols,n/f.rows*rm),h=m/rm;return{wallW:f.cells.reduce((x,w)=>Math.max(x,w.col+w.cw),0)*m,wallH:f.rows*h,placements:f.cells.map(x=>({deviceId:x.deviceId,x:x.col*m,y:x.row*h,w:x.cw*m,h:x.ch*h}))}}function S5(){const[e,t]=T.useState(null),[n,a]=T.useState("idle"),o=T.useRef(null),p=T.useRef(null),f=T.useRef(null),m=T.useRef(0),h=T.useRef(null),u=zte(),x=Lte(),w=qte(),C=T.useRef({start:u.mutateAsync,answer:x.mutateAsync,stop:w.mutateAsync});C.current={start:u.mutateAsync,answer:x.mutateAsync,stop:w.mutateAsync};const A=T.useCallback(()=>{if(o.current){try{o.current.close()}catch{}o.current=null}if(p.current){for(const D of p.current.getTracks())try{D.stop()}catch{}p.current=null}},[]),R=T.useCallback(async()=>{const D=f.current;if(f.current=null,A(),D)try{await C.current.stop({deviceId:D.deviceId,sessionId:D.sessionId})}catch{}},[A]),I=T.useCallback(async D=>{if(h.current===D){m.current+=1,h.current=null,t(null),a("idle"),await R();return}m.current+=1;const z=m.current;h.current=D,t(D),a("starting");let B;try{B=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}catch{z===m.current&&(h.current=null,t(null),a("error"));return}if(z!==m.current){for(const G of B.getTracks())G.stop();return}if(await R(),z!==m.current){for(const G of B.getTracks())G.stop();return}let q=null;try{p.current=B;const G=await C.current.start({deviceId:D});if(z!==m.current){try{await C.current.stop({deviceId:D,sessionId:G.sessionId})}catch{}A();return}f.current={deviceId:D,sessionId:G.sessionId},q=new RTCPeerConnection,o.current=q,q.oniceconnectionstatechange=()=>{if(z!==m.current||!q)return;const Q=q.iceConnectionState;Q==="connected"||Q==="completed"?a("talking"):(Q==="failed"||Q==="closed"||Q==="disconnected")&&(h.current=null,t(null),a("idle"),R())};for(const Q of B.getAudioTracks())q.addTrack(Q,B);await q.setRemoteDescription({type:"offer",sdp:G.sdpOffer});const ae=await q.createAnswer();if(await q.setLocalDescription(ae),z!==m.current)return;await C.current.answer({deviceId:D,sessionId:G.sessionId,sdpAnswer:q.localDescription?.sdp??ae.sdp??""})}catch{if(q)try{q.close()}catch{}A();const G=f.current;if(f.current=null,G)try{await C.current.stop({deviceId:G.deviceId,sessionId:G.sessionId})}catch{}z===m.current&&(h.current=null,t(null),a("error"))}},[R,A]),O=T.useCallback(D=>{if(D===null){m.current+=1,h.current=null,t(null),a("idle"),R();return}h.current!==D&&I(D)},[R,I]);return T.useEffect(()=>()=>{m.current+=1,R()},[R]),{activeMicId:e,micState:n,toggleMic:D=>{I(D)},setActiveMic:O}}const Lpe=6e3,qpe=500;function Bpe(e,t){const n=T.useRef(new Map),[,a]=T.useState(0),o=t?.motion??!1,p=t?.audio??"off",f=t?.audioDb??-30,m=t?.audioHoldSec??5,h=t?.detection??!1,u=t?.detectionHoldSec??3,x=t?.detectionClasses??[],w=(R,I)=>{n.current.set(R,Date.now()+I),a(O=>O+1)};fi(Ke.MotionOnMotionChanged,R=>{if(!o)return;const I=R.data;I&&I.detected&&w(I.deviceId,Lpe)}),fi(Ke.PipelineAudioInferenceResult,R=>{if(p==="off")return;const I=R.data;if(!I)return;(p==="sensor"?I.frame.detections.length>0:(I.frame.level?.dbfs??Number.NEGATIVE_INFINITY)>=f)&&w(I.deviceId,m*1e3)}),fi(Ke.DetectionResult,R=>{if(!h)return;const I=R.data;if(!I)return;I.frame.detections.some(D=>x.length===0||x.includes(D.macroClass))&&w(I.frame.deviceId,u*1e3)}),T.useEffect(()=>{const R=setInterval(()=>a(I=>I+1),qpe);return()=>clearInterval(R)},[]);const C=Date.now(),A=new Set;for(const R of e){const I=n.current.get(R);I!==void 0&&C<I&&A.add(R)}return A}function Upe(e){return{type:"tileOpen",deviceId:e}}function Fpe(e){return{type:"audioToggle",deviceId:e}}function Hpe(e){return{type:"pauseToggle",deviceId:e}}function $pe(e){return{type:"ptzOpen",deviceId:e}}function Qpe(e,t){return{type:"cellPanelOpen",deviceId:e,panel:t}}function Vpe(e){return{type:"tileRemove",deviceId:e}}function Gpe(e,t,n){return{type:"tileResize",deviceId:e,cw:t,ch:n}}function x5(e,t,n){return{type:"state",state:e,...t!==void 0?{message:t}:{},...n!==void 0?{commands:n}:{}}}function Zpe(e){return{type:"layout",tiles:e}}function di(e){an(e)}const Kpe=["top-left","top-center","top-right","left-center","right-center","bottom-left","bottom-center","bottom-right"];function fA(e){return typeof e=="string"&&Kpe.includes(e)}const Wpe={"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 k5(e){return{position:"absolute",display:"flex",...Wpe[e]}}const w5=[-60,-53,-46,-39,-32,-24],Ype=w5.length,mv=["#22c55e","#84cc16","#eab308","#f59e0b","#f97316","#ef4444"];function Xpe(e){const t=Math.min(Math.max(0,e),mv.length-1);return mv[t]??mv[0]}function Jpe(e){if(e===null||!Number.isFinite(e))return 0;let t=0;for(const n of w5)e>=n&&(t+=1);return t}function eme(e){if(e==="off")return null;const t=e.split("-"),n=t.includes("top")?"top":t.includes("bottom")?"bottom":"center",a=t.includes("left")?"left":t.includes("right")?"right":"center";return n!=="center"&&a!=="center"?"compact":a==="center"?"horizontal":"vertical"}const hA=[8,11,14,17,21,26],fv={horizontal:{width:8,height:16},vertical:{width:24,height:7},compactWidth:4};function tme(e,t){if(e==="vertical")return fv.vertical;if(e==="horizontal")return fv.horizontal;const n=hA[t]??hA[0];return{width:fv.compactWidth,height:n}}function nme(e){const t=Array.from({length:Ype},(n,a)=>a);return e==="vertical"?[...t].reverse():t}function Co(e){return typeof e=="object"&&e!==null}function ame(e){if(!Co(e))return[];if(e.detected!==!0)return[];const t=typeof e.frameWidth=="number"?e.frameWidth:0,n=typeof e.frameHeight=="number"?e.frameHeight:0;if(t<=0||n<=0)return[];const a=e.regions;if(!Array.isArray(a))return[];const o=[];for(const p of a){if(!Co(p)||!Co(p.bbox))continue;const{x:f,y:m,w:h,h:u}=p.bbox;typeof f!="number"||typeof m!="number"||typeof h!="number"||typeof u!="number"||!(h>0)||!(u>0)||o.push({x:f/t,y:m/n,w:h/t,h:u/n,pixelCount:typeof p.pixelCount=="number"?p.pixelCount:0})}return o}function ime(e){return!Number.isFinite(e)||e<=0?.08:Math.min(.28,.08+e/4e3*.28)}function gA(e){if(!Co(e))return[];const t=Co(e.frame)?e.frame.byClass:void 0,n=Co(t)?t:e.byClass;if(!Co(n))return[];const a=[];for(const[o,p]of Object.entries(n))typeof p!="number"||!Number.isFinite(p)||p<=0||a.push({className:o,count:Math.round(p)});return a.sort((o,p)=>p.count-o.count||o.className.localeCompare(p.className))}function rme(e,t,n){if(n<=0)return 0;const a=t-e;return a<=0?0:Math.round(a*1e3/n)}function ome(e){if(e===null)return"—";const t=[e.resolution,`${e.fps}fps`];return e.dropped>0&&t.push(`${e.dropped} dropped`),t.join(" · ")}const sme=1200,lme=1e3;function cme({deviceId:e}){const[t,n]=T.useState([]),a=T.useRef(void 0);return fi(Ke.MotionAnalysis,o=>{const p=o.data;!p||p.deviceId!==e||(n(ame(p)),a.current&&clearTimeout(a.current),a.current=setTimeout(()=>n([]),sme))}),T.useEffect(()=>()=>{a.current&&clearTimeout(a.current)},[e]),t.length===0?null:v.jsx("div",{style:{position:"absolute",inset:0,overflow:"hidden",pointerEvents:"none"},children:t.map((o,p)=>v.jsx("div",{style:{position:"absolute",left:`${o.x*100}%`,top:`${o.y*100}%`,width:`${o.w*100}%`,height:`${o.h*100}%`,border:"1px dashed #f59e0b",borderRadius:2,background:`rgba(245,158,11,${ime(o.pixelCount)})`}},`${o.x}:${o.y}:${o.w}:${o.h}:${p}`))})}function ume({deviceId:e,anchor:t}){const[n,a]=T.useState(null);fi(Ke.PipelineAudioInferenceResult,h=>{const u=h.data;!u||u.deviceId!==e||a(u.frame.level?.dbfs??null)});const o=Jpe(n),p=eme(t);if(p===null)return null;const f=p==="horizontal",m=p==="vertical";return v.jsx("div",{style:{...k5(t),pointerEvents:"none"},children:v.jsx("span",{style:{display:"flex",flexDirection:m?"column":"row",alignItems:m||f?"center":"flex-end",gap:m||f?4:3,padding:f||m?"4px 8px":"3px 6px",borderRadius:8,background:"rgba(0,0,0,0.7)"},children:nme(p).map(h=>{const u=h<o,x=tme(p,h);return v.jsx("span",{style:{width:x.width,height:x.height,borderRadius:2,background:u?Xpe(h):"#71717a",opacity:u?1:.35}},h)})})})}function dme(e,t){if(typeof e!="object"||e===null)return null;const n=Reflect.get(e,"zoneAnalytics");if(typeof n!="object"||n===null)return null;const a=Reflect.get(n,"getCurrentSnapshot");if(typeof a!="object"||a===null)return null;const o=Reflect.get(a,"query");if(typeof o!="function")return null;const p=o.call(a,{deviceId:t});return p instanceof Promise?p:Promise.resolve(p)}function pme({system:e,deviceId:t,anchor:n}){const[a,o]=T.useState([]);return T.useEffect(()=>{let p=!1;const f=dme(e.trpcClient,t);if(f!==null)return f.then(m=>{p||o(gA(m))}).catch(()=>{p||o([])}),()=>{p=!0}},[e,t]),fi(Ke.ZoneAnalyticsOccupancyChanged,p=>{const f=p.data;f.deviceId===t&&o(gA(f))}),a.length===0?null:v.jsx("div",{style:{...k5(n),gap:4,pointerEvents:"none"},children:a.slice(0,4).map(p=>v.jsx("span",{style:{padding:"2px 6px",borderRadius:6,background:"rgba(0,0,0,0.75)",color:"#fafaf9",fontSize:11,fontWeight:700,fontFamily:"system-ui, sans-serif",whiteSpace:"nowrap"},children:`${p.className} ${p.count}`},p.className))})}function mme({containerRef:e}){const[t,n]=T.useState(null),a=T.useRef(null);return T.useEffect(()=>{const o=()=>{const f=e.current?.querySelector("video");if(!f){n(null);return}const m=typeof f.getVideoPlaybackQuality=="function"?f.getVideoPlaybackQuality():null,h=m?.totalVideoFrames??0,u=Date.now(),x=a.current;a.current={frames:h,at:u},n({resolution:f.videoWidth>0?`${f.videoWidth}x${f.videoHeight}`:"—",fps:x===null?0:rme(x.frames,h,u-x.at),dropped:m?.droppedVideoFrames??0})};o();const p=setInterval(o,lme);return()=>{clearInterval(p),a.current=null}},[e]),v.jsx("div",{style:{position:"absolute",top:4,right:4,maxWidth:"90%",padding:"2px 6px",borderRadius:6,background:"rgba(0,0,0,0.7)",color:"#fafaf9",fontSize:10,fontWeight:600,fontFamily:"system-ui, sans-serif",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",pointerEvents:"none"},children:ome(t)})}const fme=1e4,vA=1e3,yA=[0,5e3,15e3,3e4],hme=4;function gme(e){const t=Math.max(0,Math.min(e,yA.length-1));return yA[t]??0}function vme(e){return!e.playing||e.lastFrameAt===null?!1:e.nowMs-e.lastFrameAt>=e.stallMs}function yme(e){const{containerRef:t,playing:n,onRecover:a,stallMs:o=fme}=e,p=e.now??Date.now,[f,m]=T.useState({recovering:!1,attempts:0}),h=T.useRef(null),u=T.useRef(0),x=T.useRef(0),w=T.useRef(a);w.current=a;const C=T.useRef(p);C.current=p;const A=T.useCallback(()=>{const R=C.current(),I=h.current;h.current=R,u.current>0&&I!==null&&R-I<o&&(u.current=0,m({recovering:!1,attempts:0}))},[o]);return T.useEffect(()=>{if(!n){h.current=null;return}const I=t.current?.querySelector("video");if(!I)return;let O=!1,D=null;if(typeof I.requestVideoFrameCallback=="function"){const q=()=>{O||(A(),D=I.requestVideoFrameCallback?.(q)??null)};return D=I.requestVideoFrameCallback(q),()=>{O=!0,D!==null&&I.cancelVideoFrameCallback?.(D)}}let z=I.currentTime;const B=setInterval(()=>{if(O)return;const q=I.currentTime;q!==z&&(z=q,A())},vA);return()=>{O=!0,clearInterval(B)}},[n,t,A]),T.useEffect(()=>{if(!n)return;const R=setInterval(()=>{const I=C.current();if(I<x.current||!vme({lastFrameAt:h.current,nowMs:I,stallMs:o,playing:n})||u.current>=hme)return;const O=u.current;u.current=O+1,h.current=I,x.current=I+gme(O+1)+o,m({recovering:!0,attempts:O+1}),w.current()},vA);return()=>clearInterval(R)},[n,o]),f}const bme=300,Sme=130,xme=["devices","viewOptions"],kme={inline:xme,overflow:!1},wme={inline:[],overflow:!0};function Mme(e,t){return e>=bme&&t>=Sme?kme:wme}const Cme=120,Ame=68;function Eme(e,t,n){return e&&t>=Cme&&n>=Ame}const Rme=16/9,_me={left:0,top:0,width:0,height:0},bA=.5;function Tme(e,t,n){if(!(e>0)||!(t>0))return _me;const a={left:0,top:0,width:e,height:t};if(!Number.isFinite(n))return a;const o=Math.min(e,t*n),p=o/n;return e-o<bA&&t-p<bA?a:{left:(e-o)/2,top:(t-p)/2,width:o,height:p}}const Ime=500;function M5(e,t,n){const{motion:a,detection:o}=Fle(e.trpcClient,t),p=T.useRef(0),f=T.useRef(0),m=T.useRef(0),h=T.useRef(!1),[,u]=T.useState(0),x=n?.audio??"off",w=n?.audioDb??-30,C=n?.audioHoldSec??5,A=n?.motionHoldSec??0,R=n?.detectionHoldSec??3,I=n?.detectionClasses??[],O=I.join(",");fi(Ke.MotionOnMotionChanged,B=>{const q=B.data;!q||q.deviceId!==t||!n?.motion||(q.detected===!0?(m.current=Date.now()+Math.max(1,A)*1e3,h.current=!0,u(G=>G+1)):q.detected===!1&&h.current&&(m.current=Date.now()+A*1e3,h.current=!1,u(G=>G+1)))}),fi(Ke.PipelineAudioInferenceResult,B=>{const q=B.data;if(!q||q.deviceId!==t||x==="off")return;(x==="sensor"?q.frame.detections.length>0:(q.frame.level?.dbfs??Number.NEGATIVE_INFINITY)>=w)&&(p.current=Date.now()+C*1e3,u(ae=>ae+1))}),T.useEffect(()=>{if(!o)return;o.detections.some(q=>I.length===0||I.includes(q.macroClass))&&(f.current=Date.now()+R*1e3,u(q=>q+1))},[o,R,O]),T.useEffect(()=>{const B=a!==null;(B||h.current)&&(m.current=Date.now()+A*1e3,B||u(q=>q+1)),h.current=B},[a,A]);const D=n?.enabled===!0;if(T.useEffect(()=>{if(!D)return;const B=setInterval(()=>u(q=>q+1),Ime);return()=>clearInterval(B)},[D]),!n?.enabled)return null;const z=Date.now();return n.detection&&z<f.current?"detection":x!=="off"&&z<p.current?"audio":n.motion&&(a!==null||z<m.current)?"motion":null}const Ws={motion:"#DC2626",audio:"#3B82F6",detection:"#22C55E"},Nme=2500,Ome={person:"#f59e0b",vehicle:"#3b82f6",animal:"#22c55e",face:"#a855f7",plate:"#ec4899"},jme="#ef4444";function Pme(e){return Ome[e]??jme}function Xd(e){return e<0?0:e>1?1:e}function Dme(e){if(e.width<=0||e.height<=0)return[];const t=[];for(const n of e.detections){const{bbox:a}=n,o=Xd(a.x/e.width),p=Xd(a.y/e.height),f=Xd((a.x+a.width)/e.width),m=Xd((a.y+a.height)/e.height);f<=o||m<=p||t.push({label:n.macroClass,score:n.score,x1:o,y1:p,x2:f,y2:m})}return t}function zme({deviceId:e}){const[t,n]=T.useState([]),a=T.useRef(void 0);return fi(Ke.DetectionResult,o=>{const p=o.data;!p||p.frame.deviceId!==e||(n(Dme(p.frame)),a.current&&clearTimeout(a.current),a.current=setTimeout(()=>n([]),Nme))}),T.useEffect(()=>()=>{a.current&&clearTimeout(a.current),n([])},[e]),t.length===0?null:v.jsx("div",{style:{position:"absolute",inset:0,overflow:"hidden",pointerEvents:"none"},children:t.map((o,p)=>{const f=Pme(o.label),m=Math.round(o.score*100);return v.jsx("div",{style:{position:"absolute",left:`${o.x1*100}%`,top:`${o.y1*100}%`,width:`${(o.x2-o.x1)*100}%`,height:`${(o.y2-o.y1)*100}%`,border:`2px solid ${f}`,borderRadius:3},children:v.jsx("span",{style:{position:"absolute",left:-2,bottom:"100%",background:f,color:"#fff",fontSize:10,fontWeight:700,fontFamily:"system-ui, sans-serif",lineHeight:"14px",padding:"0 4px",borderRadius:3,whiteSpace:"nowrap"},children:`${o.label} ${m}%`})},`${o.label}-${p}`)})})}function Lme(e,t,n,a){const o=Number.isFinite(e)&&e>0?e:0,p=Number.isFinite(t)&&t>0?t:0;if(!Number.isFinite(n)||!Number.isFinite(a)||n<=0||a<=0)return{width:o,height:p};const f=Math.min(o/n,p/a);return{width:n*f,height:a*f}}function qme(e,t,n){return!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(n)?0:Math.max(0,(n*t-e)/2)}function SA(e,t,n,a){if(!Number.isFinite(e))return 0;const o=qme(t,n,a);return Math.max(-o,Math.min(o,e))}const Bme=4,xA=8,Ume=300;function kA(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function Fme({children:e,onTap:t}){const n=T.useRef(null),a=T.useRef(null),o=T.useRef(new Map),p=T.useRef(1),f=T.useRef(0),m=T.useRef(0),h=T.useRef(null),u=T.useRef(null),x=T.useRef(0),w=()=>{const D=a.current;D&&(D.style.transform=`translate(${f.current}px, ${m.current}px) scale(${p.current})`)},C=()=>{const D=n.current?.getBoundingClientRect();if(!D||D.width<=0||D.height<=0)return;const z=a.current?.querySelector("video")??null,B=z?null:a.current?.querySelector("img")??null,q=z?.videoWidth??B?.naturalWidth??0,G=z?.videoHeight??B?.naturalHeight??0,ae=Lme(D.width,D.height,q,G);f.current=SA(f.current,D.width,ae.width,p.current),m.current=SA(m.current,D.height,ae.height,p.current)},A=()=>{p.current=1,f.current=0,m.current=0,w()},R=D=>{try{D.currentTarget.setPointerCapture(D.pointerId)}catch{}if(o.current.set(D.pointerId,{x:D.clientX,y:D.clientY}),o.current.size===2){const z=[...o.current.values()],B=z[0],q=z[1];B&&q&&(h.current={dist:kA(B,q),scale:p.current,cx:(B.x+q.x)/2,cy:(B.y+q.y)/2,tx:f.current,ty:m.current}),u.current=null}else o.current.size===1&&(u.current={x:D.clientX,y:D.clientY,tx:f.current,ty:m.current,moved:!1})},I=D=>{if(!o.current.has(D.pointerId))return;if(o.current.set(D.pointerId,{x:D.clientX,y:D.clientY}),o.current.size>=2&&h.current){const B=[...o.current.values()],q=B[0],G=B[1];if(!q||!G)return;const ae=kA(q,G);h.current.dist>0&&(p.current=Math.max(1,Math.min(Bme,h.current.scale*(ae/h.current.dist))));const Q=(q.x+G.x)/2,H=(q.y+G.y)/2;f.current=h.current.tx+(Q-h.current.cx),m.current=h.current.ty+(H-h.current.cy),C(),w();return}const z=u.current;if(o.current.size===1&&z){const B=D.clientX-z.x,q=D.clientY-z.y;(Math.abs(B)>xA||Math.abs(q)>xA)&&(z.moved=!0),p.current>1&&(f.current=z.tx+B,m.current=z.ty+q,C(),w())}},O=D=>{const z=o.current.size===1,B=u.current;if(o.current.delete(D.pointerId),o.current.size<2&&(h.current=null),o.current.size===0&&(u.current=null,z&&B&&!B.moved)){const q=Date.now();q-x.current<Ume?(x.current=0,A()):(x.current=q,t())}};return v.jsx("div",{ref:n,style:{position:"absolute",inset:0,overflow:"hidden",touchAction:"none"},onPointerDown:R,onPointerMove:I,onPointerUp:O,onPointerCancel:O,children:v.jsx("div",{ref:a,style:{width:"100%",height:"100%",transformOrigin:"center center",willChange:"transform"},children:e})})}function Hme(e,t){if(t==null||t.length===0)return null;if(/^https?:\/\//i.test(t))return t;const n=e.replace(/\/+$/,""),a=t.startsWith("/")?t:`/${t}`;return`${n}${a}`}function $me(e,t){const n=t[0];return n===void 0?null:Hme(e,n.url)}function Qme(e,t){return{handleOffer:(n,a,o)=>e(t,n,a,o),reoffer:(n,a,o,p)=>e(o,a,n,p)}}const Vme=3500;function Gme(e){return e==="auto"?{kind:"adaptive"}:{kind:"profile",profile:e}}function Zme({system:e,deviceId:t,name:n,online:a,quality:o,muted:p,paused:f,showName:m,audioActive:h,micActive:u,onTogglePause:x,onToggleAudio:w,onToggleMic:C,onOpen:A,ptzSupported:R,onPtz:I,cellW:O,cellH:D,onCellPanel:z,highlight:B,showBoxes:q,overlay:G,reconnectSignal:ae,onStall:Q,posterUrl:H,labels:oe=im,editable:we,span:Me,onRemove:Ae,onResize:Ce}){const{handleOffer:re,getIceServers:Te,addIceCandidate:F,getIceCandidates:ue,closeSession:ke,getSessionState:Ee}=qN(e.trpcClient,t),fe=M5(e,t,B),L=T.useRef(null),[ee,me]=T.useState(0),[be,X]=T.useState("idle"),xe=yme({containerRef:L,playing:be==="playing"&&!f,onRecover:()=>{me(We=>We+1),Q?.(t)}}),[Oe,le]=T.useState(void 0);T.useEffect(()=>{if(H||f)return;let We=!1;const _n=O!==void 0&&O>0?Math.round(O):void 0;return e.trpcClient.snapshot.getSnapshotLinks.query({targets:[{deviceId:t,..._n!==void 0?{width:_n}:{}}]}).then(Aa=>{if(We)return;const Ja=$me(e.serverUrl,Aa??[]);Ja!==null&&le(Ja)}).catch(()=>{}),()=>{We=!0}},[H,f,e,t,O]);const ye=H??Oe,Be=T.useMemo(()=>Gme(o),[o]),ot=`grid:${t}:${o}`,Ve=T.useMemo(()=>Qme(re,Be),[re,Be]),[Ie,bt]=T.useState(!1),Re=T.useRef(null),Le=()=>{Re.current&&clearTimeout(Re.current),Re.current=setTimeout(()=>bt(!1),Vme)},lt=()=>{bt(!0),Le()},st=()=>{bt(We=>{const _n=!We;return _n&&Le(),_n})},Pt=Mme(O??0,D??0),Rt=We=>{We.stopPropagation(),lt()},gn=O!==void 0&&D!==void 0&&O>0&&D>0,Ca=Tme(O??0,D??0,Rme),Wa=gn?{position:"absolute",left:Ca.left,top:Ca.top,width:Ca.width,height:Ca.height}:{position:"absolute",inset:0},$t=Math.max(1,Math.round(Me?.cw??1)),Ya=Math.max(1,Math.round(Me?.ch??1)),Xa=gn&&O!==void 0?O/$t:0,zn=gn&&D!==void 0?D/Ya:0,Kn=Eme(we===!0,O??0,D??0);return T.useEffect(()=>()=>{Re.current&&clearTimeout(Re.current)},[]),v.jsxs("div",{ref:L,"data-stall-recovering":xe.recovering?"true":void 0,style:{position:"relative",width:"100%",height:"100%",background:"#000"},children:[v.jsxs("div",{style:Wa,children:[v.jsx(Fme,{onTap:st,children:f?v.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:"#fafaf9"},children:v.jsx(MA,{size:28})}):v.jsx(_4,{serverUrl:e.serverUrl,streamKey:ot,autoPlay:!0,muted:p,showControls:!1,className:"w-full h-full",handleOffer:Ve.handleOffer,reoffer:Ve.reoffer,getSessionState:Ee,getIceServers:Te,addIceCandidate:F,getIceCandidates:ue,closeSession:ke,reconnectSignal:(ae??0)+ee,onStateChange:X,posterUrl:ye,onClientNetworkSample:o==="auto"?We=>{e.trpcClient.networkQuality.reportClientStats.mutate({deviceId:t,...We}).catch(()=>{})}:void 0},ot)}),q&&!f?v.jsx(zme,{deviceId:t}):null,G?.motionBoxes===!0&&!f?v.jsx(cme,{deviceId:t}):null]}),fA(G?.audioMeter)&&!f?v.jsx(ume,{deviceId:t,anchor:G.audioMeter}):null,fA(G?.occupancy)&&!f?v.jsx(pme,{system:e,deviceId:t,anchor:G.occupancy}):null,G?.stats===!0&&!f?v.jsx(mme,{containerRef:L}):null,fe&&(()=>{const We=B?.appearance,_n=fe==="motion"?We?.motionColor??Ws.motion:fe==="audio"?We?.audioColor??Ws.audio:We?.detectionColor??Ws.detection,Aa=We?.thickness??3;return v.jsx("div",{style:{position:"absolute",inset:0,border:`${Aa}px solid ${_n}`,boxShadow:`inset 0 0 12px ${_n}`,pointerEvents:"none"}})})(),(m||Ie)&&v.jsxs("div",{style:{position:"absolute",left:0,right:0,top:0,display:"flex",alignItems:"center",gap:6,padding:"4px 8px",background:"rgba(0,0,0,0.6)",color:"#fafaf9",fontSize:12,fontWeight:600,fontFamily:"system-ui, sans-serif",pointerEvents:"none",opacity:m||Ie?1:0,transition:"opacity 150ms ease"},children:[v.jsx("span",{style:{width:8,height:8,borderRadius:4,background:a?"#34d399":"#71717a"}}),v.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n})]}),v.jsxs("div",{style:{position:"absolute",inset:0,opacity:Ie?1:0,transition:"opacity 150ms ease",pointerEvents:"none"},children:[v.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"},children:v.jsx(Tr,{label:f?oe.play:oe.pause,big:!0,enabled:Ie,onClick:We=>{Rt(We),x(t)},children:f?v.jsx(MA,{size:22}):v.jsx(Kme,{size:22})})}),v.jsxs("div",{style:{position:"absolute",left:8,bottom:8,display:"flex",gap:8,pointerEvents:"none"},children:[v.jsx(Tr,{label:h?oe.mute:oe.listen,active:h,enabled:Ie,onClick:We=>{Rt(We),w(t)},children:h?v.jsx(Wme,{size:18}):v.jsx(Yme,{size:18})}),v.jsx(Tr,{label:u?oe.stopTalk:oe.talk,active:u,enabled:Ie,onClick:We=>{Rt(We),C(t)},children:v.jsx(Xme,{size:18,muted:!u})}),R&&I&&(!z||!Pt.overflow)?v.jsx(Tr,{label:oe.ptz,enabled:Ie,onClick:We=>{Rt(We),I(t)},children:v.jsx(ife,{size:18})}):null,z?Pt.inline.map(We=>v.jsx(Tr,{label:We==="devices"?oe.linkedDevices:oe.viewOptions,enabled:Ie,onClick:_n=>{Rt(_n),z(t,We)},children:We==="devices"?v.jsx(efe,{size:18}):v.jsx(tfe,{size:18})},We)):null,z&&Pt.overflow?v.jsx(Tr,{label:oe.moreActions,enabled:Ie,onClick:We=>{Rt(We),z(t,"actions")},children:v.jsx(nfe,{size:18})}):null]}),v.jsx("div",{style:{position:"absolute",right:8,bottom:8,pointerEvents:"none"},children:v.jsx(Tr,{label:oe.open,enabled:Ie,onClick:We=>{Rt(We),A(t)},children:v.jsx(Jme,{size:18})})}),Kn&&Ae?v.jsx("div",{style:{position:"absolute",right:8,top:8,pointerEvents:"none"},children:v.jsx(Tr,{label:oe.removeFromView,enabled:Ie,onClick:We=>{Rt(We),Ae(t)},children:v.jsx(afe,{size:18})})}):null,Kn&&Ce?v.jsxs(v.Fragment,{children:[v.jsx(wA,{axis:"x",label:oe.resizeWidth,enabled:Ie,track:Xa,span:$t,onSpan:We=>{lt(),Ce(t,We,Ya)}}),v.jsx(wA,{axis:"y",label:oe.resizeHeight,enabled:Ie,track:zn,span:Ya,onSpan:We=>{lt(),Ce(t,$t,We)}})]}):null]})]})}function wA({axis:e,label:t,enabled:n,track:a,span:o,onSpan:p}){const f=T.useRef(null),m=h=>e==="x"?h.clientX:h.clientY;return v.jsx("div",{role:"separator","aria-label":t,"aria-orientation":e==="x"?"vertical":"horizontal",onPointerDown:h=>{h.stopPropagation(),h.currentTarget.setPointerCapture(h.pointerId),f.current={origin:m(h),base:o}},onPointerMove:h=>{if(f.current===null||!(a>0))return;h.stopPropagation();const u=Math.round((m(h)-f.current.origin)/a),x=Math.max(1,f.current.base+u);x!==o&&p(x)},onPointerUp:h=>{f.current=null,h.currentTarget.hasPointerCapture(h.pointerId)&&h.currentTarget.releasePointerCapture(h.pointerId)},onPointerCancel:()=>{f.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,background:"rgba(0,0,0,0.55)",border:"1px solid rgba(250,250,249,0.35)",cursor:e==="x"?"ew-resize":"ns-resize",touchAction:"none",pointerEvents:n?"auto":"none"}})}function Tr({children:e,label:t,onClick:n,big:a=!1,active:o=!1,enabled:p=!0}){const f=a?52:40;return v.jsx("button",{type:"button","aria-label":t,onClick:n,style:{width:f,height:f,borderRadius:f/2,border:"none",display:"flex",alignItems:"center",justifyContent:"center",background:o?"rgba(59,130,246,0.85)":"rgba(0,0,0,0.55)",color:"#fafaf9",cursor:"pointer",padding:0,WebkitTapHighlightColor:"transparent",pointerEvents:p?"auto":"none"},children:e})}const Zr={fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};function MA({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 Kme({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 Wme({size:e}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",...Zr,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 Yme({size:e}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",...Zr,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 Xme({size:e,muted:t}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",...Zr,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 Jme({size:e}){return v.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",...Zr,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 efe({size:e}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",...Zr,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 tfe({size:e}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",...Zr,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 nfe({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 afe({size:e}){return v.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",...Zr,children:v.jsx("path",{d:"M18 6L6 18M6 6l12 12"})})}function ife({size:e}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",...Zr,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 rfe({wall:e,renderTile:t}){return v.jsx("div",{style:{position:"relative",width:e.wallW,height:e.wallH},children:e.placements.map(n=>v.jsx("div",{"data-device-id":n.deviceId,style:{position:"absolute",left:n.x,top:n.y,width:n.w,height:n.h},children:t(n.deviceId,n.w,n.h)},n.deviceId))})}function CA({message:e}){return T.useEffect(()=>di(x5("error",e)),[e]),v.jsxs("div",{style:{position:"fixed",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:"#000",color:"#f87171",fontFamily:"system-ui, sans-serif",fontSize:13,padding:16,textAlign:"center"},children:["Grid embed config error: ",e]})}const ofe=["setDevices","setSpans"];function sfe(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function lfe({system:e,config:t}){const[n,a]=T.useState(t.devices),[o,p]=T.useState(()=>new Set(t.audioOnIds??[])),f=S5(),m=T.useRef(f.setActiveMic);m.current=f.setActiveMic;const[h,u]=T.useState(()=>new Set(t.pausedIds??[])),[x,w]=T.useState(t.highlight),[C,A]=T.useState(t.activeOnly??!1),[R,I]=T.useState(t.showBoxes??!1),[O,D]=T.useState(()=>t.overlays??{}),[z,B]=T.useState(()=>t.spans??{}),q=Bpe(n,x),G=T.useMemo(()=>C?n.filter(X=>q.has(X)):n,[C,n,q]),[ae,Q]=T.useState(t.quality),[H,oe]=T.useState(t.layout),[we,Me]=T.useState(t.showName),[Ae,Ce]=T.useState(0),re=T.useMemo(()=>hpe(t.labels),[t.labels]),[Te,F]=T.useState(()=>t.snapshots??{}),ue=T.useMemo(()=>new Set(t.ptzIds??[]),[t.ptzIds]),[ke,Ee]=T.useState({w:window.innerWidth,h:window.innerHeight}),fe=re.camera,[L,ee]=T.useState({});T.useEffect(()=>{let X=!1;return e.trpcClient.deviceManager.listAll.query({deviceIds:[...n],projection:"slim"}).then(xe=>{if(X)return;const Oe={};for(const le of xe)Oe[le.id]={name:le.name??`${fe} ${le.id}`,online:le.online??!1};ee(Oe)}).catch(()=>{}),()=>{X=!0}},[e,n,fe]),T.useEffect(()=>(window.__camstackGrid={setAudioOn:X=>p(new Set(X)),setMutedAll:X=>{X&&p(new Set)},setActiveMic:X=>m.current(X),setHighlight:X=>w(X),setActiveOnly:X=>A(X),setShowBoxes:X=>I(X),setOverlays:X=>D(X),setPaused:X=>u(new Set(X)),setDevices:X=>a(xe=>sfe(xe,X)?xe:[...X]),setSpans:X=>B(X),setQuality:X=>Q(X),setLayout:X=>oe(X),setShowName:Me,setShowBadges:()=>{},setSnapshots:X=>F(X),fit:(X,xe)=>Ee({w:X,h:xe}),reconnect:()=>Ce(X=>X+1)},di(x5("ready",void 0,ofe)),()=>{window.__camstackGrid&&delete window.__camstackGrid}),[]),T.useEffect(()=>hu(X=>{const xe=window.__camstackGrid;if(!xe)return;switch(X.kind){case"setAudioOn":xe.setAudioOn(X.value);break;case"setMutedAll":xe.setMutedAll(X.value);break;case"setActiveMic":xe.setActiveMic(X.value);break;case"setHighlight":xe.setHighlight(X.value);break;case"setActiveOnly":xe.setActiveOnly(X.value);break;case"setShowBoxes":xe.setShowBoxes(X.value===!0);break;case"setOverlays":xe.setOverlays(X.value);break;case"setPaused":xe.setPaused(X.value);break;case"setDevices":xe.setDevices(X.value);break;case"setSpans":xe.setSpans(X.value);break;case"setQuality":xe.setQuality(f5.parse(X.value));break;case"setLayout":xe.setLayout(X.value);break;case"setShowName":xe.setShowName(X.value);break;case"setShowBadges":xe.setShowBadges(X.value);break;case"setSnapshots":xe.setSnapshots(X.value);break;case"fit":xe.fit(X.w,X.h);break;case"reconnect":xe.reconnect();break}}),[]);const me=T.useMemo(()=>zpe(G,ke.w,ke.h,H,z),[G,ke.w,ke.h,H,z]),be=T.useRef(null);return T.useEffect(()=>{const X=be.current;if(!X)return;const xe=[];X.querySelectorAll("[data-device-id]").forEach(Oe=>{const le=Number(Oe.dataset.deviceId),ye=Oe.getBoundingClientRect();xe.push({deviceId:le,rect:{x:ye.x,y:ye.y,w:ye.width,h:ye.height}})}),xe.length&&di(Zpe(xe))},[me,G]),v.jsxs("div",{ref:be,style:{position:"fixed",inset:0,background:"#000",display:"flex",alignItems:"center",justifyContent:"center"},children:[C&&G.length===0&&v.jsx("div",{style:{color:"#a1a1aa",fontFamily:"system-ui, sans-serif",fontSize:14,padding:24,textAlign:"center"},children:re.noActiveCameras}),v.jsx(rfe,{wall:me,renderTile:(X,xe,Oe)=>v.jsx(Zme,{system:e,deviceId:X,name:L[X]?.name??`${re.camera} ${X}`,online:L[X]?.online??!1,quality:ae,muted:!o.has(X),paused:h.has(X),showName:we,audioActive:o.has(X),micActive:f.activeMicId===X,onTogglePause:le=>di(Hpe(le)),onToggleAudio:le=>di(Fpe(le)),onToggleMic:f.toggleMic,onOpen:le=>di(Upe(le)),ptzSupported:ue.has(X),onPtz:le=>di($pe(le)),cellW:xe,cellH:Oe,onCellPanel:(le,ye)=>di(Qpe(le,ye)),highlight:x,showBoxes:R,overlay:O[String(X)],reconnectSignal:Ae,posterUrl:Te[String(X)],editable:t.editable===!0,span:z[String(X)],onRemove:le=>di(Vpe(le)),onResize:(le,ye,Be)=>di(Gpe(le,ye,Be)),labels:re})})]})}function cfe(){const e=Tm("grid",()=>window.__CAMSTACK_GRID__,g5,_pe),t=T.useMemo(()=>{if(e===null||!e.ok)return null;const n=bm({serverUrl:e.config.serverUrl,token:e.config.token}),a=new wT({defaultOptions:{queries:{retry:!1,refetchOnWindowFocus:!1}}});return{system:n,queryClient:a}},[e]);return T.useEffect(()=>{if(t)return()=>t.system.close()},[t]),e===null?null:e.ok?t?v.jsx(sI,{system:t.system,children:v.jsx(CT,{client:t.queryClient,children:v.jsx(y.Provider,{client:t.system.trpcClient,queryClient:t.queryClient,children:v.jsx(lfe,{system:t.system,config:e.config})})})}):v.jsx(CA,{message:"Failed to initialise the grid embed"}):v.jsx(CA,{message:e.error})}const _0=nt([d({kind:V("adaptive")}),d({kind:V("profile"),profile:Rn})]),ufe=d({deviceId:l().int().nonnegative(),target:_0.optional(),muted:E().optional(),stats:E().optional(),snapshot:s().optional()});function dfe(e){const t=ufe.safeParse(e);return t.success?t.data:null}const pfe=["live","loading","playing","paused","gap","ended","error"];function mfe(e){return typeof e=="string"&&pfe.includes(e)}const bo="low",AA=5e3;class ffe{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;onMessage=t=>{if(this.disposed||typeof t.data!="string")return;let n;try{n=JSON.parse(t.data)}catch{return}if(typeof n!="object"||n===null)return;const a=n;if(a.t==="liveProfile"&&(a.profile==="high"||a.profile==="mid"||a.profile==="low")){this.deps.onLiveProfile?.(a.profile);return}if(a.t==="servedProfile"&&(a.profile==="high"||a.profile==="mid"||a.profile==="low")&&typeof a.requested=="string"){const o=a.requested;this.lastSentProfile=a.profile,this.degradedRequest=a.profile===o?null:o,this.degradedRequest!==null&&this.pendingUpgrade?.desiredProfile===this.degradedRequest&&(this.deps.onLog?.("scrub:playback-upgrade-vetoed",{to:this.degradedRequest}),this.cancelPlaybackUpgrade()),this.deps.onServedProfile?.({profile:a.profile,requested:o});return}if(a.t==="state"&&mfe(a.state)){this.lastState=a.state,a.state==="playing"||a.state==="paused"?(this.maybeArmPlaybackUpgrade(),this.playIntentAt!==null&&(this.deps.onLog?.("playback:ready",{kind:this.playIntentKind,state:a.state,waitMs:Math.round(performance.now()-this.playIntentAt),dragId:this.playIntentDragId}),this.playIntentAt=null,this.playIntentKind=null,this.playIntentDragId=void 0)):(a.state==="live"||a.state==="gap"||a.state==="ended"||a.state==="error")&&this.cancelPlaybackUpgrade(),this.deps.onState?.(a.state);return}a.t!=="position"||typeof a.epochMs!="number"||(this.lastCursorMs=a.epochMs,this.deps.onPosition?.(a.epochMs),typeof a.seq=="number"&&(this.lastPushSeq=a.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,n,a,o,p){const f=this.send({t:"playRecorded",deviceId:t,epoch:n,profile:a});return f&&(this.lastSentProfile=a,this.playIntentAt=performance.now(),this.playIntentKind=o,this.playIntentDragId=p,this.deps.onLog?.("playback:intent",{kind:o,deviceId:t,epochMs:n,profile:a,dragId:p})),f}maybeArmPlaybackUpgrade(){if(this.pendingUpgrade===null||this.upgradeTimer!==null||this.disposed)return;this.upgradeTimer=setTimeout(()=>this.firePlaybackUpgrade(),AA);const t=this.pendingUpgrade;this.upgradeWarmTimer=setTimeout(()=>{if(this.upgradeWarmTimer=null,this.pendingUpgrade===null||this.disposed)return;const n=this.lastCursorMs??t.landEpochMs;this.warm(n,t.desiredProfile)},Math.max(0,AA-1500))}firePlaybackUpgrade(){this.upgradeTimer=null;const t=this.pendingUpgrade;if(this.pendingUpgrade=null,!t||this.disposed)return;const n=this.lastCursorMs??t.landEpochMs;this.sendPlayRecorded(t.deviceId,n,t.desiredProfile,"upgrade"),this.deps.onLog?.("scrub:playback-upgrade",{from:bo,to:t.desiredProfile,epochMs:n})}cancelPlaybackUpgrade(){this.upgradeTimer!==null&&(clearTimeout(this.upgradeTimer),this.upgradeTimer=null),this.upgradeWarmTimer!==null&&(clearTimeout(this.upgradeWarmTimer),this.upgradeWarmTimer=null),this.pendingUpgrade=null}playRecorded(t,n,a){return this.cancelPlaybackUpgrade(),this.sendPlayRecorded(t,n,a,"play")}upgradePlayback(t,n,a){return a===this.lastSentProfile?!0:(this.cancelPlaybackUpgrade(),this.warm(n,a),this.sendPlayRecorded(t,n,a,"upgrade"))}landFromScrub(t,n,a,o){return this.end(),this.cancelPlaybackUpgrade(),this.sendPlayRecorded(t,n,bo,"land",o)?(this.lastCursorMs=n,a===this.degradedRequest?this.deps.onLog?.("scrub:playback-upgrade-vetoed",{to:a,epochMs:n}):a!==bo&&(this.pendingUpgrade={deviceId:t,desiredProfile:a,landEpochMs:n},this.warm(n,a),(this.lastState==="playing"||this.lastState==="paused")&&this.maybeArmPlaybackUpgrade()),!0):!1}seek(t){this.cancelPlaybackUpgrade();const n=this.send({t:"seek",epoch:t});return n&&(this.playIntentAt=performance.now(),this.playIntentKind="seek",this.playIntentDragId=void 0,this.deps.onLog?.("playback:intent",{kind:"seek",epochMs:t})),n}warm(t,n=bo){return this.send({t:"warm",epoch:t,profile:n})}setRate(t){return this.send({t:"setRate",rate:t})}stepFrame(t){return this.send({t:"stepFrame",dir:t})}commit(t,n){return this.end(),this.send(n!==void 0?{t:"scrubCommit",epoch:t,dragId:n}:{t:"scrubCommit",epoch:t})}goLive(){this.cancelPlaybackUpgrade();const t=this.send({t:"goLive"});return t&&this.deps.onLog?.("scrub:push-golive",{}),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!==bo&&(this.lastSentProfile=bo,this.send({t:"setProfile",profile:bo})),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,n){this.isActive()&&(this.retargets+=1,this.send(n?{t:"scrubTo",epoch:t,m:n.mode,v:Math.round(n.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 hfe(e,t,n,a){return e?.isOpen()?(e.warm(n),e.playRecorded(t,n,a)):!1}const gfe=24e4;function vfe(e,t=gfe){if(t<=0)return[e];const n=[];for(let a=0;a<e.length;a+=t)n.push(e.slice(a,a+t));return n.length===0?[""]:n}const yfe=["video/mp4;codecs=avc1.42E01E,mp4a.40.2","video/webm;codecs=vp8,opus","video/webm;codecs=vp9,opus"],EA=["video/mp4;codecs=avc1.42E01E","video/mp4","video/webm;codecs=vp8","video/webm"];function bfe(e=n=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(n),t){const n=t?.audio?[...yfe,...EA]:EA;for(const a of n)try{if(e(a))return a}catch{}return""}function Sfe(e,t){const n=[...e.getVideoTracks()],a=t?.getAudioTracks()??[],o=a.length>0?a.map(p=>{const f=p.clone();return"enabled"in f&&(f.enabled=!0),f}):[...e.getAudioTracks()];return[...n,...o]}function xfe(e,t=30){const n=e;try{if(typeof n.captureStream=="function"){const a=n.captureStream(t);if(a.getVideoTracks().length>0)return a}}catch{}try{if(typeof n.mozCaptureStream=="function"){const a=n.mozCaptureStream(t);if(a.getVideoTracks().length>0)return a}}catch{}return kfe(e,t)}function kfe(e,t){if(e.videoWidth<2||e.videoHeight<2||typeof document>"u")return null;const n=document.createElement("canvas");n.width=e.videoWidth,n.height=e.videoHeight;const a=n.getContext("2d");if(!a||typeof n.captureStream!="function")return null;let o=!0;const p=()=>{if(o){try{a.drawImage(e,0,0,n.width,n.height)}catch{}requestAnimationFrame(p)}};p();const f=n.captureStream(t),m=f.getVideoTracks()[0];if(m){const h=m.stop.bind(m);m.stop=()=>{o=!1,h()}}return f}function wfe(e){return new Promise((t,n)=>{const a=new FileReader;a.onload=()=>{const o=String(a.result??""),p=o.indexOf(",");t(p>=0?o.slice(p+1):o)},a.onerror=()=>n(a.error??new Error("read failed")),a.readAsDataURL(e)})}function Mfe(){return`c${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}function Cfe(e){let t=null,n=[],a=null,o="",p=!1;const f=()=>{if(t=null,n=[],p=!1,a){for(const h of a.getTracks())try{h.stop()}catch{}a=null}},m=h=>{f(),e.emit({type:"liveCaptureError",message:h})};return{start(){if(t)return;const h=e.getVideo();if(!h){m("no video");return}if(typeof MediaRecorder>"u"){m("MediaRecorder missing");return}const u=xfe(h);if(!u){m("no video");return}const x=h.srcObject instanceof MediaStream?h.srcObject:null,w=Sfe(u,x);if(x&&x.getAudioTracks().length>0)for(const I of u.getAudioTracks())try{I.stop()}catch{}const C=new MediaStream(w);a=C;const A=w.some(I=>I.kind==="audio"),R=bfe(void 0,{audio:A});try{t=R?new MediaRecorder(C,{mimeType:R,videoBitsPerSecond:25e5,...A?{audioBitsPerSecond:128e3}:{}}):new MediaRecorder(C)}catch(I){m(I instanceof Error?I.message:"MediaRecorder missing");return}n=[],o=Mfe(),p=!1,t.ondataavailable=I=>{I.data&&I.data.size>0&&n.push(I.data)},t.onerror=()=>m("MediaRecorder missing");try{t.start(1e3)}catch(I){m(I instanceof Error?I.message:"MediaRecorder missing")}},stop(){const h=t;if(!h||p){h||m("no video");return}p=!0;const u=o,x=h.mimeType||"video/mp4";h.onstop=()=>{const w=new Blob(n,{type:x});if(f(),w.size===0){e.emit({type:"liveCaptureError",message:"empty capture"});return}wfe(w).then(C=>{e.emit({type:"liveCaptureStart",id:u,mime:x});const A=vfe(C),R=A.length;A.forEach((I,O)=>{e.emit({type:"liveCaptureChunk",id:u,index:O,total:R,data:I})}),e.emit({type:"liveCaptureDone",id:u})}).catch(C=>{e.emit({type:"liveCaptureError",message:C instanceof Error?C.message:"encode failed"})})};try{typeof h.requestData=="function"&&h.requestData(),h.stop()}catch(w){m(w instanceof Error?w.message:"stop failed")}},abort(){if(t&&t.state!=="inactive")try{t.stop()}catch{}f()}}}const Afe=8,Efe=2.5;function Rfe(e){return e>=Afe?"high":e>=Efe?"mid":"low"}function _fe(e,t){return e.kind==="profile"?e.profile:"low"}function Tfe(e,t){return e.kind==="profile"?e.profile:Rfe(t)}const Ife=d({serverUrl:s().min(1),token:s().min(1),deviceId:l().int().nonnegative(),target:_0,muted:E(),stats:E().optional(),highlight:h5.optional(),snapshot:s().optional(),initialSeekMs:l().positive().optional()});function Wy(e,t){an(t!==void 0?{type:"state",state:e,message:t}:{type:"state",state:e})}function Nfe(e){switch(e){case"playing":return"playing";case"error":return"error";case"connecting":case"disconnected":case"idle":return"connecting"}}function RA(e,t){return _fe(e)}async function Ofe(){if(typeof window>"u")return null;const e=window.location.origin.replace(/\/+$/,""),t=new AbortController,n=window.setTimeout(()=>t.abort(),2500),a=performance.now();try{const o=await fetch(`${e}/adaptive-probe`,{signal:t.signal});if(!o.ok)return null;const p=await o.arrayBuffer(),f=Math.max(1,performance.now()-a);return p.byteLength<1024?null:p.byteLength*8/f/1e3}catch{return null}finally{window.clearTimeout(n)}}function _A(e,t,n,a){a.kind==="adaptive"&&Ofe().then(o=>{if(o===null)return;const p=Tfe(a,o);e.upgradePlayback(t,n,p)})}function jfe(e){return e.kind==="adaptive"?{kind:"adaptive"}:{kind:"profile",profile:e.profile}}function Pfe(e){return e.kind==="adaptive"?"embed:adaptive":`embed:profile:${e.profile}`}function Dfe(e){const t=Ife.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(n=>`${n.path.join(".")||"(root)"}: ${n.message}`).join("; ")}}function TA({message:e}){return T.useEffect(()=>{Wy("error",e)},[e]),v.jsxs("div",{style:{position:"fixed",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:"#000",color:"#f87171",fontFamily:"system-ui, sans-serif",fontSize:13,padding:16,textAlign:"center"},children:["Embed config error: ",e]})}function zfe({system:e,deviceId:t,initialTarget:n,initialMuted:a,initialStats:o,initialHighlight:p,initialSnapshot:f,initialSeekMs:m}){const[h,u]=T.useState(n);T.useEffect(()=>o5(t),[t]);const x=T.useRef(h);x.current=h;const[w,C]=T.useState(a),[A,R]=T.useState(o),[I,O]=T.useState(p),[D,z]=T.useState(f),[B,q]=T.useState(0),[G,ae]=T.useState({w:window.innerWidth,h:window.innerHeight}),Q=M5(e,t,I),H=S5(),oe=T.useRef(H.setActiveMic);oe.current=H.setActiveMic;const{handleOffer:we,getIceServers:Me,addIceCandidate:Ae,getIceCandidates:Ce,closeSession:re,getSessionState:Te}=qN(e.trpcClient,t),F=T.useMemo(()=>jfe(h),[h]),ue=T.useMemo(()=>(le,ye,Be)=>we(F,le,ye,Be),[we,F]),ke=T.useMemo(()=>(le,ye,Be,ot)=>we(Be,ye,le,ot),[we]),Ee=T.useRef(null),fe=T.useRef(null),L=T.useRef("low"),ee=T.useRef(!1),me=T.useRef(null),be=T.useRef(null),X=()=>{const le=me.current;if(le===null)return;const ye=L.current,Be=`${le.phase}|${le.viewportWidth??"-"}x${le.viewportHeight??"-"}|${le.devicePixelRatio??"-"}|${le.downlinkMbps??"-"}|${le.prefersTier??"-"}|${le.probeOrigin??"unreachable"}|${ye}`;Be!==be.current&&(be.current=Be,an({type:"log",scope:"adaptive",msg:"tier decision",data:{deviceId:t,requested:h.kind==="adaptive"?"adaptive":`pinned:${h.kind}`,phase:le.phase,viewportWidth:le.viewportWidth??null,viewportHeight:le.viewportHeight??null,devicePixelRatio:le.devicePixelRatio??null,downlinkMbps:le.downlinkMbps??null,prefersTier:le.prefersTier??null,probeOrigin:le.probeOrigin,liveProfile:ye}}))},xe=T.useRef(m??null);T.useEffect(()=>{if(!w)return;const le=setInterval(()=>{let ye=0;for(const Be of Array.from(document.querySelectorAll("video"))){Be.muted||(Be.muted=!0,ye++);const ot=Be.srcObject;if(ot instanceof MediaStream)for(const Ve of ot.getAudioTracks())Ve.enabled&&(Ve.enabled=!1,ye++)}ye>0&&an({type:"log",scope:"live-audio",msg:"re-muted",data:{corrected:ye}})},1e3);return()=>clearInterval(le)},[w]),T.useEffect(()=>()=>Ee.current?.dispose(),[]),T.useEffect(()=>{const le=()=>{const Re=Ee.current;return Re?.isOpen()?Re:null},ye=()=>RA(x.current,L.current),Be=(Re,Le)=>{_A(Re,t,Le,x.current)},ot=Re=>{ee.current||(ee.current=!0,an({type:"log",scope:"recorded:session",msg:"pointer move with no open session",data:{what:Re}}),an({type:"recState",state:"error"}))},Ve=(Re,Le)=>{const lt=le();return!lt||!Le(lt)?(ot(Re),!1):(ee.current=!1,!0)},Ie=(Re,Le)=>{Ve("scrubCommit",lt=>{const st=lt.landFromScrub(t,Re,ye(),Le);return st&&Be(lt,Re),st})},bt=Cfe({emit:an,getVideo:()=>fe.current});return window.__camstackEmbed={setMuted:Re=>C(Re),setTarget:Re=>{const Le=_0.safeParse(Re);Le.success&&u(Le.data)},setStats:Re=>R(Re),setHighlight:Re=>O(Re),setSnapshot:Re=>z(Re),setMic:Re=>oe.current(Re?t:null),fit:(Re,Le)=>ae({w:Re,h:Le}),reconnect:()=>q(Re=>Re+1),playRecorded:(Re,Le,lt)=>{Number.isFinite(Le)&&Ve("playRecorded",st=>st.playRecorded(Re,Le,lt))},seek:Re=>{Number.isFinite(Re)&&Ve("seek",Le=>{const lt=Le.playRecorded(t,Re,ye());return lt&&Be(Le,Re),lt})},scrubCommit:(Re,Le)=>{Number.isFinite(Re)&&Ie(Re,Le)},scrubStart:Re=>{an({type:"log",scope:"recorded:scrub",msg:"scrubStart",data:{dragId:Re}}),Ve("scrubStart",Le=>Le.begin(Re))},scrubTo:(Re,Le,lt)=>{if(!Number.isFinite(Re))return;const st=(Le==="fine"||Le==="coarse")&&Number.isFinite(lt)?{mode:Le,velocityPxPerS:lt}:void 0;Ve("scrubTo",Pt=>Pt.isActive()?(Pt.retarget(Re,st),!0):!1)},timelineWarm:Re=>{Number.isFinite(Re)&&le()?.warm(Re)},scrubEnd:Re=>{Number.isFinite(Re)&&Ie(Re)},setRate:Re=>{Number.isFinite(Re)&&Ve("setRate",Le=>Le.setRate(Re))},stepFrame:Re=>{Re!==1&&Re!==-1||Ve("stepFrame",Le=>Le.stepFrame(Re))},goLive:()=>{Ve("goLive",Re=>Re.goLive())&&an({type:"recState",state:"live"})},startLiveCapture:()=>bt.start(),stopLiveCapture:()=>bt.stop()},()=>{bt.abort(),window.__camstackEmbed&&delete window.__camstackEmbed}},[t]),T.useEffect(()=>{an({type:"micState",state:H.micState})},[H.micState]),T.useEffect(()=>hu(le=>{const ye=window.__camstackEmbed;if(!ye)return;switch(le.kind){case"setMuted":ye.setMuted(le.value);break;case"setTarget":ye.setTarget(le.value);break;case"setStats":ye.setStats(le.value);break;case"setHighlight":ye.setHighlight(le.value);break;case"setSnapshot":ye.setSnapshot(le.value);break;case"setMic":ye.setMic(le.value);break;case"fit":ye.fit(le.w,le.h);break;case"reconnect":ye.reconnect();break;case"playRecorded":ye.playRecorded(le.deviceId,le.epochMs,le.profile);break;case"seek":ye.seek(le.epochMs??le.value);break;case"scrubCommit":ye.scrubCommit(le.epochMs??le.value,le.dragId);break;case"scrubStart":ye.scrubStart(le.dragId);break;case"scrubTo":ye.scrubTo(le.epochMs??le.value,le.m,le.v);break;case"scrubEnd":ye.scrubEnd(le.epochMs??le.value);break;case"timelineWarm":ye.timelineWarm(le.epochMs??le.value);break;case"setRate":ye.setRate(le.rate??le.value);break;case"stepFrame":{const ot=le.dir;(ot===1||ot===-1)&&ye.stepFrame(ot);break}case"goLive":ye.goLive();break;case"startLiveCapture":ye.startLiveCapture();break;case"stopLiveCapture":ye.stopLiveCapture();break}}),[]);const Oe=Pfe(h);return v.jsxs("div",{style:{position:"fixed",left:0,top:0,width:G.w,height:G.h,background:"#000"},children:[v.jsx(_4,{serverUrl:e.serverUrl,streamKey:Oe,autoPlay:!0,muted:w,showControls:!1,showStats:A,onPlaybackStats:le=>an({type:"log",scope:"playback",msg:"stats",data:le}),onConnectTiming:le=>an({type:"log",scope:"webrtc-timing",msg:"connect",data:le}),onClientNetworkSample:h.kind==="adaptive"?le=>{e.trpcClient.networkQuality.reportClientStats.mutate({deviceId:t,...le}).catch(()=>{})}:void 0,className:"w-full h-full",onAdaptiveHints:le=>{me.current=le,X()},handleOffer:ue,reoffer:ke,getSessionState:Te,getIceServers:Me,addIceCandidate:Ae,getIceCandidates:Ce,closeSession:re,reconnectSignal:B,posterUrl:D,onStateChange:le=>Wy(Nfe(le)),onError:le=>Wy("error",le),onReconnectAttempt:le=>an({type:"log",scope:"live:retry",msg:le.kind==="retry"?"auto-retry scheduled":"auto-retry exhausted",data:le}),onControlChannel:le=>{if(Ee.current?.dispose(),ee.current=!1,Ee.current=new ffe({channel:le,video:()=>fe.current,onState:ye=>an({type:"recState",state:ye}),onPosition:ye=>an({type:"position",positionMs:ye}),onServedProfile:ye=>an({type:"servedProfile",profile:ye.profile,requested:ye.requested}),onLiveProfile:ye=>{L.current=ye,X()},onFirstFrame:()=>an({type:"scrubDrawn"}),onLog:(ye,Be)=>an({type:"log",scope:ye.startsWith("playback:")?"playback":"scrub",msg:ye,data:Be})}),xe.current!==null){const ye=()=>{const Be=xe.current;if(Be===null)return;const ot=RA(x.current,L.current);hfe(Ee.current,t,Be,ot)&&(xe.current=null,Ee.current&&_A(Ee.current,t,Be,x.current),an({type:"log",scope:"recorded:initial-seek",msg:"config-carried seek fired",data:{epochMs:Be,profile:ot}}))};le.readyState==="open"?ye():le.addEventListener("open",ye,{once:!0})}},onVideoElement:le=>{fe.current=le}}),Q&&(()=>{const le=I?.appearance,ye=Q==="motion"?le?.motionColor??Ws.motion:Q==="audio"?le?.audioColor??Ws.audio:le?.detectionColor??Ws.detection,Be=le?.thickness??3;return v.jsx("div",{style:{position:"absolute",inset:0,border:`${Be}px solid ${ye}`,boxShadow:`inset 0 0 12px ${ye}`,pointerEvents:"none",transform:"translateZ(0)"}})})()]})}function Lfe(){const e=Tm("player",()=>window.__CAMSTACK_EMBED__,Dfe),[t,n]=T.useState(null);T.useEffect(()=>{const u=w=>{const C=dfe(w);C&&n(C)};window.__camstackEmbedPage={setDevice:u};const x=hu(w=>{w.kind==="setDevice"&&u(w.value)});return()=>{window.__camstackEmbedPage&&delete window.__camstackEmbedPage,x()}},[]);const a=T.useMemo(()=>{if(e===null||!e.ok)return null;const u=bm({serverUrl:e.config.serverUrl,token:e.config.token}),x=new wT({defaultOptions:{queries:{retry:!1,refetchOnWindowFocus:!1}}});return{system:u,queryClient:x}},[e]);if(T.useEffect(()=>{if(a)return()=>{a.system.close()}},[a]),e===null)return null;if(!e.ok)return v.jsx(TA,{message:e.error});if(!a)return v.jsx(TA,{message:"Failed to initialise the embed player"});const o=t?.deviceId??e.config.deviceId,p=t?.target??e.config.target,f=t?.muted??e.config.muted,m=t?.stats??e.config.stats??!1,h=t!==null?t.snapshot:e.config.snapshot;return v.jsx(sI,{system:a.system,children:v.jsx(CT,{client:a.queryClient,children:v.jsx(y.Provider,{client:a.system.trpcClient,queryClient:a.queryClient,children:v.jsx(zfe,{system:a.system,deviceId:o,initialTarget:p,initialMuted:f,initialStats:m,initialHighlight:e.config.highlight,initialSnapshot:h,initialSeekMs:t===null?e.config.initialSeekMs:void 0},o)})})})}const qfe=d({serverUrl:s().min(1),token:s().min(1),deviceId:l().int().nonnegative(),startMs:l().int().nonnegative().optional()});function Bfe(e){if(e==null)return{ok:!1,error:"config is required"};const t=qfe.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(n=>`${n.path.join(".")||"(root)"}: ${n.message}`).join("; ")}}function Ufe(e,t){const n=(e-t)/1e3;return Number.isFinite(n)&&n>0?n:0}const IA=360*60*1e3,Ffe="scrub unavailable: no open RecordedTrackSession";function Qa(e){an(e)}function fn(e,t,n){try{an({type:"log",scope:e,msg:t,data:n})}catch{}try{console.debug(`[rec-embed:${e}] ${t}`,n??"")}catch{}}function Hfe({system:e,config:t}){T.useEffect(()=>o5(t.deviceId),[t.deviceId]);const n=T.useRef(null),a=T.useRef(0),o=T.useRef(0),p=T.useRef(0),[f,m]=T.useState({w:window.innerWidth,h:window.innerHeight}),h=T.useMemo(()=>async u=>{const x=n.current;if(!x)return;const w=++p.current;o.current=performance.now(),fn("loadAt","start",{epochMs:u,window:IA}),Qa({type:"state",state:"loading"});try{const C=await e.trpcClient.recording.getPlaybackManifest.query({deviceId:t.deviceId,fromMs:u,toMs:u+IA});if(w!==p.current){fn("loadAt","superseded",{epochMs:u});return}if(fn("loadAt","manifest",{playbackUrl:C?.playbackUrl??null,endpoints:C?.playbackEndpoints?.length??0,localMaster:!!C?.localMasterPath}),!C?.playbackUrl){Qa({type:"state",state:"error",message:"no footage"});return}x.src=C.playbackUrl;const A=()=>{if(w!==p.current)return;const R=typeof x.getStartDate=="function"?x.getStartDate():null,I=R instanceof Date&&!Number.isNaN(R.getTime())?R.getTime():u;a.current=I;const O=Ufe(u,I);if(O>0)try{x.currentTime=O}catch(D){fn("loadAt","seek-failed",{msg:String(D)})}x.play().catch(D=>{fn("loadAt","play-rejected",{msg:String(D)})}),fn("loadAt","seek",{epochMs:u,media0Ms:I,offsetSec:O})};x.readyState>=HTMLMediaElement.HAVE_METADATA?A():x.addEventListener("loadedmetadata",A,{once:!0}),fn("loadAt","src-set",{src:C.playbackUrl})}catch(C){fn("loadAt","error",{msg:C instanceof Error?C.message:String(C)}),Qa({type:"state",state:"error",message:C instanceof Error?C.message:String(C)})}},[e,t.deviceId]);return T.useEffect(()=>{fn("init","mounted",{deviceId:t.deviceId,startMs:t.startMs??null,ua:navigator.userAgent});const u=(x,w)=>{fn("scrub","unavailable",{command:x,...w===void 0?{}:{epochMs:w}}),Qa({type:"state",state:"error",message:Ffe})};return window.__camstackRecording={seekTo:x=>{fn("cmd","seekTo",{epochMs:x}),h(x)},play:()=>{fn("cmd","play"),n.current?.play().catch(()=>{})},pause:()=>{fn("cmd","pause"),n.current?.pause()},setRate:x=>{fn("cmd","setRate",{rate:x}),n.current&&(n.current.playbackRate=x)},fit:(x,w)=>{fn("cmd","fit",{w:x,h:w}),m({w:x,h:w})},scrubStart:()=>{fn("cmd","scrubStart"),u("scrubStart")},scrubTo:x=>{fn("cmd","scrubTo",{epochMs:x}),u("scrubTo",x)},scrubEnd:x=>{fn("cmd","scrubEnd",{epochMs:x}),u("scrubEnd",x)}},t.startMs&&t.startMs>0&&h(t.startMs),()=>{window.__camstackRecording&&delete window.__camstackRecording}},[h,t.startMs,t.deviceId]),T.useEffect(()=>hu(u=>{const x=window.__camstackRecording;if(!x)return;switch(u.kind){case"seekTo":x.seekTo(u.value);break;case"play":x.play();break;case"pause":x.pause();break;case"setRate":x.setRate(u.value);break;case"scrubStart":x.scrubStart();break;case"scrubTo":x.scrubTo(u.value);break;case"scrubEnd":x.scrubEnd(u.value);break;case"fit":x.fit(u.w,u.h);break}}),[]),v.jsx("div",{style:{position:"fixed",left:0,top:0,width:f.w,height:f.h,background:"#000"},children:v.jsx("video",{ref:n,playsInline:!0,controls:!1,style:{width:"100%",height:"100%",objectFit:"contain",background:"#000"},onLoadedMetadata:u=>fn("video","loadedmetadata",{w:u.currentTarget.videoWidth,h:u.currentTarget.videoHeight,dur:u.currentTarget.duration}),onPlaying:()=>{fn("video","playing",{vodStartMs:Math.round(performance.now()-o.current)}),Qa({type:"state",state:"playing"})},onPause:()=>Qa({type:"state",state:"paused"}),onEnded:()=>Qa({type:"state",state:"ended"}),onError:u=>{const x=u.currentTarget.error;fn("video","error",{code:x?.code??null,message:x?.message??null}),Qa({type:"state",state:"error",message:x?.message||"video error"})},onTimeUpdate:u=>Qa({type:"position",positionMs:a.current+u.currentTarget.currentTime*1e3})})})}function $fe(){const e=Tm("recording",()=>window.__CAMSTACK_RECORDING__,Bfe),t=T.useMemo(()=>e===null||!e.ok?null:(document.cookie=`camstack_session=${e.config.token}; path=/; SameSite=Lax`,bm({serverUrl:e.config.serverUrl,token:e.config.token})),[e]);return T.useEffect(()=>()=>t?.close(),[t]),e===null?null:e.ok?t?v.jsx(Hfe,{system:t,config:e.config}):(Qa({type:"state",state:"error",message:"init failed"}),null):(Qa({type:"state",state:"error",message:e.error}),null)}function Qfe(){const e=window.__CAMSTACK_EMBED_MODE__??new URLSearchParams(location.search).get("mode")??"grid";return e==="player"?v.jsx(Lfe,{}):e==="recording"?v.jsx($fe,{}):e==="events"?v.jsx(ppe,{}):v.jsx(cfe,{})}const NA=document.getElementById("root");NA&&qj.createRoot(NA).render(v.jsx(Qfe,{}));export{Iee as C,Bee as E,GT as I,Jfe as M,cte as R,du as S,lhe as T,ehe as W,Dte as a,uhe as b,K as c,Mte as d,To as e,che as f,she as g,ohe as h,the as i,v as j,ihe as k,qg as l,Yy as m,jj as n,Tj as o,kn as p,T as r,rhe as s,mu as u,kp as v};
115
+ `;function kN({trpc:e,deviceId:t,layout:n,optimistic:a}){const{cap:o,slice:p,available:f}=ft({trpc:e,deviceId:t,cap:z=>z.climateControl,slice:z=>z.state.climateControl}),{display:m,applyOptimistic:h}=Lt(p,{enabled:a??!0});if(o===void 0||m===void 0)return null;const u=!f;if(n==="compact")return v.jsxs("div",{"data-mode":m.mode,className:"inline-flex items-center gap-1",children:[v.jsx("span",{className:se("text-xs tabular-nums font-medium",G4[m.mode]),children:m.target!==null?v.jsxs(v.Fragment,{children:[m.target,"°",m.currentTemp!==null&&v.jsxs("span",{className:"text-foreground-subtle font-normal",children:[" ","(",m.currentTemp,"°)"]})]}):m.currentTemp!==null?v.jsxs("span",{className:"text-foreground-subtle",children:[m.currentTemp,"°"]}):null}),m.target!==null&&v.jsxs(v.Fragment,{children:[v.jsx("button",{type:"button","aria-label":"Decrease target",disabled:u,onClick:z=>{if(z.stopPropagation(),!u&&m.target!==null){const B=m.target-1;h({target:B}),o.setTarget({target:B})}},className:se("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",u&&"opacity-40 cursor-not-allowed"),children:"−"}),v.jsx("button",{type:"button","aria-label":"Increase target",disabled:u,onClick:z=>{if(z.stopPropagation(),!u&&m.target!==null){const B=m.target+1;h({target:B}),o.setTarget({target:B})}},className:se("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",u&&"opacity-40 cursor-not-allowed"),children:"+"})]}),v.jsx("select",{"aria-label":"Mode",value:m.mode,disabled:u,onChange:z=>{z.stopPropagation();const B=m.availableModes.find(q=>q===z.target.value);!u&&B&&(h({mode:B}),o.setMode({mode:B}))},className:se("bg-transparent px-0.5 text-xs text-foreground-subtle hover:text-foreground cursor-pointer",u&&"opacity-40 cursor-not-allowed"),children:m.availableModes.map(z=>v.jsx("option",{value:z,children:Jg[z]},z))})]});const x=Ose[m.mode],w=m.mode!=="off",C=Dse(m.preset),A=m.preset==="turbo",R=Math.max(.55,zse(m.fanMode)*(A?.6:1)),I=m.swingVertical!==null,O=m.swingHorizontal!==null,D=w&&(m.swingVertical===!0||m.swingHorizontal===!0);return v.jsxs("div",{"data-mode":m.mode,className:se("relative flex flex-col items-stretch gap-2.5 overflow-hidden rounded-lg border p-3 transition-colors",v0[m.mode]),children:[v.jsx("style",{children:Lse}),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(Use,{mode:m.mode,accent:x,periodSec:R,swaying:D})}),v.jsx("div",{className:"pointer-events-none absolute inset-0 bg-gradient-to-b from-surface/50 via-transparent to-surface/50"}),w&&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(CC,{mode:m.mode,className:"h-3.5 w-3.5"}),Jg[m.mode],m.currentTemp!==null&&v.jsxs("span",{className:"normal-case text-foreground-subtle",children:["· ",m.currentTemp,"° now"]}),m.currentHumidity!==null&&v.jsxs("span",{className:"inline-flex items-center gap-0.5 normal-case text-foreground-subtle",children:[v.jsx(pl,{className:"h-3 w-3"}),m.currentHumidity,"%"]})]}),m.target!==null?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"relative z-10 flex items-center gap-3",children:[v.jsx(AC,{label:"Decrease target",symbol:"−",disabled:u,onClick:()=>{if(u||m.target===null)return;const z=m.target-1;h({target:z}),o.setTarget({target:z})}}),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:m.target}),v.jsx("span",{className:"text-lg text-foreground-subtle",children:"°"})]}),v.jsx(AC,{label:"Increase target",symbol:"+",disabled:u,onClick:()=>{if(u||m.target===null)return;const z=m.target+1;h({target:z}),o.setTarget({target:z})}})]}),v.jsx("div",{className:"relative z-10 w-36",children:v.jsx(Bse,{value:m.target,min:jse,max:Pse,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:m.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(ev,{label:"Mode",icon:v.jsx("span",{style:{color:x},className:"flex",children:v.jsx(CC,{mode:m.mode,className:"h-4 w-4"})}),value:m.mode,options:m.availableModes.map(z=>({value:z,label:Jg[z]})),disabled:u,onChange:z=>{const B=m.availableModes.find(q=>q===z);B&&(h({mode:B}),o.setMode({mode:B}))}}),m.availableFanModes.length>0&&v.jsx(ev,{label:"Fan",icon:v.jsx(Ki,{className:"h-4 w-4 text-sky-500"}),value:m.fanMode,options:m.availableFanModes.map(z=>({value:z,label:MC(z)})),disabled:u,onChange:z=>{h({fanMode:z}),o.setFanMode({fanMode:z})}}),m.availablePresets.length>0&&v.jsx(ev,{label:"Preset",icon:v.jsx(C,{className:"h-4 w-4 text-emerald-500"}),value:m.preset,options:m.availablePresets.map(z=>({value:z,label:MC(z)})),disabled:u,onChange:z=>{h({preset:z}),o.setPreset({preset:z})}})]}),(I||O)&&v.jsx(qse,{label:"Swing",children:v.jsxs("div",{className:"grid grid-cols-2 gap-1",children:[I&&v.jsx(EC,{axis:"vertical",on:m.swingVertical??!1,busy:u,onToggle:z=>{h({swingVertical:z}),o.setSwingVertical({on:z})}}),O&&v.jsx(EC,{axis:"horizontal",on:m.swingHorizontal??!1,busy:u,onToggle:z=>{h({swingHorizontal:z}),o.setSwingHorizontal({on:z})}})]})})]})}function qse({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 CC({mode:e,className:t}){const n=Nse[e];return v.jsx(n,{className:t,"aria-hidden":!0})}function ev({label:e,icon:t,value:n,options:a,disabled:o,onChange:p}){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:se("flex items-center gap-1 overflow-hidden rounded-lg border border-border/60 bg-surface-subtle px-1.5 py-1.5",o&&"opacity-40"),children:[v.jsx("span",{className:"flex shrink-0",children:t}),v.jsx("select",{"aria-label":e,value:n,disabled:o,onChange:f=>{f.stopPropagation(),o||p(f.target.value)},className:"min-w-0 flex-1 cursor-pointer appearance-none truncate bg-transparent text-xs font-medium text-foreground outline-none",children:a.map(f=>v.jsx("option",{value:f.value,children:f.label},f.value))}),v.jsx(zo,{className:"h-3 w-3 shrink-0 text-foreground-subtle"})]})]})}function AC({label:e,symbol:t,disabled:n,onClick:a}){return v.jsx("button",{type:"button","aria-label":e,disabled:n,onClick:a,className:se("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",n&&"opacity-40 cursor-not-allowed"),children:t})}function Bse({value:e,min:t,max:n,accent:a}){const o=`${Math.min(1,Math.max(0,(e-t)/(n-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:o,background:a}}),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:o,background:a}})]}),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:[n,"°"]})]})]})}function Use({mode:e,accent:t,periodSec:n,swaying:a}){const o=[0,1,2,3,4,5],p=e==="heat",f=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:o.map(m=>v.jsx("span",{className:"h-8 w-1 rounded-full bg-foreground-subtle opacity-40"},m))}):e==="fan_only"?v.jsx("div",{className:"flex h-full items-center justify-center",children:v.jsx(Fse,{color:t,periodSec:Math.max(.5,n*.7),size:56})}):v.jsx("div",{className:se("acv-sway-wrap absolute inset-0",a&&"acv-sway"),style:a?{animation:"acv-sway 2.6s ease-in-out infinite"}:void 0,children:o.map(m=>v.jsx("span",{className:"acv-streak absolute rounded-full",style:{left:`${8+m*15}%`,width:f?"0.4rem":"0.3rem",height:f?"0.4rem":"1.9rem",background:t,boxShadow:`0 0 6px ${t}`,animationName:p?"acv-rise":"acv-fall",animationTimingFunction:"linear",animationIterationCount:"infinite",animationDuration:`${n}s`,animationDelay:`${m%3*(n/3)+m*.05}s`}},m))})})}function Fse({color:e,periodSec:t,size:n}){return v.jsxs("svg",{width:n,height:n,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(a=>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(${a} 50 50)`},a)),v.jsx("circle",{cx:"50",cy:"50",r:"7",fill:e})]})}function EC({axis:e,on:t,busy:n,onToggle:a}){const o=e==="vertical"?"Vertical":"Horizontal",p=e==="vertical"?tte:ete,f=e==="vertical"?"acv-swing-v":"acv-swing-h";return v.jsxs("button",{type:"button","aria-label":`${o} swing`,"aria-pressed":t,disabled:n,onClick:()=>{n||a(!t)},className:se("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",n&&"opacity-40 cursor-not-allowed"),children:[v.jsx(p,{className:"acv-swing h-4 w-4","aria-hidden":!0,style:t?{animation:`${f} 1.4s ease-in-out infinite`}:void 0}),o]})}var Hse=5,$se=35;function tv(e,t,n){return Math.min(1,Math.max(0,(e-t)/(n-t)))}function nv(e,t,n){return Math.round(t+e*(n-t))}var Qi=176,em=76,Ap=2*Math.PI*em,yc=Ap*(270/360),av=Qi/2-em-10;function RC(e){const t=Qi/2,n=Qi/2,a=Ap-yc,o=e.mode==="band"?(()=>{const p=e.band.from*yc,f=Math.max(0,(e.band.to-e.band.from)*yc);return{dasharray:`${f} ${Ap-f}`,dashoffset:-p}})():(()=>{const p=e.fraction*yc;return{dasharray:`${p} ${Ap-p}`,dashoffset:void 0}})();return v.jsxs("svg",{width:Qi,height:Qi,viewBox:`0 0 ${Qi} ${Qi}`,"aria-hidden":"true",className:"absolute inset-0",style:{transform:"rotate(135deg)"},children:[v.jsx("circle",{cx:t,cy:n,r:em,fill:"none",stroke:"var(--color-border)",strokeWidth:12,strokeDasharray:`${yc} ${a}`,strokeLinecap:"round"}),v.jsx("circle",{cx:t,cy:n,r:em,fill:"none",stroke:e.color,strokeWidth:12,strokeDasharray:o.dasharray,...o.dashoffset!==void 0?{strokeDashoffset:o.dashoffset}:{},strokeLinecap:"round"})]})}var Qse={heat:"#f59e0b",cool:"#60a5fa",auto:"#c084fc",heat_cool:"#e879f9",fan_only:"#94a3b8",dry:"#22d3ee",off:"#d4d4d8"};function Vse({trpc:e,deviceId:t,features:n,optimistic:a}){const{cap:o,slice:p,available:f}=ft({trpc:e,deviceId:t,cap:D=>D.climateControl,slice:D=>D.state.climateControl}),{display:m,applyOptimistic:h}=Lt(p,{enabled:a??!0});if(o===void 0||m===void 0)return null;const u=!f,x=Qse[m.mode],w=m.mode==="heat_cool"||m.targetLow!==null&&m.targetHigh!==null,C=Hse,A=$se,R=!w&&m.target!==null?tv(m.target,C,A):0,I=w&&m.targetLow!==null?tv(m.targetLow,C,A):0,O=w&&m.targetHigh!==null?tv(m.targetHigh,C,A):0;return v.jsxs("div",{"data-mode":m.mode,className:se("flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4 transition-colors",v0[m.mode]),children:[v.jsxs("div",{className:"flex flex-col items-center gap-3",children:[v.jsxs("div",{className:"relative",style:{width:Qi,height:Qi},children:[w?v.jsx(RC,{mode:"band",band:{from:I,to:O},color:x}):v.jsx(RC,{mode:"fill",fraction:R,color:x}),w?v.jsxs(v.Fragment,{children:[v.jsx("div",{"data-testid":"arc-knob",children:v.jsx(Mp,{fraction:I,color:x,knobTopPx:av,onDragFraction:D=>{if(u||m.targetHigh===null)return;const z=Math.min(nv(D,C,A),m.targetHigh);h({targetLow:z}),o.setTargetRange({targetLow:z,targetHigh:m.targetHigh})}})}),v.jsx("div",{"data-testid":"arc-knob",children:v.jsx(Mp,{fraction:O,color:x,knobTopPx:av,onDragFraction:D=>{if(u||m.targetLow===null)return;const z=Math.max(nv(D,C,A),m.targetLow);h({targetHigh:z}),o.setTargetRange({targetLow:m.targetLow,targetHigh:z})}})})]}):v.jsx("div",{"data-testid":"arc-knob",children:v.jsx(Mp,{fraction:R,color:x,knobTopPx:av,onDragFraction:D=>{if(u)return;const z=nv(D,C,A);h({target:z}),o.setTarget({target:z})}})}),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:[m.currentTemp!==null?m.currentTemp:"—",v.jsx("span",{className:"text-lg text-foreground-subtle font-normal ml-0.5",children:"°"})]}),!w&&m.target!==null&&v.jsxs("div",{className:"text-xs font-semibold",style:{color:x},children:["set ",m.target,"°"]}),w&&m.targetLow!==null&&m.targetHigh!==null&&v.jsxs("div",{className:"text-xs font-semibold",style:{color:x},children:[m.targetLow,"° – ",m.targetHigh,"°"]})]})]}),!w&&m.target!==null&&v.jsx("div",{className:"w-[200px]",children:v.jsx(Q4,{value:`${m.target}°`,onDelta:D=>{if(u||m.target===null)return;const z=m.target+D;h({target:z}),o.setTarget({target:z})}})})]}),v.jsx("select",{"aria-label":"Mode",value:m.mode,disabled:u,onChange:D=>{D.stopPropagation();const z=D.target.value;!u&&z&&(h({mode:m.availableModes.find(B=>B===z)??m.mode}),o.setMode({mode:m.availableModes.find(B=>B===z)??m.mode}))},className:se("w-full rounded border border-border bg-surface px-3 py-1.5 text-sm",u&&"opacity-40 cursor-not-allowed"),children:m.availableModes.map(D=>v.jsx("option",{value:D,children:D},D))})]})}function Gse(e){return e==="locked"||e==="locking"}function wN(e){return e==="jammed"}var Zse={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 Kse({state:e}){const t=Zse[e];return v.jsx("div",{"data-testid":"lock-glyph","data-state":e,className:se("flex h-16 w-16 items-center justify-center rounded-full border-2",t.colorClass),children:t.icon==="locked"?v.jsx(lu,{className:"h-8 w-8","aria-hidden":"true"}):v.jsx(yy,{className:"h-8 w-8","aria-hidden":"true"})})}function Wse({state:e}){return v.jsx("span",{className:se("text-sm font-medium capitalize",wN(e)?"text-danger":"text-foreground-muted"),children:e})}function Yse({busy:e,onOpen:t}){return v.jsxs("button",{type:"button","aria-label":"Open (unlatch)",title:"Open (unlatch)",disabled:e,onClick:n=>{n.stopPropagation(),t()},className:se("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(il,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Open"]})}function Xse({trpc:e,deviceId:t,features:n,optimistic:a}){const{cap:o,slice:p,available:f}=ft({trpc:e,deviceId:t,cap:I=>I.lockControl,slice:I=>I.state.lockControl}),{display:m,applyOptimistic:h}=Lt(p,{enabled:a??!0});if(o===void 0||m===void 0)return null;const u=Gse(m.state),x=wN(m.state)||!f,w=n?.includes(la.LockOpen)===!0,C=()=>{x||(u?(h({state:"unlocking"}),o.unlock({})):(h({state:"locking"}),o.lock({})))},A=()=>{x||o.open({})},R=u?"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(Kse,{state:m.state}),v.jsx(Wse,{state:m.state})]}),v.jsx("div",{className:se(x&&"pointer-events-none opacity-40"),children:v.jsx(zre,{on:u,targetLabel:R,onConfirm:C})}),w&&v.jsx("div",{className:"flex justify-center",children:v.jsx(Yse,{busy:x,onOpen:A})})]})}var qy=500,MN=150,Jse="linear-gradient(90deg, #9ec9ff, #ffffff, #ffb24d)";function ele(e,t,n){return Math.min(1,Math.max(0,(e-t)/(n-t)))}function tle(e){return ele(e,MN,qy)}var nle="#f4b740",ale="#d4d4d8";function ile({trpc:e,deviceId:t,features:n,optimistic:a}){const o=ft({trpc:e,deviceId:t,cap:q=>q.switch,slice:q=>q.state.switch}),p=ft({trpc:e,deviceId:t,cap:q=>q.brightness,slice:q=>q.state.brightness}),f=ft({trpc:e,deviceId:t,cap:q=>q.color,slice:q=>q.state.color}),m=Lt(o.slice,{enabled:a??!0}),h=Lt(p.slice,{enabled:a??!0}),u=Lt(f.slice,{enabled:a??!0});if(o.cap===void 0||m.display===void 0)return null;const x=m.display.on===!0,w=!o.available,C=h.display?.percentage??0,A=!p.available,R=x?C/100:0,I=x?nle:ale,O=(n?.includes(la.LightColorMired)??!1)&&f.cap!==void 0,D=u.display?.mireds,z=!f.available,B=()=>{if(w)return;const q=!x;m.applyOptimistic({on:q}),o.cap?.setState({on:q})};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(V4,{fraction:R,color:I,children:[v.jsxs("div",{"data-testid":"brightness-readout",className:"text-3xl font-bold tabular-nums text-foreground leading-none",children:[C,v.jsx("span",{className:"text-base text-foreground-subtle font-normal ml-0.5",children:"%"})]}),v.jsx(wm,{className:"h-5 w-5 text-foreground-subtle","aria-hidden":"true"})]}),p.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:C,disabled:A||!x,onChange:q=>{const G=Number(q.target.value);h.applyOptimistic({percentage:G}),A||p.cap?.setBrightness({percentage:G})}}),v.jsxs("span",{className:"tabular-nums w-9 text-right",children:[C,"%"]})]})]}),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(h0,{on:x,busy:w,onToggle:B})]}),O&&v.jsxs("div",{className:"flex items-center gap-2","data-testid":"color-temp-strip",children:[v.jsx(Cm,{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:MN,max:qy,step:1,className:"w-full",value:D??qy,disabled:z||!x,onChange:q=>{const G=Number(q.target.value);u.applyOptimistic({mode:"mired",mireds:G}),z||f.cap?.setColor({color:{mode:"mired",mireds:G}})}}),v.jsx("div",{className:"pointer-events-none mt-1",children:v.jsx(zy,{fraction:D!==void 0?tle(D):.5,color:Jse})})]})]})]})}var rle="#3aa6a0",ole="#d4d4d8";function sle({trpc:e,deviceId:t,features:n,optimistic:a}){const o=ft({trpc:e,deviceId:t,cap:H=>H.switch,slice:H=>H.state.switch}),p=ft({trpc:e,deviceId:t,cap:H=>H.fanControl,slice:H=>H.state.fanControl}),f=Lt(o.slice,{enabled:a??!0}),m=Lt(p.slice,{enabled:a??!0});if(o.cap===void 0||f.display===void 0)return null;const h=f.display.on===!0,u=!o.available,x=m.display?.percentage??0,w=!p.available,C=h?x/100:0,A=h?rle:ole,R=n?.includes(la.FanSpeed)??!1,I=(n?.includes(la.FanOscillating)??!1)&&p.cap!==void 0,O=m.display?.availablePresets??[],D=(n?.includes(la.FanPreset)??!1)&&p.cap!==void 0&&O.length>0,z=m.display?.preset??"",B=m.display?.oscillating===!0,q=()=>{if(u)return;const H=!h;f.applyOptimistic({on:H}),o.cap?.setState({on:H})},G=()=>{if(w)return;const H=!B;m.applyOptimistic({oscillating:H}),p.cap?.setOscillating({oscillating:H})},ae=H=>{if(w)return;const oe=m.display;if(oe===void 0)return;const we=oe.percentageStep!==void 0&&oe.percentageStep>0?oe.percentageStep:1,Me=Math.min(100,Math.max(0,Math.round(H*100/we)*we));m.applyOptimistic({percentage:Me}),p.cap?.setPercentage({percentage:Me})},Q=H=>{w||H===""||(m.applyOptimistic({preset:H}),p.cap?.setPreset({preset:H}))};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:R?v.jsxs(V4,{fraction:C,color:A,onDragFraction:ae,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(Vp,{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(Vp,{className:"h-16 w-16",style:{color:A},"aria-hidden":"true"})})}),D&&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:z,disabled:w,onChange:H=>{H.stopPropagation(),Q(H.target.value)},className:se("bg-surface border border-border rounded px-1 py-0.5",w&&"opacity-40 cursor-not-allowed"),children:[v.jsx("option",{value:"",disabled:!0,children:"—"}),O.map(H=>v.jsx("option",{value:H,children:H},H))]})]})}),v.jsxs("div",{className:"flex items-center justify-between gap-2",children:[I?v.jsxs("button",{type:"button","aria-label":"Oscillate","aria-pressed":B,disabled:w,onClick:H=>{H.stopPropagation(),G()},className:se("inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs font-medium transition-colors",B?"border-success/50 bg-success/10 text-success":"border-border text-foreground-muted hover:bg-surface-hover",w&&"opacity-40 cursor-not-allowed"),children:[v.jsx(n0,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Oscillate"]}):v.jsx("span",{className:"text-sm font-medium text-foreground-muted",children:h?"On":"Off"}),v.jsx(h0,{on:h,busy:u,onToggle:q})]})]})}function lle({trpc:e,deviceId:t,optimistic:n}){const{cap:a,slice:o,available:p}=ft({trpc:e,deviceId:t,cap:w=>w.switch,slice:w=>w.state.switch}),{display:f,applyOptimistic:m}=Lt(o,{enabled:n??!0});if(a===void 0||f===void 0)return null;const h=f.on===!0,u=!p,x=()=>{if(u)return;const w=!h;m({on:w}),a.setState({on:w})};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":h?"on":"off",className:se("flex h-16 w-16 items-center justify-center rounded-full border-2 transition-colors",h?"border-success/30 bg-success/10 text-success":"border-border bg-surface-subtle text-foreground-subtle"),children:v.jsx(uu,{className:"h-8 w-8","aria-hidden":"true"})}),v.jsx("span",{className:"text-sm font-medium text-foreground-muted",children:h?"On":"Off"}),v.jsx(h0,{on:h,busy:u,onToggle:x})]})}function cle(e){return e==="playing"||e==="buffering"?"pause":"play"}function ule(e,t){return e===null||t===null||t<=0?0:Math.min(1,Math.max(0,e/t))}function _C(e){if(e===null)return"--:--";const t=Math.floor(e/1e3);return`${Math.floor(t/60)}:${(t%60).toString().padStart(2,"0")}`}function dle({title:e,subtitle:t}){return v.jsxs("div",{className:"flex flex-col items-center gap-1 text-center",children:[v.jsx(YT,{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 iv({label:e,busy:t,onPress:n,children:a,primary:o}){return v.jsx("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:p=>{p.stopPropagation(),t||n()},className:se("inline-flex items-center justify-center rounded-full transition-colors",o?"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:a})}function ple({trpc:e,deviceId:t,features:n,optimistic:a}){const{cap:o,slice:p,available:f}=ft({trpc:e,deviceId:t,cap:B=>B.mediaPlayer,slice:B=>B.state.mediaPlayer}),{display:m,applyOptimistic:h}=Lt(p,{enabled:a??!0});if(o===void 0||m===void 0)return null;const u=!f,x=cle(m.state),w=(n?.includes(la.MediaPlayerSeek)??!1)&&m.durationMs!==null&&m.durationMs>0,C=n?.includes(la.MediaPlayerNext)??!1,A=n?.includes(la.MediaPlayerPrevious)??!1,R=(n?.includes(la.MediaPlayerVolume)??!1)&&m.volumeLevel!==null,I=()=>{u||(x==="play"?(h({state:"playing"}),o.play({})):(h({state:"paused"}),o.pause({})))},O=m.currentMedia?.artist??m.currentMedia?.album??null,D=ule(m.positionMs,m.durationMs),z=m.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(dle,{title:m.currentMedia?.title??null,subtitle:O}),w&&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:m.durationMs??0,step:1e3,className:"absolute inset-0 h-4 w-full cursor-pointer opacity-0",value:m.positionMs??0,disabled:u,onChange:B=>{if(u)return;const q=Number(B.target.value);h({positionMs:q}),o.seek({positionMs:q})}}),v.jsx("div",{className:"pointer-events-none",children:v.jsx(zy,{fraction:D})})]}),v.jsxs("div",{className:"flex justify-between text-[11px] tabular-nums text-foreground-subtle",children:[v.jsx("span",{children:_C(m.positionMs)}),v.jsx("span",{children:_C(m.durationMs)})]})]}),v.jsxs("div",{className:"flex items-center justify-center gap-4",children:[A&&v.jsx(iv,{label:"Previous",busy:u,onPress:()=>{o.previous({})},children:v.jsx(hte,{className:"h-5 w-5","aria-hidden":"true"})}),v.jsx(iv,{label:x==="play"?"Play":"Pause",busy:u,onPress:I,primary:!0,children:x==="play"?v.jsx(Lo,{className:"h-6 w-6","aria-hidden":"true"}):v.jsx(cu,{className:"h-6 w-6","aria-hidden":"true"})}),C&&v.jsx(iv,{label:"Next",busy:u,onPress:()=>{o.next({})},children:v.jsx(gte,{className:"h-5 w-5","aria-hidden":"true"})})]}),R&&v.jsxs("div",{"data-testid":"media-volume",className:"flex items-center gap-2",children:[v.jsx("button",{type:"button","aria-label":m.isMuted===!0?"Unmute":"Mute",title:m.isMuted===!0?"Unmute":"Mute",disabled:u,onClick:B=>{if(B.stopPropagation(),u||m.isMuted===null)return;const q=!m.isMuted;h({isMuted:q}),o.setMute({muted:q})},className:se("inline-flex h-7 w-7 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",u&&"opacity-40 cursor-not-allowed"),children:m.isMuted===!0?v.jsx(iI,{className:"h-4 w-4","aria-hidden":"true"}):v.jsx(pu,{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:z,disabled:u,onChange:B=>{if(u)return;const q=Number(B.target.value);h({volumeLevel:q}),o.setVolume({volumeLevel:q})}}),v.jsx("div",{className:"pointer-events-none",children:v.jsx(zy,{fraction:z/100})})]}),v.jsxs("span",{className:"w-9 text-right text-[11px] tabular-nums text-foreground-subtle",children:[z,"%"]})]})]})}var CN={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"}},AN={home:"Home",away:"Away",night:"Night",vacation:"Vacation",custom_bypass:"Bypass"};function EN(e){return e.startsWith("armed_")}function b0(e){return e==="arming"||e==="disarming"}function RN({icon:e,sizeClass:t="h-8 w-8"}){return e==="disarmed"?v.jsx(mte,{className:t,"aria-hidden":"true"}):e==="triggered"?v.jsx(Mm,{className:t,"aria-hidden":"true"}):e==="pending"?v.jsx(fte,{className:t,"aria-hidden":"true"}):v.jsx(pte,{className:t,"aria-hidden":"true"})}function TC({label:e,active:t,busy:n,onSelect:a}){return v.jsx("button",{type:"button","aria-label":e,"aria-pressed":t,disabled:n,onClick:o=>{o.stopPropagation(),n||a()},className:se("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",n&&"opacity-40 cursor-not-allowed"),children:e})}function mle({state:e,availableModes:t,busy:n,onDisarm:a,onArm:o}){const p=EN(e),f=b0(e);return v.jsxs("div",{className:se("flex min-w-0 items-stretch gap-1 rounded-lg border border-border bg-surface-subtle p-1"),children:[v.jsx(TC,{label:"Disarm",active:!p&&!f,busy:n,onSelect:a}),t.map(m=>v.jsx(TC,{label:AN[m],active:!f&&e===`armed_${m}`,busy:n,onSelect:()=>o(m)},m))]})}function _N(e,t,n){const{cap:a,slice:o,available:p}=ft({trpc:e,deviceId:t,cap:w=>w.alarmPanel,slice:w=>w.state.alarmPanel}),{display:f,applyOptimistic:m}=Lt(o,{enabled:n??!0}),h=!p;return{display:f,capPresent:a!==void 0,busy:h,handleDisarm:()=>{a===void 0||h||(m({state:"disarming"}),a.disarm({}))},handleArm:w=>{a===void 0||h||(m({state:"arming"}),a.arm({mode:w}))}}}function fle({trpc:e,deviceId:t,optimistic:n}){const{display:a,capPresent:o,busy:p,handleDisarm:f,handleArm:m}=_N(e,t,n);if(!o||a===void 0)return null;const h=CN[a.state],u=EN(a.state)?a.state.replace("armed_",""):"";return v.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[v.jsxs("span",{className:se("inline-flex shrink-0 items-center gap-1 rounded-md border px-1.5 py-0.5 text-[11px] font-medium whitespace-nowrap",h.colorClass,b0(a.state)&&"animate-pulse"),children:[v.jsx(RN,{icon:h.icon,sizeClass:"h-3 w-3"}),h.label]}),v.jsxs("select",{"aria-label":"Alarm mode",disabled:p,value:u,onClick:x=>x.stopPropagation(),onChange:x=>{x.stopPropagation();const w=x.target.value;w===""?f():m(w)},className:se("min-w-0 shrink rounded-md border border-border bg-surface-subtle px-1.5 py-0.5 text-xs text-foreground-muted",p&&"cursor-not-allowed opacity-40"),children:[v.jsx("option",{value:"",children:"Disarm"}),a.availableModes.map(x=>v.jsx("option",{value:x,children:AN[x]},x))]})]})}function hle({trpc:e,deviceId:t,optimistic:n}){const{display:a,capPresent:o,busy:p,handleDisarm:f,handleArm:m}=_N(e,t,n);if(!o||a===void 0)return null;const h=CN[a.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":a.state,className:se("flex h-16 w-16 items-center justify-center rounded-full border-2",h.colorClass,b0(a.state)&&"animate-pulse"),children:v.jsx(RN,{icon:h.icon})}),v.jsx("span",{className:se("text-sm font-medium",h.colorClass,"border-0 bg-transparent"),children:h.label})]}),v.jsx(mle,{state:a.state,availableModes:a.availableModes,busy:p,onDisarm:f,onArm:m})]})}function gle(e,t){if(e<=0)return null;const n=Math.max(0,Math.round((t-e)/1e3));return n<60?"just now":n<3600?`${Math.floor(n/60)} min ago`:n<86400?`${Math.floor(n/3600)} h ago`:new Date(e).toLocaleDateString()}function S0({atMs:e,neverLabel:t}){const n=gle(e,Date.now());return v.jsx("span",{className:"text-xs text-foreground-subtle","data-testid":"last-run",children:n===null?t:n})}function TN({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(rl,{className:"h-3 w-3 shrink-0","aria-hidden":"true"}),v.jsx("span",{className:"truncate",children:e})]})}function IN(e,t,n){const{cap:a,slice:o,available:p}=ft({trpc:e,deviceId:t,cap:x=>x.scriptRunner,slice:x=>x.state.scriptRunner}),{display:f,applyOptimistic:m}=Lt(o,{enabled:n??!0}),h=!p,u=f?.isRunning===!0;return{display:f,capPresent:a!==void 0,busy:h,running:u,run:()=>{a===void 0||h||u||(m({isRunning:!0}),a.run({}))},stop:()=>{a===void 0||h||!u||(m({isRunning:!1}),a.stop({}))}}}function NN({running:e,busy:t,large:n,onRun:a,onStop:o}){const p=e?"Stop":"Run";return v.jsxs("button",{type:"button","aria-label":p,title:p,disabled:t,"data-testid":"script-run","data-running":e?"true":"false",onClick:f=>{f.stopPropagation(),e?o():a()},className:se("inline-flex items-center gap-1 rounded transition-colors",n?"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(jee,{className:n?"h-4 w-4":"h-3 w-3","aria-hidden":"true"}):v.jsx(Lo,{className:n?"h-4 w-4":"h-3 w-3","aria-hidden":"true"}),v.jsx("span",{children:p})]})}function vle({trpc:e,deviceId:t,optimistic:n}){const{display:a,capPresent:o,busy:p,running:f,run:m,stop:h}=IN(e,t,n);return!o||a===void 0?null:v.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[v.jsx(NN,{running:f,busy:p,large:!1,onRun:m,onStop:h}),v.jsx(S0,{atMs:a.lastRunAt,neverLabel:"never run"})]})}function yle({trpc:e,deviceId:t,optimistic:n}){const{display:a,capPresent:o,busy:p,running:f,run:m,stop:h}=IN(e,t,n);return!o||a===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":f?"true":"false",className:se("flex h-16 w-16 items-center justify-center rounded-full border-2",f?"border-primary text-primary animate-pulse":"border-border text-foreground-subtle"),children:v.jsx(Lo,{className:"h-8 w-8","aria-hidden":"true"})}),v.jsx("span",{className:"text-sm font-medium",children:f?"Running":"Idle"}),v.jsx(S0,{atMs:a.lastRunAt,neverLabel:"never run"}),v.jsx(TN,{error:a.lastError})]}),v.jsx("div",{className:"flex justify-center",children:v.jsx(NN,{running:f,busy:p,large:!0,onRun:m,onStop:h})})]})}function ON(e,t,n){const{cap:a,slice:o,available:p}=ft({trpc:e,deviceId:t,cap:u=>u.automationControl,slice:u=>u.state.automationControl}),{display:f,applyOptimistic:m}=Lt(o,{enabled:n??!0}),h=!p;return{display:f,capPresent:a!==void 0,busy:h,setEnabled:u=>{a===void 0||h||(m({enabled:u}),u?a.enable({}):a.disable({}))},trigger:()=>{a===void 0||h||a.trigger({})}}}function jN({enabled:e,busy:t,onToggle:n}){return v.jsx("button",{type:"button",role:"switch","aria-checked":e,"aria-label":"Automation enabled",disabled:t,"data-testid":"automation-enabled",onClick:a=>{a.stopPropagation(),n(!e)},className:se("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 PN({busy:e,large:t,onTrigger:n}){return v.jsxs("button",{type:"button","aria-label":"Trigger",title:"Run this automation now",disabled:e,"data-testid":"automation-trigger",onClick:a=>{a.stopPropagation(),n()},className:se("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(Pr,{className:t?"h-4 w-4":"h-3 w-3","aria-hidden":"true"}),v.jsx("span",{children:"Trigger"})]})}function ble({trpc:e,deviceId:t,optimistic:n}){const{display:a,capPresent:o,busy:p,setEnabled:f,trigger:m}=ON(e,t,n);return!o||a===void 0?null:v.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[v.jsx(jN,{enabled:a.enabled,busy:p,onToggle:f}),v.jsx(PN,{busy:p,large:!1,onTrigger:m})]})}function Sle({trpc:e,deviceId:t,optimistic:n}){const{display:a,capPresent:o,busy:p,setEnabled:f,trigger:m}=ON(e,t,n);return!o||a===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":a.enabled?"true":"false",className:se("flex h-16 w-16 items-center justify-center rounded-full border-2",a.enabled?"border-success text-success":"border-border text-foreground-subtle"),children:v.jsx(Pr,{className:"h-8 w-8","aria-hidden":"true"})}),v.jsx("span",{className:"text-sm font-medium",children:a.enabled?"Enabled":"Disabled"}),v.jsx(S0,{atMs:a.lastTriggeredAt,neverLabel:"never triggered"}),v.jsx(TN,{error:a.lastError})]}),v.jsxs("div",{className:"flex items-center justify-center gap-3",children:[v.jsx(jN,{enabled:a.enabled,busy:p,onToggle:f}),v.jsx(PN,{busy:p,large:!0,onTrigger:m})]})]})}function xle({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 DN(e,t){const{cap:n}=ft({trpc:e,deviceId:t,cap:a=>a.switch,slice:a=>a.state.switch});return n!==void 0}function kle({trpc:e,deviceId:t,features:n,optimistic:a}){return DN(e,t)?v.jsx(g0,{trpc:e,deviceId:t,features:n,layout:"compact",optimistic:a}):null}function wle(e,t){const{cap:n}=ft({trpc:e,deviceId:t,cap:a=>a.lockControl,slice:a=>a.state.lockControl});return n!==void 0}function Mle({trpc:e,deviceId:t,features:n,optimistic:a}){return wle(e,t)?v.jsx(Vre,{trpc:e,deviceId:t,features:n,layout:"compact",optimistic:a}):null}function Cle({trpc:e,deviceId:t,features:n,optimistic:a}){return DN(e,t)?v.jsxs("div",{className:"inline-flex items-center gap-2",children:[v.jsx(g0,{trpc:e,deviceId:t,features:n,layout:"compact",optimistic:a}),v.jsx(Gre,{trpc:e,deviceId:t,features:n,layout:"compact",optimistic:a})]}):null}function Ale(e,t){const{cap:n}=ft({trpc:e,deviceId:t,cap:a=>a.fanControl,slice:a=>a.state.fanControl});return n!==void 0}function Ele({trpc:e,deviceId:t,features:n,optimistic:a}){return Ale(e,t)?v.jsxs("div",{className:"inline-flex items-center gap-2",children:[v.jsx(g0,{trpc:e,deviceId:t,features:n,layout:"compact",optimistic:a}),v.jsx(Zre,{trpc:e,deviceId:t,features:n,layout:"compact",optimistic:a})]}):null}function x0(e,t){const{cap:n}=ft({trpc:e,deviceId:t,cap:a=>a.climateControl,slice:a=>a.state.climateControl});return n!==void 0}function Rle({trpc:e,deviceId:t,features:n,optimistic:a}){return x0(e,t)?v.jsx(Wre,{trpc:e,deviceId:t,features:n,layout:"compact",optimistic:a}):null}function _le({trpc:e,deviceId:t,features:n,optimistic:a}){return x0(e,t)?v.jsx(kN,{trpc:e,deviceId:t,features:n,layout:"compact",optimistic:a}):null}function Tle({trpc:e,deviceId:t,features:n,optimistic:a}){return x0(e,t)?v.jsx(kN,{trpc:e,deviceId:t,features:n,layout:"full",optimistic:a}):null}function Ile(e,t){const{cap:n}=ft({trpc:e,deviceId:t,cap:a=>a.mediaPlayer,slice:a=>a.state.mediaPlayer});return n!==void 0}function Nle({trpc:e,deviceId:t,features:n,optimistic:a}){return Ile(e,t)?v.jsx(noe,{trpc:e,deviceId:t,features:n,layout:"compact",optimistic:a}):null}function zN(e,t){const{cap:n}=ft({trpc:e,deviceId:t,cap:a=>a.control,slice:a=>a.state.control});return n!==void 0}function Ole({trpc:e,deviceId:t,features:n,optimistic:a}){return zN(e,t)?v.jsx(K4,{trpc:e,deviceId:t,features:n,layout:"compact",optimistic:a}):null}function jle({trpc:e,deviceId:t,features:n,optimistic:a}){return zN(e,t)?v.jsx(xle,{children:v.jsx(K4,{trpc:e,deviceId:t,features:n,layout:"full",optimistic:a})}):null}var Ple={cover:{InlineControl:Soe,HeroCard:woe},valve:{InlineControl:ose,HeroCard:use},humidifier:{InlineControl:pse,HeroCard:fse},"water-heater":{InlineControl:vse,HeroCard:bse},switch:{InlineControl:kle,HeroCard:lle},light:{InlineControl:Cle,HeroCard:ile},fan:{InlineControl:Ele,HeroCard:sle},sensor:{InlineControl:Eoe,HeroCard:Doe},thermostat:{InlineControl:Rle,HeroCard:Vse},climate:{InlineControl:_le,HeroCard:Tle},button:{InlineControl:Fre,HeroCard:Hre},update:{InlineControl:zoe,HeroCard:Loe},lock:{InlineControl:Mle,HeroCard:Xse},"media-player":{InlineControl:Nle,HeroCard:ple},alarm:{InlineControl:fle,HeroCard:hle},control:{InlineControl:Ole,HeroCard:jle},weather:{InlineControl:kse,HeroCard:Cse},vacuum:{InlineControl:Zoe,HeroCard:Koe},"lawn-mower":{InlineControl:ase,HeroCard:ise},image:{InlineControl:Ase,HeroCard:Ese},"pet-feeder":{InlineControl:Tse,HeroCard:Ise},script:{InlineControl:vle,HeroCard:yle},automation:{InlineControl:ble,HeroCard:Sle},dummy:{InlineControl:Moe,HeroCard:Coe}};Object.fromEntries(Object.values($).map(e=>[e,Ple[HY[e]]]));$.Cover+"",$.Valve+"",$.Thermostat+"",$.Climate+"",$.Control+"",$.Button+"",$.MediaPlayer+"",$.AlarmPanel+"",$.Lock+"",$.Vacuum+"",$.LawnMower+"",$.Humidifier+"",$.Switch+"",$.Siren+"",$.Light+"",$.Fan+"",$.WaterHeater+"",$.Sensor+"",$.Presence+"",$.EventEmitter+"",$.Notifier+"",$.Script+"",$.Automation+"",$.Camera+"",$.Hub+"",$.Update+"",$.Generic+"",$.Weather+"",$.Container+"",$.Image+"",$.PetFeeder+"";new Set(Object.values($));var LN={[$.Camera]:{icon:Iee,label:"Camera"},[$.Hub]:{icon:ate,label:"Hub"},[$.Light]:{icon:wm,label:"Light"},[$.Siren]:{icon:Zp,label:"Siren"},[$.Switch]:{icon:by,label:"Switch"},[$.Sensor]:{icon:qT,label:"Sensor"},[$.Thermostat]:{icon:Cm,label:"Thermostat"},[$.Climate]:{icon:kee,label:"Air conditioner"},[$.Button]:{icon:UT,label:"Button"},[$.EventEmitter]:{icon:Pr,label:"Event Emitter"},[$.Update]:{icon:n0,label:"Update"},[$.Generic]:{icon:j2,label:"Generic"},[$.Notifier]:{icon:Qp,label:"Notifier"},[$.Script]:{icon:dte,label:"Script"},[$.Automation]:{icon:Nte,label:"Automation"},[$.Lock]:{icon:lu,label:"Lock"},[$.Cover]:{icon:Eee,label:"Cover"},[$.Valve]:{icon:ote,label:"Valve"},[$.Humidifier]:{icon:Tte,label:"Humidifier"},[$.WaterHeater]:{icon:Cee,label:"Water heater"},[$.Fan]:{icon:Vp,label:"Fan"},[$.MediaPlayer]:{icon:Jee,label:"Media player"},[$.AlarmPanel]:{icon:Mm,label:"Alarm panel"},[$.Control]:{icon:a0,label:"Control"},[$.Presence]:{icon:Xee,label:"Presence"},[$.Weather]:{icon:HT,label:"Weather"},[$.Vacuum]:{icon:_ee,label:"Vacuum"},[$.LawnMower]:{icon:kte,label:"Lawn mower"},[$.Container]:{icon:j2,label:"Container"},[$.Image]:{icon:Vee,label:"Image"},[$.PetFeeder]:{icon:Ree,label:"Pet feeder"}},Dle={[Qe.Siren]:{icon:Zp,label:"Siren"},[Qe.Floodlight]:{icon:wm,label:"Floodlight"},[Qe.Spotlight]:{icon:Fee,label:"Spotlight"},[Qe.PirSensor]:{icon:XT,label:"PIR sensor"},[Qe.Chime]:{icon:Qp,label:"Chime"},[Qe.Autotrack]:{icon:$T,label:"Auto-track"},[Qe.Nightvision]:{icon:t0,label:"Night vision"},[Qe.PrivacyMask]:{icon:Bee,label:"Privacy mask"},[Qe.Doorbell]:{icon:qee,label:"Doorbell"},[Qe.BinaryHelper]:{icon:by,label:"Binary helper"},[Qe.MotionSensor]:{icon:VT,label:"Motion sensor"},[Qe.ContactSensor]:{icon:il,label:"Contact sensor"},[Qe.LeakSensor]:{icon:Jb,label:"Leak sensor"},[Qe.SmokeSensor]:{icon:wee,label:"Smoke sensor"},[Qe.COSensor]:{icon:Ki,label:"CO sensor"},[Qe.GasSensor]:{icon:Gp,label:"Gas sensor"},[Qe.TamperSensor]:{icon:Mm,label:"Tamper sensor"},[Qe.VibrationSensor]:{icon:aI,label:"Vibration sensor"},[Qe.ConnectivitySensor]:{icon:Ite,label:"Connectivity"},[Qe.SoundSensor]:{icon:pu,label:"Sound sensor"},[Qe.BinarySensor]:{icon:by,label:"Binary sensor"},[Qe.TemperatureSensor]:{icon:Cm,label:"Temperature"},[Qe.HumiditySensor]:{icon:pl,label:"Humidity"},[Qe.AmbientLightSensor]:{icon:tI,label:"Ambient light"},[Qe.PressureSensor]:{icon:fp,label:"Pressure"},[Qe.WindSensor]:{icon:Ki,label:"Wind"},[Qe.RainSensor]:{icon:FT,label:"Rain"},[Qe.UvSensor]:{icon:bte,label:"UV index"},[Qe.SolarRadiationSensor]:{icon:Ste,label:"Solar radiation"},[Qe.SoilMoistureSensor]:{icon:yte,label:"Soil moisture"},[Qe.PowerSensor]:{icon:Pr,label:"Power"},[Qe.EnergySensor]:{icon:Pr,label:"Energy"},[Qe.VoltageSensor]:{icon:Pr,label:"Voltage"},[Qe.CurrentSensor]:{icon:Pr,label:"Current"},[Qe.AirQualitySensor]:{icon:Ki,label:"Air quality"},[Qe.BatterySensor]:{icon:fp,label:"Battery"},[Qe.NumericSensor]:{icon:Qee,label:"Numeric sensor"},[Qe.EnumSensor]:{icon:Wee,label:"Enum sensor"},[Qe.DateTimeSensor]:{icon:D2,label:"Date / time"},[Qe.GenericSensor]:{icon:fp,label:"Sensor"},[Qe.NumericControl]:{icon:a0,label:"Numeric control"},[Qe.SelectControl]:{icon:Kee,label:"Select control"},[Qe.TextControl]:{icon:Ate,label:"Text control"},[Qe.DateTimeControl]:{icon:D2,label:"Date / time control"},[Qe.MobilePushNotifier]:{icon:vte,label:"Mobile push"},[Qe.MessagingNotifier]:{icon:KT,label:"Messaging"},[Qe.EmailNotifier]:{icon:Yee,label:"Email"},[Qe.GenericNotifier]:{icon:Qp,label:"Notifier"}},zle=new Set(Object.values($));new Set(Object.values(Qe));function Lle(e){return zle.has(e)}var IC=LN[$.Generic];Dle[Qe.GenericSensor];function qle(e){return Lle(e)?LN[e]??IC:IC}Object.values($).map(e=>{const t=qle(e);return{id:e,label:t.label,icon:t.icon}});T.createContext(null);$.Sensor,$.Presence;var Ble="/addon/snapshot/media";function che(e,t={}){const{width:n,baseUrl:a}=t,[o,p]=T.useState(0);return{src:T.useMemo(()=>{if(e===null||e<=0)return null;const f=a!==void 0?a.replace(/\/+$/,""):"",m=new URLSearchParams;n!==void 0&&Number.isInteger(n)&&n>0&&m.set("w",String(n)),o>0&&(m.set("force","1"),m.set("r",String(o)));const h=m.toString();return`${f}${Ble}/${String(e)}.jpg${h.length>0?`?${h}`:""}`},[e,n,a,o]),loading:!1,refresh:T.useCallback(()=>{p(f=>f+1)},[])}}d({id:l(),stableId:s(),addonId:s(),type:s(),name:s(),online:E(),disabled:E(),parentDeviceId:l().nullable(),role:s().nullable().optional(),features:M(s()).optional(),isCamera:E().optional()});gi("camstack:player-overlays-state",null);var Ule=gi("camstack:player-overlays-actions",null);function uhe(e){const t=T.useContext(Ule);T.useEffect(()=>{if(!(!t||!e))return t.setLayer(e),()=>t.removeLayer(e.id)},[t,e])}gi("camstack:zone-editing",null);var NC=500,rv=800;function bc(e,t,n){try{const a=e.live;if(!a)return null;const o=a.onEvent;return!o||typeof o.subscribe!="function"?null:o.subscribe({category:t},{onData:n})}catch{return null}}function Wd(e,t){return e?.id===t}function Fle(e,t){const[n,a]=T.useState(null),[o,p]=T.useState(null),[f,m]=T.useState(null),[h,u]=T.useState("watching"),x=T.useRef(void 0),w=T.useRef(void 0),C=T.useRef(void 0),A=T.useRef(0);return T.useEffect(()=>{if(t===null)return;const R=bc(e,"detection.motion-analysis",I=>{const O=I;if(!Wd(O?.source,t))return;const D=O.data;!D?.regions||D.regions.length===0||(a({zones:D.regions.map(z=>({...z.bbox,intensity:z.intensity})),frameWidth:D.frameWidth,frameHeight:D.frameHeight}),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>a(null),NC))});return()=>{R?.unsubscribe(),x.current&&clearTimeout(x.current)}},[e,t]),T.useEffect(()=>{if(t===null)return;const R=bc(e,"detection.motion-zones-raw",I=>{const O=I;if(!Wd(O?.source,t))return;const D=O.data;D?.zones&&(p({boxes:D.zones.map(z=>({bbox:z.bbox,changeScore:z.changeScore})),frameWidth:D.frameSize?.width??0,frameHeight:D.frameSize?.height??0,motionScore:D.zones.length>0?D.zones.reduce((z,B)=>z+B.changeScore,0)/D.zones.length:0}),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>p(null),NC))});return()=>{R?.unsubscribe(),w.current&&clearTimeout(w.current)}},[e,t]),T.useEffect(()=>{if(A.current=0,t===null)return;const R=bc(e,"pipeline-analytics.frame-tracked",I=>{const O=I?.data;!O||O.deviceId!==t||O.detections?.length&&typeof O.detections[0]?.kind=="string"&&(A.current=Date.now(),m({detections:O.detections,frameWidth:O.frameWidth,frameHeight:O.frameHeight}),C.current&&clearTimeout(C.current),C.current=setTimeout(()=>m(null),rv))});return()=>{R?.unsubscribe(),C.current&&clearTimeout(C.current)}},[e,t]),T.useEffect(()=>{if(t===null)return;const R=bc(e,"detection.result",I=>{const O=I;if(!Wd(O?.source,t)||Date.now()-A.current<rv)return;const D=O.data?.frame;D?.detections?.length&&(m({detections:D.detections,frameWidth:D.width,frameHeight:D.height}),C.current&&clearTimeout(C.current),C.current=setTimeout(()=>m(null),rv))});return()=>{R?.unsubscribe(),C.current&&clearTimeout(C.current)}},[e,t]),T.useEffect(()=>{if(t===null)return;const R=bc(e,"detection.phase-transition",I=>{const O=I;Wd(O?.source,t)&&O.data?.to&&u(O.data.to)});return()=>{R?.unsubscribe()}},[e,t]),{motion:n,motionRaw:o,detection:f,phase:h}}var Hle=5*6e4,$le=720*6e4,Qle="camstack:turn-servers:v1";function Vle(){const e=globalThis;try{return e.localStorage??null}catch{return null}}function Gle(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(n=>{if(typeof n!="object"||n===null)return!1;const a=n;return!(!(typeof a.urls=="string"||Array.isArray(a.urls)&&a.urls.every(o=>typeof o=="string"))||a.username!==void 0&&typeof a.username!="string"||a.credential!==void 0&&typeof a.credential!="string")})}var Zle=class{freshTtlMs;staleCapMs;storage;now;storageKey;memory=new WeakMap;inflight=new WeakMap;constructor(e={}){this.freshTtlMs=e.freshTtlMs??Hle,this.staleCapMs=e.staleCapMs??$le,this.storage="storage"in e?e.storage??null:Vle(),this.now=e.now??(()=>Date.now()),this.storageKey=e.storageKey??Qle}async getOrFetch(e,t){const n=this.now(),a=this.memory.get(e)??this.readStorage();if(a){const o=n-a.fetchedAt;if(o<this.freshTtlMs)return a.servers;if(o<this.staleCapMs)return this.startFetch(e,t,a),a.servers}return this.startFetch(e,t,a)}startFetch(e,t,n){const a=this.inflight.get(e);if(a)return a;const o=(async()=>{try{const p=await t();if(p.length>0){const f={servers:p,fetchedAt:this.now()};this.memory.set(e,f),this.writeStorage(f)}return p}catch{return n?.servers}})().finally(()=>{this.inflight.delete(e)});return this.inflight.set(e,o),o}readStorage(){if(this.storage)try{const e=this.storage.getItem(this.storageKey);if(e===null)return;const t=JSON.parse(e);return Gle(t)?t:void 0}catch{return}}writeStorage(e){if(this.storage)try{this.storage.setItem(this.storageKey,JSON.stringify(e))}catch{}}},Kle=new Zle;function qN(e,t,n=5e3){const[a,o]=T.useState([]);T.useEffect(()=>{if(t===null)return;let A=!1;const R=()=>{e.webrtcSession.listStreams.query({deviceId:t}).then(O=>{A||o(O)}).catch(()=>{})};R();const I=setInterval(R,n);return()=>{A=!0,clearInterval(I)}},[e,t,n]);const[p,f]=T.useState(null);T.useEffect(()=>{if(t===null)return;let A=!1;return e.pipelineOrchestrator&&e.pipelineOrchestrator.getCameraMetrics.query({deviceId:t}).then(R=>{A||!R||f({phase:R.phase,detectionFps:R.actualFps,avgInferenceMs:R.avgInferenceTimeMs,droppedFrames:R.droppedFrames})}).catch(()=>{}),()=>{A=!0}},[e,t]),fi("pipeline.camera-metrics-snapshot",A=>{if(t===null)return;const R=A.data;R.deviceId!==t||!R.metrics||f({phase:R.metrics.phase,detectionFps:R.metrics.actualFps,avgInferenceMs:R.metrics.avgInferenceTimeMs,droppedFrames:R.metrics.droppedFrames})});const{streams:m,hasWebrtc:h}=T.useMemo(()=>t===null||a.length===0?{streams:[],hasWebrtc:!1}:{streams:a.map(A=>({id:A.id,label:A.label,target:A.target,status:A.status,inputFps:A.inputFps,decodeFps:A.decodeFps,bitrateKbps:A.bitrateKbps})),hasWebrtc:!0},[t,a]),u=T.useCallback(async()=>{const A=e.turnProvider;if(A)return Kle.getOrFetch(e,async()=>(await A.getTurnServers.query()).map(R=>({urls:typeof R.urls=="string"?R.urls:[...R.urls],...R.username!==void 0?{username:R.username}:{},...R.credential!==void 0?{credential:R.credential}:{}})))},[e]);T.useEffect(()=>{u()},[u]);const x=T.useCallback(async(A,R)=>{if(t===null)throw new Error("No device selected");const I=await e.webrtcSession.createSession.mutate({deviceId:t,target:A,hints:R}),O=await u();return{sessionId:I.sessionId,sdpOffer:I.sdpOffer,...O?{iceServers:O}:{}}},[e,t,u]),w=T.useCallback(async(A,R,I,O)=>{if(t===null)throw new Error("No device selected");return e.webrtcSession.handleOffer.mutate({deviceId:t,target:A,sdpOffer:R,...I!==void 0?{sessionId:I}:{},...O!==void 0?{hints:O}:{}})},[e,t]),C=T.useCallback(async(A,R)=>{if(t===null)throw new Error("No device selected");await e.webrtcSession.handleAnswer.mutate({deviceId:t,sessionId:A,sdpAnswer:R})},[e,t]);return{streams:m,hasWebrtc:h,pipelineMetrics:p,createSession:x,handleOffer:w,getIceServers:u,addIceCandidate:T.useCallback(async(A,R)=>{t!==null&&await e.webrtcSession.addIceCandidate.mutate({deviceId:t,sessionId:A,candidate:R.candidate??"",sdpMid:R.sdpMid??null,sdpMLineIndex:R.sdpMLineIndex??null}).catch(()=>{})},[e,t]),getIceCandidates:T.useCallback(async A=>t===null?{candidates:[],done:!0}:e.webrtcSession.getIceCandidates.query({deviceId:t,sessionId:A}),[e,t]),sendAnswer:C,closeSession:T.useCallback(async A=>{t!==null&&await e.webrtcSession.closeSession.mutate({deviceId:t,sessionId:A}).catch(()=>{})},[e,t]),getSessionState:T.useCallback(async A=>{if(t===null)return{pendingRenegotiation:null};try{return await e.webrtcSession.getSessionState.query({deviceId:t,sessionId:A})}catch{return{pendingRenegotiation:null}}},[e,t])}}T.lazy(()=>Ys(()=>import("./MaskShapeCanvas-DI4BY7W2-D2YOCxqL.js"),[],import.meta.url).then(e=>({default:e.MaskShapeCanvas})));T.lazy(()=>Ys(()=>import("./MotionZonesSettings-DNdnFHso-P9zbA9fe.js"),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.MotionZonesSettings})));T.lazy(()=>Ys(()=>import("./SceneMonitorEditor-d_A4kO-M-DMBYwDxO.js"),__vite__mapDeps([3,1]),import.meta.url).then(e=>({default:e.SceneMonitorEditor})));T.lazy(()=>Ys(()=>import("./PrivacyMaskSettings-DNSLc6ww-DRxNCXl7.js"),__vite__mapDeps([2,1]),import.meta.url).then(e=>({default:e.PrivacyMaskSettings})));const BN=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim();const Wle=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const Yle=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase());const OC=e=>{const t=Yle(e);return t.charAt(0).toUpperCase()+t.slice(1)};var Xle={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const Jle=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1};const ece=T.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:o="",children:p,iconNode:f,...m},h)=>T.createElement("svg",{ref:h,...Xle,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:BN("lucide",o),...!p&&!Jle(m)&&{"aria-hidden":"true"},...m},[...f.map(([u,x])=>T.createElement(u,x)),...Array.isArray(p)?p:[p]]));const tce=(e,t)=>{const n=T.forwardRef(({className:a,...o},p)=>T.createElement(ece,{ref:p,iconNode:t,className:BN(`lucide-${Wle(OC(e))}`,`lucide-${e}`,a),...o}));return n.displayName=OC(e),n};const nce=[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["path",{d:"M9 9h.01",key:"1q5me6"}],["path",{d:"M15 9h.01",key:"x1ddxp"}]],ace=tce("scan-face",nce),tm={unassignedFace:"unassigned face",reviewed:"reviewed",debug:"debug",train:"train",favourite:"favourite",active:"active",loadingMore:"Loading more events"},ice=Object.keys(tm),UN=Y(s(),s());function rce(e){if(e===null||typeof e!="object")return tm;const t=e,n={...tm};for(const a of ice){const o=t[a];typeof o=="string"&&o.trim()!==""&&(n[a]=o)}return{unassignedFace:n.unassignedFace,reviewed:n.reviewed,debug:n.debug,train:n.train,favourite:n.favourite,active:n.active,loadingMore:n.loadingMore}}const oce="/viewer/camstack/embed/index.html",sce=j(["reel","gallery"]),lce=j(["small","medium","large"]),cce=j(["time","importance"]),uce=j(["text","semantic"]),dce=["face","plate"],k0=j(dce),pce=j(["auto","dark","light"]),mce=nt([V("auto"),l().int().min(1).max(12)]),fce=d({label:E(),sublabel:E(),camera:E(),time:E(),badges:E()});d({view:sce,rows:l().int().min(1).max(6).optional(),columns:mce.optional(),thumb:lce,deviceIds:M(l().int().nonnegative()),classes:M(s()).optional(),attrs:M(k0).optional(),search:s().optional(),searchMode:uce.optional(),semanticLimit:l().int().min(1).max(200).optional(),semanticMinScore:l().min(0).max(1).optional(),sort:cce.optional(),sinceMs:l().int().nonnegative().optional(),untilMs:l().int().nonnegative().optional(),deviceNames:Y(s(),s()).optional(),fields:fce,pageSize:l().int().min(1).max(500).optional(),maxRows:l().int().min(1).max(5e3).optional(),refreshMs:l().int().min(0).max(6e5).optional(),maxAgeMs:l().int().min(6e4).optional(),theme:pce});function w0(e){return e.startsWith("/")&&!e.startsWith("//")}function hce(e){return e!==void 0&&e.length>0?{Authorization:`Bearer ${e}`}:{}}function gce(e,t,n){if(!t.endsWith(n))return e;const a=t.slice(0,t.length-n.length);return a.length>0?a:e}function FN(e,t){e.token===void 0&&(w0(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 HN=j(["reel","gallery"]),$N=j(["small","medium","large"]),QN=j(["auto","dark","light"]),VN=d({label:E(),sublabel:E(),camera:E(),time:E(),badges:E()}),GN={label:!0,sublabel:!0,camera:!0,time:!0,badges:!0},ZN=j(["time","importance"]),KN=j(["text","semantic"]),WN=nt([V("auto"),l().int().min(1).max(12)]),vce=60,yce=5e3,bce=600;function Sce(e){return e.view==="reel"?Math.min(e.maxRows,bce):e.maxRows}const xce=0,kce=720*60*60*1e3,wce=d({serverUrl:s().min(1),token:s().min(1).optional(),view:HN.default("reel"),rows:l().int().min(1).max(6).default(1),columns:WN.default("auto"),thumbSize:$N.default("medium"),fields:VN.default(GN),deviceIds:M(l().int().nonnegative()).default([]),classes:M(s()).default([]),attrs:M(k0).catch([]).default([]),deviceNames:Y(s(),s()).default({}),kindLabels:Y(s(),s()).default({}),labels:UN.default({}),strings:d({empty:s().optional(),error:s().optional(),retry:s().optional(),end:s().optional(),loadOlder:s().optional()}).default({}),search:s().default(""),searchMode:KN.default("text"),semanticLimit:l().int().min(1).max(200).default(50),semanticMinScore:l().min(0).max(1).default(.2),sort:ZN.default("time"),filterDebug:E().default(!1),filterTrain:E().default(!1),filterFavourited:E().default(!1),showStationary:E().default(!1),reviewedTrackIds:M(s()).default([]),showAdminFlags:E().default(!1),sinceMs:l().int().nonnegative().optional(),untilMs:l().int().nonnegative().optional(),pageSize:l().int().min(1).max(500).default(vce),maxRows:l().int().min(1).max(5e3).default(yce),refreshMs:l().int().min(0).max(6e5).default(xce),maxAgeMs:l().int().min(6e4).default(kce),theme:QN.default("auto"),nativePullToRefresh:E().default(!1)}).superRefine(FN),YN=d({view:HN.optional(),rows:l().int().min(1).max(6).optional(),columns:WN.optional(),thumbSize:$N.optional(),fields:VN.partial().optional(),deviceIds:M(l().int().nonnegative()).optional(),classes:M(s()).optional(),attrs:M(k0).optional(),deviceNames:Y(s(),s()).optional(),kindLabels:Y(s(),s()).optional(),labels:UN.optional(),strings:d({empty:s().optional(),error:s().optional(),retry:s().optional(),end:s().optional(),loadOlder:s().optional()}).optional(),search:s().optional(),searchMode:KN.optional(),semanticLimit:l().int().min(1).max(200).optional(),semanticMinScore:l().min(0).max(1).optional(),sort:ZN.optional(),filterDebug:E().optional(),filterTrain:E().optional(),filterFavourited:E().optional(),showStationary:E().optional(),reviewedTrackIds:M(s()).optional(),showAdminFlags:E().optional(),sinceMs:l().int().nonnegative().nullable().optional(),untilMs:l().int().nonnegative().nullable().optional(),pageSize:l().int().min(1).max(500).optional(),maxRows:l().int().min(1).max(5e3).optional(),refreshMs:l().int().min(0).max(6e5).optional(),maxAgeMs:l().int().min(6e4).optional(),theme:QN.optional(),nativePullToRefresh:E().optional()});function M0(e){return e==="small"?80:e==="large"?132:106}function Mce(e,t=1){const n=Number.isFinite(t)&&t>0?t:1,a=Math.round(M0(e)*n);return Math.max(Cce,Math.min(Ace,a))}const Cce=64,Ace=320,Ep=3,Rp=14,Ece=4;function Rce(e){return M0(e)+Ep*2+Rp}function XN(e){if(e==null)return{ok:!1,error:"config is required"};const t=wce.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(n=>`${n.path.join(".")||"(root)"}: ${n.message}`).join("; ")}}function By(e,t){const n=t.fields!==void 0?{...e.fields,...t.fields}:e.fields,{sinceMs:a,untilMs:o,...p}=t,{sinceMs:f,untilMs:m,...h}=e,u=jC(a,f),x=jC(o,m);return{...h,...p,fields:n,...u!==void 0?{sinceMs:u}:{},...x!==void 0?{untilMs:x}:{}}}function jC(e,t){if(e!==null)return e??t}function _ce(e,t,n){const a=n[String(e)];return a!==void 0&&a.trim().length>0?a:t}const Tce={empty:"No events",error:"Couldn't load events",retry:"Retry",end:"·",loadOlder:"Load older events"};function Is(e,t){const n=e.strings[t];return n!==void 0&&n.trim().length>0?n:Tce[t]}const Ice="/addon/pipeline-analytics/event-media",PC=64,Nce=320;function Oce(e){return e.replace(/\/+$/,"")}function jce(e){const t=Math.round(e);return Number.isFinite(t)?Math.max(PC,Math.min(Nce,t)):PC}function JN(e,t,n){return`${Oce(e)}${Ice}/${t}?kind=thumbnailSmall&variant=thumb&size=${jce(n)}`}const Pce="audio";function nm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Dce(e){const t=new Map;if(!Array.isArray(e))return t;for(const n of e){if(!nm(n))continue;const a=n.kinds;if(Array.isArray(a))for(const o of a){if(!nm(o))continue;const p=o.kind;if(typeof p!="string"||p.length===0)continue;const f=o.parentKind;t.set(p,typeof f=="string"&&f.length>0?f:p)}}return t}function e5(e,t){return t.get(e)??e}const DC="audio-",zC="audio";function fu(e){const t=e.toLowerCase();return t.startsWith(DC)?t:`${DC}${t}`}function zce(e){const t=new Map;if(!Array.isArray(e))return t;for(const n of e){if(!nm(n))continue;const a=n.kinds;if(Array.isArray(a))for(const o of a){if(!nm(o))continue;const p=o.kind,f=o.iconId;typeof p!="string"||p.length===0||typeof f!="string"||f.length===0||t.set(p,f)}}return t}function Lce(e,t,n=!1){if(n){const o=t.get(e);if(o!==void 0)return o;if(e.toLowerCase()===zC)return zC;const p=fu(e);return t.get(p)??p}const a=e.toLowerCase();return t.get(e)??t.get(a)??a}function qce(e){const t=new Map;for(const[n,a]of Object.entries(e)){if(n.length===0||a.length===0)continue;t.set(n,a);const o=n.toLowerCase();t.has(o)||t.set(o,a)}return t}const C0=new Map;function _p(e,t){return t.get(e)??t.get(e.toLowerCase())??e}function t5(e,t){const n=fu(e);return t.get(n)??t.get(e)??e}const LC={background:"#09090b",card:"#18181b",cardHover:"#27272a",border:"#27272a",text:"#fafafa",textMuted:"#a1a1aa",skeleton:"#27272a",chip:"#3f3f46",colorScheme:"dark"},qC={background:"#ffffff",card:"#f4f4f5",cardHover:"#e4e4e7",border:"#e4e4e7",text:"#18181b",textMuted:"#71717a",skeleton:"#e4e4e7",chip:"#d4d4d8",colorScheme:"light"};function n5(e,t){return e==="light"?qC:e==="dark"||t?LC:qC}const Uy="#f472b6";function Bce(e,t=!1){if(t)return Uy;const n=e.toLowerCase();return n.includes("person")||n.includes("face")?"#38bdf8":n.includes("vehicle")||n.includes("car")||n.includes("truck")||n.includes("plate")?"#a78bfa":n.includes("animal")||n.includes("dog")||n.includes("cat")||n.includes("bird")?"#fbbf24":n.includes("package")||n.includes("parcel")?"#34d399":n.includes("audio")||n.includes("sound")?Uy:n.includes("motion")?"#94a3b8":"#71717a"}function Uce(e){return new Date(e).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}function Fce(e,t){const n=new Date(e),a=new Date(t),o=String(n.getHours()).padStart(2,"0"),p=String(n.getMinutes()).padStart(2,"0");if(n.getFullYear()===a.getFullYear()&&n.getMonth()===a.getMonth()&&n.getDate()===a.getDate())return`${o}:${p}`;const m=String(n.getDate()).padStart(2,"0"),h=String(n.getMonth()+1).padStart(2,"0");return`${m}/${h} ${o}:${p}`}const Hce=/[_\-/.]+/g;function a5(e){return e.toLowerCase().replace(Hce," ").replace(/\s+/g," ").trim()}function $ce(e){if(e===void 0)return[];const t=e.trim().toLowerCase();if(t.length===0)return[];const n=a5(e);return n===t||n.length===0?[t]:[t,n]}const _m=new Map,Qce=new Set(["plate-detection","plate-ocr","operator:plate-gallery"]),BC=new Set(["face-recognizer","face-embedding","operator:face-gallery"]),Vce=[];function ov(e,t){if(!A0(e))return!1;const n=e.stepId;return typeof n=="string"&&t.has(n)}function i5(e){return e.source==="audio"}function A0(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Nr(e){return typeof e=="string"&&e.length>0?e:void 0}function sv(e){if(!Array.isArray(e))return[];const t=[];for(const n of e)typeof n=="string"&&n.length>0&&!t.includes(n)&&t.push(n);return t}function Gce(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const a=A0(n)?Nr(n.label):void 0;a!==void 0&&!t.includes(a)&&t.push(a)}return t}function Zce(e,t){if(!A0(e))return null;const n=Nr(e.trackId),a=Nr(e.className);if(n===void 0||a===void 0||typeof e.deviceId!="number"||typeof e.firstSeen!="number"||typeof e.lastSeen!="number")return null;const o=Nr(e.label),p=Nr(e.subLabel),f=Nr(e.producingDeviceName),m=Nr(e.source),h=sv(e.classes);return{trackId:n,deviceId:e.deviceId,cameraName:t.get(e.deviceId)??`Camera ${e.deviceId}`,className:a,...o!==void 0?{label:o}:{},...p!==void 0?{subLabel:p}:{},...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:sv(e.zonesVisited),zoneNames:sv(e.zoneNames),classes:h.includes(a)?h:[a,...h],audioLabels:Gce(e.audioLabels),bestEventId:Nr(e.bestEventId)??n,...f!==void 0?{producingDeviceName:f}:{},...m!==void 0?{source:m}:{},...e.hasEmbeddedFace===!0||ov(e.subLabelMeta,BC)?{hasAssignableFace:!0}:{},...e.hasEmbeddedFace===!0&&!ov(e.subLabelMeta,BC)?{hasUnassignedFace:!0}:{},...ov(e.subLabelMeta,Qce)?{hasPlate:!0}:{},...e.debug===!0?{debug:!0}:{},...e.markForTrain===!0?{markForTrain:!0}:{},...e.favourited===!0?{favourited:!0}:{}}}function UC(e,t){if(!Array.isArray(e))return[];const n=[];for(const a of e){const o=Zce(a,t);o!==null&&n.push(o)}return n}function Kce(e,t){const n=new Set;for(const a of[e.className,...e.classes])a.length!==0&&(n.add(a),n.add(e5(a,t)));if(e.audioLabels.length>0){n.add(Pce);for(const a of e.audioLabels)n.add(fu(a))}return n}function Wce(e,t,n=_m){if(t.size===0)return!0;const a=Kce(e,n);for(const o of t)if(a.has(o))return!0;return!1}function Yce(e,t=_m){const n=new Set,a=o=>{for(const p of $ce(o))n.add(p)};for(const o of[e.className,...e.classes])a(o),o.length>0&&a(e5(o,t));a(e.label),a(e.subLabel),a(e.cameraName),a(e.producingDeviceName);for(const o of e.audioLabels)a(o),a(fu(o));for(const o of e.zoneNames)a(o);for(const o of[e.label,e.subLabel]){if(o===void 0)continue;const p=t.get(o.trim().toLowerCase());p!==void 0&&a(p)}return n}function Xce(e,t,n=_m){const a=t.trim().toLowerCase();if(a.length===0)return!0;const o=a5(t);for(const p of Yce(e,n))if(p.includes(a)||o.length>0&&p.includes(o))return!0;return!1}function Jce(e,t){return!!(t.size===0||t.has("face")&&e.hasAssignableFace===!0||t.has("plate")&&e.hasPlate===!0)}function eue(e,t={}){const n=t.debug===!0,a=t.train===!0,o=t.favourited===!0;if(!n&&!a&&!o)return!0;const p=t.reviewedTrackIds?.includes(e.trackId)===!0;return!!(n&&e.debug===!0&&!p||a&&e.markForTrain===!0||o&&e.favourited===!0)}function FC(e,t,n,a=_m,o=Vce,p={}){const f=new Set(t),m=new Set(o);return e.filter(h=>Wce(h,f,a)&&Jce(h,m)&&Xce(h,n,a)&&eue(h,p))}function tue(e,t=C0){return e.producingDeviceName!==void 0?{text:_p(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:_p(e.label,t),tier:"kind"}:{text:_p(e.className,t),tier:"class"}}function nue(e,t,n,a=C0){if(t)return"";const o=[n];for(const p of e.audioLabels){if(p===e.className||p===e.label)continue;const f=t5(p,a);o.includes(f)||o.push(f)}return o.join(" · ")}function HC(e,t){let n=!1;const a=e.map(o=>{const p=t.get(o.deviceId);return p===void 0||p===o.cameraName?o:(n=!0,{...o,cameraName:p})});return n?a:e}function $C(e,t){if(Object.keys(t).length===0)return e;let a=!1;const o=e.map(p=>{const f=t[p.trackId];if(f===void 0)return p;const m=iue(p,f);return m!==p&&(a=!0),m});return a?o:e}function aue(e){const{debug:t,markForTrain:n,favourited:a,...o}=e;return o}function iue(e,t){const n=t.debug===!0?!0:t.debug===!1?void 0:e.debug,a=t.markForTrain===!0?!0:t.markForTrain===!1?void 0:e.markForTrain,o=t.favourited===!0?!0:t.favourited===!1?void 0:e.favourited;return n===e.debug&&a===e.markForTrain&&o===e.favourited?e:{...aue(e),...n===!0?{debug:!0}:{},...a===!0?{markForTrain:!0}:{},...o===!0?{favourited:!0}:{}}}function rue(e){const t=e.filter(n=>n.isCamera===!0).map(n=>n.id);return t.length>0?t:e.map(n=>n.id)}const Fy=11,QC=9,lv=3,oue=8,sue=12,lue=24,cue=.58,uue=.85;function due(e,t){return[...e].length*t*cue}function pue(e){return Math.max(lue,e-oue-sue)}function VC(e,t,n){const a=pue(t),o=n.maxLines===1?a:a*n.maxLines*uue;return due(e,n.fontSizePx)<=o}function mue(e,t){for(let n=1;n<=lv;n+=1){const a={fontSizePx:Fy,maxLines:n};if(VC(e,t,a))return a}for(let n=Fy-1;n>=QC;n-=1){const a={fontSizePx:n,maxLines:lv};if(VC(e,t,a))return a}return{fontSizePx:QC,maxLines:lv}}const fue=1e4;function r5(){try{return window.parent!==window}catch{return!0}}let Hy=null;function o5(e){Hy=e}function hue(e){if(Hy===null||typeof e!="object"||e===null)return e;const t=e;if(t.type!=="log")return e;const n=typeof t.data=="object"&&t.data!==null?t.data:{};return{...t,data:{deviceId:Hy,...n}}}function an(e){const t=hue(e),n=window.ReactNativeWebView;if(n){n.postMessage(JSON.stringify(t));return}r5()&&window.parent.postMessage(t,"*")}function hu(e){const t=n=>{const a=n.data;if(typeof a!="object"||a===null)return;const o=a;o.type!=="embed-command"||typeof o.command!="object"||o.command===null||e(o.command)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}function gue(e,t,n,a,o){const p=t();if(p!=null)return Promise.resolve(n(p));if(o?.urlFirst===!0){const f=a!==void 0?a():null;if(f!==null)return Promise.resolve(f)}if(!r5()){const f=a!==void 0?a():null;return f!==null?Promise.resolve(f):Promise.resolve({ok:!1,error:`config global for mode "${e}" is not set`})}return new Promise(f=>{let m;const h=u=>{const x=u.data;if(typeof x!="object"||x===null)return;const w=x;w.type==="embed-config"&&(clearTimeout(m),window.removeEventListener("message",h),f(n(w.config)))};window.addEventListener("message",h),m=setTimeout(()=>{window.removeEventListener("message",h),f({ok:!1,error:"config handshake timed out"})},fue),window.parent.postMessage({type:"embed-ready",mode:e},"*")})}function Tm(e,t,n,a,o){const[p,f]=T.useState(null),m=T.useRef(t);m.current=t;const h=T.useRef(n);h.current=n;const u=T.useRef(a);u.current=a;const x=o?.urlFirst===!0;return T.useEffect(()=>{let w=!0;return gue(e,()=>m.current(),C=>h.current(C),()=>u.current!==void 0?u.current():null,{urlFirst:x}).then(C=>{w&&f(C)}),()=>{w=!1}},[e,x]),p}const Ga=1,vue=["window","sort","semantic-search","macro-classes","device-names","kind-labels","heartbeat","track-list","attr-filters","flag-filters","debug-status","native-pull-refresh","track-list-delta"];function yue(e){return{v:Ga,type:"ready",view:e,features:[...vue]}}function bue(e){return{v:Ga,type:"error",message:e}}function Tp(e,t){return t!==void 0?{v:Ga,type:"state",state:e,message:t}:{v:Ga,type:"state",state:e}}function Sue(e){return{v:Ga,type:"trackClick",...e}}function xue(e,t){return{v:Ga,type:"trackList",tracks:e,seq:t}}function kue(e){return{v:Ga,type:"trackListDelta",...e}}function GC(e,t,n,a="feed"){return{v:Ga,type:"countChanged",loaded:e,shown:t,hasMore:n,mode:a}}function wue(){return{v:Ga,type:"heartbeat"}}function Mue(e){return{v:Ga,type:"scroll",atTop:e}}function Cue(){return{v:Ga,type:"refreshed"}}function Da(e){an(e)}function mi(e,t,n="feed"){an({type:"log",scope:n,msg:e,...t!==void 0?{data:t}:{}})}const Aue=j(["full","delta"]),Eue=d({debug:E().optional(),markForTrain:E().optional(),favourited:E().optional()}),Rue=Y(s(),Eue);function Sc(e){if(typeof e!="object"||e===null)return null;const t=e,n=t.type;if(n==="refresh"||n==="reload"||n==="loadMore"||n==="scrollToTop"||n==="ping")return{type:n};if(n==="setWindow"){const o=_ue.safeParse(t);return o.success?{type:"setWindow",...o.data.sinceMs!==void 0?{sinceMs:o.data.sinceMs}:{},...o.data.untilMs!==void 0?{untilMs:o.data.untilMs}:{}}:null}if(n==="setTrackListMode"){const o=Aue.safeParse(t.mode);return o.success?{type:"setTrackListMode",mode:o.data}:null}if(n==="setTrackFlagPatches"){const o=Rue.safeParse(t.patches);return o.success?{type:"setTrackFlagPatches",patches:o.data}:null}if(n!=="setConfig")return null;const a=YN.safeParse(t.patch);return a.success?{type:"setConfig",patch:a.data}:null}const _ue=d({sinceMs:l().int().nonnegative().nullable().optional(),untilMs:l().int().nonnegative().nullable().optional()});function Tue(e){return{...e.sinceMs!==void 0?{sinceMs:e.sinceMs}:{},...e.untilMs!==void 0?{untilMs:e.untilMs}:{}}}const Iue={blockedMs:0,maxLagMs:0,samples:0};function Nue(e,t,n){if(n<=t)return Iue;let a=0,o=0,p=0;for(const f of e){const m=f.at-f.lagMs,h=Math.min(f.at,n)-Math.max(m,t);h<=0||(a+=h,o=Math.max(o,f.lagMs),p+=1)}return{blockedMs:Math.round(a),maxLagMs:Math.round(o),samples:p}}function $y(e,t){const n=Math.min(Math.round(e),t.blockedMs);return{ms:Math.round(e),blockedMs:n,netMs:Math.max(0,Math.round(e)-n),maxLagMs:t.maxLagMs,lagSamples:t.samples}}const Oue=250,ZC=600,jue=8;let Ds=[],KC=null;function Pue(e){e.lagMs<jue||(Ds.push(e),Ds.length>ZC&&(Ds=Ds.slice(Ds.length-ZC)))}function Qy(e,t){return Nue(Ds,e,t)}function Due(e=Oue,t=()=>performance.now(),n=(a,o)=>{const p=setInterval(a,o);return()=>clearInterval(p)}){if(KC!==null)return;let a=t()+e;KC={stop:n(()=>{const p=t();Pue({at:p,lagMs:Math.max(0,p-a)}),a=p+e},e)}}function zue(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 Lue(e,t){let n=null;for(const a of e)a.startTime+1<t||(n===null||a.startTime<n.startTime)&&(n=a);return n}function que(){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:(n,a)=>t.call(performance,n,a)}}function Bue(e,t,n=que()){if(n===null)return null;try{const a=Lue(n.getEntriesByName(e,"resource"),t);return a===null?null:zue(a)}catch{return null}}const Uue=250,Gi=new Map,cv=new Map,Fue=6,Hue=1e4,$ue=5e3,uv=[250,750];let dv=40;const WC=32;function Que(e){try{const t=new URL(e),n=t.pathname.lastIndexOf("/"),a=n>=0?`${t.pathname.slice(0,n)}/<id>`:t.pathname;return{origin:t.origin,path:a,query:t.search}}catch{const t=e.slice(0,WC);return{origin:"(unparseable)",path:e.length>WC?`${t}…`:t,query:""}}}function Vue(e){return e instanceof Error?{errorName:e.name,errorMessage:e.message}:{errorName:"unknown",errorMessage:String(e)}}let am=0,s5=[];async function Gue(){if(am<Fue){am+=1;return}await new Promise(e=>{s5.push(e)})}function Zue(){const e=s5.shift();if(e!==void 0){e();return}am=Math.max(0,am-1)}function Kue(e,t){for(Gi.set(e,t);Gi.size>Uue;){const n=Gi.keys().next();if(n.done===!0)break;const a=Gi.get(n.value);Gi.delete(n.value),a!==void 0&&URL.revokeObjectURL(a)}}async function l5(e,t){const n=Gi.get(e);if(n!==void 0)return Gi.delete(e),Gi.set(e,n),{status:"ready",src:n};const a=cv.get(e);if(a!==void 0)return a;const o=(async()=>{const p=performance.now(),f=Que(e);let m={lastStatus:null,errorName:null,errorMessage:null},h=0;try{for(let u=0;u<=uv.length;u+=1){const x=performance.now();await Gue(),h+=performance.now()-x;const w=performance.now(),C=new AbortController,A=setTimeout(()=>C.abort(),Hue);try{const I=await fetch(e,{headers:hce(t),signal:C.signal});if(I.ok){const O=Math.round(performance.now()-w),D=await I.blob(),z=Math.round(performance.now()-p),B=Math.round(performance.now()-w),q=URL.createObjectURL(D);if(Kue(e,q),dv>0||z>=500){dv=Math.max(0,dv-1);const G=Bue(e,w),ae=$y(performance.now()-w,Qy(w,performance.now()));mi("thumbnail ready",{ms:z,queuedMs:Math.round(h),headersMs:O,blobMs:B-O,blockedMs:ae.blockedMs,maxLagMs:ae.maxLagMs,netTotalMs:G?.totalMs??null,netQueuedMs:G?.queuedMs??null,netTtfbMs:G?.ttfbMs??null,bytes:D.size,attempt:u+1,serverTiming:I.headers?.get("server-timing")??null},"media")}return{status:"ready",src:q}}if(I.status===401||I.status===403||I.status===404)return mi("thumbnail missing",{ms:Math.round(performance.now()-p),queuedMs:Math.round(h),status:I.status,attempt:u+1,...f},"media"),{status:"missing"};m={lastStatus:I.status,errorName:null,errorMessage:null}}catch(I){m={lastStatus:null,...Vue(I)}}finally{clearTimeout(A),Zue()}const R=uv[u];R!==void 0&&await new Promise(I=>setTimeout(I,R))}return mi("thumbnail transient failure",{ms:Math.round(performance.now()-p),queuedMs:Math.round(h),attempts:uv.length+1,...m,...f},"media"),{status:"transient-failure"}}finally{cv.delete(e)}})();return cv.set(e,o),o}async function Wue(e,t){const n=await l5(e,t);return n.status==="ready"?n.src:null}function Yue(e,t){const[n,a]=T.useState({status:"loading"}),[o,p]=T.useState(0);return T.useEffect(()=>{if(e===null){a({status:"loading"});return}const f=Gi.get(e);if(f!==void 0){a({status:"ready",src:f});return}let m=!0,h;return a({status:"loading"}),l5(e,t).then(u=>{if(m){if(u.status==="ready"){a({status:"ready",src:u.src});return}if(u.status==="missing"){a({status:"failed"});return}h=setTimeout(()=>p(x=>x+1),$ue)}}),()=>{m=!1,h!==void 0&&clearTimeout(h)}},[e,t,o]),n}function Xue(e){const t=e?.clientHeight??0;return t>0?t:600}function Jue(e,t){const{root:n,disabled:a}=t,[o,p]=T.useState(a===!0),f=T.useRef(o);return f.current=o,T.useEffect(()=>{if(f.current)return;if(a===!0){p(!0);return}const m=e.current;if(!m||typeof IntersectionObserver!="function"){p(!0);return}const h=new IntersectionObserver(u=>{u.some(x=>x.isIntersecting)&&(p(!0),h.disconnect())},{root:n,rootMargin:`${Xue(n)}px`});return h.observe(m),()=>h.disconnect()},[e,n,a]),o}const Yd={display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:14,height:14,padding:"0 3px",borderRadius:4,background:"#000000B3",color:"#fff",fontSize:9,fontWeight:700,lineHeight:"14px",letterSpacing:.2},ede=T.memo(function({row:t,serverUrl:n,token:a,thumbPx:o,width:p,heroPx:f,fields:m,palette:h,nowMs:u,variant:x,iconId:w,kindLabels:C=C0,labels:A=tm,scrollRoot:R,eagerImages:I,showAdminFlags:O,onClick:D}){const z=T.useRef(null),q=Jue(z,{root:R,...I===!0?{disabled:!0}:{}})?JN(n,t.bestEventId,o):null,G=Yue(q,a),ae=Bce(t.className,i5(t)),Q=x==="reel",H=f+Ep*2+Rp,oe=tue(t,C),we=oe.tier!=="class",Me=!we,Ae=mue(oe.text,f),Ce=m.label,re=nue(t,Ce,oe.text,C),Te=F2(w),F=v.jsxs("div",{style:{position:"relative",width:Q?f:"100%",height:Q?f:void 0,aspectRatio:Q?void 0:"1 / 1",borderRadius:10,overflow:"hidden",background:h.skeleton,border:`1px solid ${h.border}`,boxSizing:"border-box",flex:"0 0 auto"},children:[v.jsx("div",{className:G.status==="loading"?"events-skeleton":void 0,"data-testid":"card-image-backing",style:{position:"absolute",inset:0,background:G.status==="failed"?`${ae}22`:h.skeleton,boxShadow:`inset 0 0 0 1px ${h.border}`}}),G.status==="ready"?v.jsx("img",{src:G.src,alt:"",draggable:!1,style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover",display:"block"}}):null,m.label&&v.jsxs("div",{style:{position:"absolute",left:4,right:4,bottom:4,display:"flex",flexWrap:Q?"nowrap":"wrap",gap:3,alignItems:"center",pointerEvents:"none"},children:[Me&&v.jsx("span",{"data-testid":"card-class-glyph",title:_p(t.className,C),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",background:`${ae}E6`,color:"#fff",borderRadius:4,padding:"2px 4px",flex:"0 0 auto"},children:v.jsx(Te,{size:13,color:"#fff"})}),we&&v.jsx("span",{"data-testid":"card-title",title:oe.fullText??oe.text,style:{background:"#000000B3",color:"#fff",fontSize:Q?Fy:Ae.fontSizePx,fontWeight:700,lineHeight:1.35,padding:"2px 6px",borderRadius:4,overflow:"hidden",minWidth:0,...Q?{textOverflow:"ellipsis",whiteSpace:"nowrap"}:{display:"-webkit-box",WebkitLineClamp:Ae.maxLines,WebkitBoxOrient:"vertical",whiteSpace:"normal",overflowWrap:"anywhere"}},children:oe.text}),t.hasUnassignedFace===!0&&v.jsxs("span",{"data-testid":"card-face-unassigned",title:A.unassignedFace,style:{display:"inline-flex",alignItems:"center",gap:3,background:"#000000B3",color:"#fff",fontSize:11,fontWeight:700,lineHeight:1.35,padding:"2px 6px",borderRadius:4,flex:"0 0 auto"},children:[v.jsx(ace,{size:13,color:"#fff"}),"?"]}),!Q&&t.audioLabels.filter(fe=>fe!==t.className&&fe!==t.label).map(fe=>{const L=fu(fe),ee=F2(L);return v.jsx("span",{title:t5(fe,C),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",background:`${Uy}E6`,color:"#fff",borderRadius:4,padding:"2px 4px",flex:"0 0 auto"},children:v.jsx(ee,{size:13,color:"#fff"})},`audio-${fe}`)})]}),(O===!0&&(t.debug===!0||t.reviewed===!0||t.markForTrain===!0)||t.favourited===!0)&&v.jsxs("span",{"data-testid":"card-flags",style:{position:"absolute",top:4,right:m.badges&&t.active?16:4,display:"inline-flex",gap:2,zIndex:2},children:[O===!0&&t.reviewed===!0&&v.jsx("span",{title:A.reviewed,style:Yd,children:"✓"}),O===!0&&t.debug===!0&&t.reviewed!==!0&&v.jsx("span",{title:A.debug,style:Yd,children:"D"}),O===!0&&t.markForTrain===!0&&v.jsx("span",{title:A.train,style:Yd,children:"T"}),t.favourited===!0&&v.jsx("span",{title:A.favourite,style:{...Yd,color:"#fbbf24"},children:"★"})]}),m.badges&&t.active&&v.jsx("span",{title:A.active,style:{position:"absolute",top:4,right:4,width:8,height:8,borderRadius:999,background:"#22c55e",boxShadow:"0 0 0 2px rgba(0,0,0,0.35)"}}),m.badges&&!Q&&t.importance!==void 0&&v.jsxs("span",{"data-testid":"card-importance",style:{position:"absolute",top:4,left:4,display:"inline-flex",alignItems:"center",gap:2,background:"#000000B3",color:"#fff",fontSize:10,fontWeight:700,fontVariantNumeric:"tabular-nums",padding:"1px 5px",borderRadius:8},children:["★",Math.round(t.importance*100)]})]});if(Q)return v.jsxs("button",{ref:z,type:"button",onClick:()=>D(t),"data-track-id":t.trackId,"data-device-id":t.deviceId,style:{width:p,height:H,minWidth:p,minHeight:H,display:"flex",flexDirection:"column",alignItems:"center",padding:0,border:"none",background:"transparent",cursor:"pointer",font:"inherit",color:h.text,boxSizing:"border-box",contain:"layout paint",overflow:"hidden"},children:[F,v.jsxs("div",{style:{paddingTop:Ep,paddingBottom:Ep,paddingLeft:4,paddingRight:4,display:"flex",flexDirection:"column",alignItems:"center",maxWidth:"100%",boxSizing:"border-box"},children:[m.camera&&t.producingDeviceName!==void 0&&v.jsx("span",{style:{fontSize:11,lineHeight:`${Rp}px`,fontWeight:600,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.producingDeviceName}),m.time&&v.jsx("span",{"data-testid":"card-time",style:{fontSize:11,lineHeight:`${Rp}px`,color:h.textMuted,fontVariantNumeric:"tabular-nums",whiteSpace:"nowrap"},children:Uce(t.lastSeen)})]})]});const ue=m.camera,ke=t.cameraName,Ee=ue||m.time||m.sublabel&&re.length>0;return v.jsxs("button",{ref:z,type:"button",onClick:()=>D(t),"data-track-id":t.trackId,"data-device-id":t.deviceId,style:{width:p,display:"flex",flexDirection:"column",gap:4,padding:0,border:"none",background:"transparent",cursor:"pointer",textAlign:"left",font:"inherit",color:h.text,boxSizing:"border-box"},children:[F,Ee&&v.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:1,minWidth:0,paddingTop:2,paddingBottom:2},children:[m.sublabel&&re.length>0&&v.jsx("span",{style:{fontSize:11,color:h.textMuted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:re}),ue&&v.jsx("span",{"data-testid":"card-camera",title:ke,style:{fontSize:12,fontWeight:600,lineHeight:"15px",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:ke}),m.time&&v.jsx("span",{"data-testid":"card-time",style:{fontSize:11,lineHeight:"14px",color:h.textMuted,fontVariantNumeric:"tabular-nums",whiteSpace:"nowrap",flex:"0 0 auto"},children:Fce(t.lastSeen,u)}),m.badges&&t.zonesVisited.length>0&&v.jsx("span",{style:{fontSize:10,color:h.textMuted,background:h.chip,borderRadius:5,padding:"1px 5px",alignSelf:"flex-start",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"100%"},children:t.zonesVisited.join(" · ")})]})]})});function tde(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 nde=2e3,ade=1e3;function YC(e,t){const n=Math.max(1,Math.floor(e)),a=Math.max(1,Math.floor(t)),o=Math.max(1,Math.floor(nde/a));return Math.min(n,ade,o)}function E0(e,t){return e.lastSeen!==t.lastSeen?t.lastSeen-e.lastSeen:e.trackId===t.trackId?0:e.trackId<t.trackId?1:-1}const Mc={rows:[],cursor:null,exhausted:!1,rebuild:null},ide=8;function Vy(e,t){const n=new Map;for(const a of e)n.set(a.trackId,a);for(const a of t)n.set(a.trackId,a);return[...n.values()].sort(E0)}function rde(e,t,n){const a=e.rebuild;if(a===null)return{rows:Vy(e.rows,t),cursor:n,exhausted:n===null,rebuild:null};const o=Vy(a.rows,t),p=a.pages+1,f=o.length>=a.floor;return n===null||f||p>=ide?{rows:o,cursor:n,exhausted:n===null,rebuild:null}:{...e,rebuild:{rows:o,cursor:n,exhausted:!1,floor:a.floor,pages:p}}}function ode(e){return e.rows.length===0?Mc:{...e,rebuild:{rows:[],cursor:null,exhausted:!1,floor:e.rows.length,pages:0}}}function sde(e){return e.rebuild===null?e:{...e,rebuild:null}}function lde(e){return e.rebuild!==null}function XC(e){return e.rebuild!==null?e.rebuild.cursor:e.cursor}function cde(e,t,n){const a=new Set(e.rows.map(p=>p.trackId));let o=0;for(const p of t)a.has(p.trackId)||(o+=1);return{state:{...e,rows:Vy(e.rows,t)},gap:n!==null,deltaCursor:n,added:o}}function ude(e){const t=e.rows[0];return t!==void 0?t.lastSeen:null}function c5(e,t){const n=e.rebuild??e;return n.exhausted?"exhausted":n.rows.length<Math.max(1,t)?"more":"ceiling"}function JC(e,t){return c5(e,t)==="more"}function dde(e,t){return Math.max(0,e-Math.max(0,t))}function pde(e){const t=e.sinceMs??dde(e.anchorMs,e.maxAgeMs);return e.untilMs!==void 0?{since:t,until:e.untilMs}:{since:t}}function mde(e,t){return e===void 0||e>t}function u5(e,t){return t==="time"?e:[...e].sort((n,a)=>{const o=n.importance??-1,p=a.importance??-1;return o!==p?p-o:E0(n,a)})}const eA=200,fde=45;function Gy(e){return{trackId:e.trackId,deviceId:e.deviceId,bestEventId:e.bestEventId,className:e.className,firstSeen:e.firstSeen,lastSeen:e.lastSeen}}function Zy(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function hde(e,t){const n=t.map(A=>A.trackId);if(Zy(e,n))return{kind:"unchanged"};if(e.length===0)return{kind:"reset"};const a=new Set(e);let o=n.length-1,p=e.length-1,f=n.length;for(;o>=0&&!a.has(n[o]);)f=o,o-=1;const m=[];for(;o>=0&&p>=0;){if(n[o]===e[p]){o-=1,p-=1;continue}m.push(e[p]),p-=1}const h=o+1;for(;p>=0;)m.push(e[p]),p-=1;const u=new Set(m),x=[...n.slice(0,h),...e.filter(A=>!u.has(A)),...n.slice(f)];if(!Zy(x,n))return{kind:"reset"};const w=h+(n.length-f);return eA*w+fde*m.length>=eA*n.length?{kind:"reset"}:{kind:"delta",prepend:t.slice(0,h).map(Gy),append:f===n.length?[]:t.slice(f).map(Gy),removeIds:m}}const gde={seq:0,sentIds:null,mode:"full"};function Ip(e,t,n){const a=e.seq+1;return{state:{seq:a,sentIds:n,mode:e.mode},message:xue(t.map(Gy),a)}}function vde(e,t){const n=t.map(p=>p.trackId);if(e.sentIds===null)return Ip(e,t,n);if(e.mode==="full")return Zy(e.sentIds,n)?{state:e,message:null}:Ip(e,t,n);const a=hde(e.sentIds,t);if(a.kind==="unchanged")return{state:e,message:null};if(a.kind==="reset")return Ip(e,t,n);const o=e.seq+1;return{state:{seq:o,sentIds:n,mode:e.mode},message:kue({seq:o,baseSeq:e.seq,prepend:a.prepend,append:a.append,removeIds:a.removeIds,count:n.length})}}function yde(e,t,n){const a=n.map(o=>o.trackId);return Ip({...e,mode:t},n,a)}function bde(e){let t=gde,n=[];const a=o=>{t=o.state,o.message!==null&&e(o.message)};return{report:o=>{n=o,a(vde(t,o))},setMode:o=>{a(yde(t,o,n))}}}function Sde(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ns(e){return typeof e=="string"&&e.length>0?e:void 0}function xde(e,t){if(!Sde(e))return null;const n=Ns(e.id),a=Ns(e.className);if(n===void 0||a===void 0||typeof e.deviceId!="number"||typeof e.timestamp!="number"||typeof e.score!="number")return null;const o=Ns(e.trackId),p=Ns(e.mediaKey),f=Ns(e.label),m=Ns(e.subLabel);return{trackId:o??n,deviceId:e.deviceId,cameraName:t.get(e.deviceId)??`Camera ${e.deviceId}`,className:a,...f!==void 0?{label:f}:{},...m!==void 0?{subLabel:m}:{},...typeof e.importance=="number"?{importance:e.importance}:{},firstSeen:e.timestamp,lastSeen:e.timestamp,state:"idle",active:!1,zonesVisited:[],zoneNames:[],classes:[a],audioLabels:[],bestEventId:p??o??n,score:e.score}}function kde(e,t){if(!Array.isArray(e))return[];const n=new Map;for(const a of e){const o=xde(a,t);if(o===null)continue;const p=n.get(o.trackId);(p===void 0||o.score>p.score)&&n.set(o.trackId,o)}return[...n.values()].sort((a,o)=>a.score!==o.score?o.score-a.score:o.lastSeen-a.lastSeen)}function wde(e,t,n){const a=new Map;for(const o of e)a.set(o.trackId,o);for(const o of t)a.set(o.trackId,o);return u5([...a.values()].sort(E0),n)}function Mde(e,t){if(e.length===0)return e;const n=Math.max(1,Math.floor(t.rowsPerColumn)),a=Math.max(1,t.cardWidth+t.gap),o=Math.max(0,Math.floor(Math.max(0,t.scrollLeft)/a)),p=t.viewportWidth>0?t.viewportWidth:t.cardWidth,f=Math.max(o+1,Math.ceil((Math.max(0,t.scrollLeft)+p*2)/a));return e.slice(o*n,Math.min(e.length,f*n))}const Cde=34;function Ade(e){const t=Math.max(0,e.gap),n=Math.max(1,e.cardWidth),a=Math.max(0,e.viewportWidth),o=e.columns??"auto",p=o==="auto"?Math.max(1,Math.floor((a+t)/(n+t))):Math.max(1,Math.floor(o)),f=a>0?(a-(p-1)*t)/p:n;return{columns:p,columnWidth:f,rowStridePx:Math.max(1,f+Cde+t)}}const Ede=2,Rde={startRow:0,endRow:0,padTopPx:0,padBottomPx:0,totalPx:0};function _de(e){const t=Math.max(0,Math.floor(e.rowCount));if(t===0)return Rde;const n=e.estimatedRowPx>0?e.estimatedRowPx:1,a=O=>{const D=e.measuredPx.get(O);return D!==void 0&&D>0?D:n};let o=0;for(let O=0;O<t;O+=1)o+=a(O);if(e.viewportHeight<=0)return{startRow:0,endRow:t,padTopPx:0,padBottomPx:0,totalPx:o};const p=Math.max(0,e.scrollTop),f=p+e.viewportHeight;let m=0,h=0;for(;m<t-1&&h+a(m)<=p;)h+=a(m),m+=1;let u=m,x=h;for(;u<t&&x<f;)x+=a(u),u+=1;const w=Math.max(0,Math.floor(e.overscanRows??Ede)),C=Math.max(0,m-w),A=Math.min(t,u+w);let R=0;for(let O=0;O<C;O+=1)R+=a(O);let I=0;for(let O=C;O<A;O+=1)I+=a(O);return{startRow:C,endRow:A,padTopPx:R,padBottomPx:Math.max(0,o-R-I),totalPx:o}}function Tde(e,t){let n=0,a=0;for(const o of e.values())o>0&&(n+=o,a+=1);return a===0?Math.max(1,t):Math.max(1,n/a)}const Ide=24,Nde=2;function Ode(e,t,n){if(e.length===0)return e;const a=Math.max(1,Math.floor(n)),o=Math.max(0,t.startRow)*a,p=Math.max(1,t.endRow-t.startRow+Nde),f=Math.min(e.length,o+Math.min(p*a,Ide));return e.slice(o,f)}function jde(e){const{rowCount:t,scrollTop:n,viewportHeight:a,fallbackRowPx:o,geometryKey:p}=e,f=T.useRef(new Map),m=T.useRef(new Map),[h,u]=T.useState(()=>new Map),x=T.useRef(p);T.useEffect(()=>{x.current!==p&&(x.current=p,m.current=new Map,u(new Map))},[p]);const w=T.useCallback(A=>{const R=m.current.get(A);if(R!==void 0)return R;const I=O=>{O===null?f.current.delete(A):f.current.set(A,O)};return m.current.set(A,I),I},[]);return T.useLayoutEffect(()=>{let A=null;for(const[R,I]of f.current){const O=Math.round(I.getBoundingClientRect().height);O<=0||h.get(R)!==O&&(A??=new Map(h),A.set(R,O))}A!==null&&u(A)}),{window:T.useMemo(()=>_de({rowCount:t,scrollTop:n,viewportHeight:a,estimatedRowPx:Tde(h,o),measuredPx:h}),[t,n,a,o,h]),measureRow:w}}const Pde=1,Dde=oce,zde=["label","sublabel","camera","time","badges"];function Os(e,t){const n=e.get(t);if(n===null||n.trim()==="")return;const a=Number.parseInt(n,10);return Number.isFinite(a)?a:void 0}function Lde(e){if(e===null)return;if(e.trim()==="")return[];const t=[];for(const n of e.split(",")){const a=Number.parseInt(n.trim(),10);Number.isFinite(a)&&a>=0&&t.push(a)}return t}function Ky(e){if(e!==null)return e.trim()===""?[]:e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function qde(e){if(e===null)return;const t=new Set((Ky(e)??[]).map(a=>a.toLowerCase())),n={};for(const a of zde)n[a]=t.has(a.toLowerCase());return n}function Bde(e,t){const n=e.startsWith("?")?e.slice(1):e;for(const a of n.split("&")){if(a.length===0)continue;const o=a.indexOf("=");if((o===-1?a:a.slice(0,o))===t)return o===-1?"":a.slice(o+1)}return null}function Ude(e){if(e===null)return;const t={};if(e.trim()==="")return t;for(const n of e.split(",")){const a=n.indexOf(":");if(a<=0)continue;const o=n.slice(0,a).trim();if(!/^\d+$/.test(o))continue;let p;try{p=decodeURIComponent(n.slice(a+1))}catch{continue}p.trim().length!==0&&(t[o]=p)}return t}function tA(e,t){const n=e.get(t);if(n===null)return;if(n.trim()==="")return null;const a=Number.parseInt(n,10);return Number.isFinite(a)&&a>=0?a:void 0}function Fde(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 Hde(e){const t=e.startsWith("#")?e.slice(1):e;if(t.length===0)return null;const n=new URLSearchParams(t).get("t");return n!==null&&n.length>0?n:null}function d5(e){const t=new URLSearchParams(e.startsWith("?")?e.slice(1):e),n=t.get("v");if(n===null)return null;if(Number.parseInt(n,10)!==Pde)return{ok:!1,error:`unsupported events URL version "${n}"`};const o={},p=t.get("view");p!==null&&(o.view=p);const f=Os(t,"rows");f!==void 0&&(o.rows=f);const m=Fde(t.get("cols"));m!==void 0&&(o.columns=m);const h=t.get("thumb");h!==null&&(o.thumbSize=h);const u=qde(t.get("fields"));u!==void 0&&(o.fields=u);const x=Lde(t.get("devices"));x!==void 0&&(o.deviceIds=x);const w=Ky(t.get("classes"));w!==void 0&&(o.classes=w);const C=Ky(t.get("attrs"));C!==void 0&&(o.attrs=C);const A=t.get("q");A!==null&&(o.search=A);const R=Os(t,"page");R!==void 0&&(o.pageSize=R);const I=Os(t,"max");I!==void 0&&(o.maxRows=I);const O=Os(t,"refresh");O!==void 0&&(o.refreshMs=O);const D=Os(t,"age");D!==void 0&&(o.maxAgeMs=D);const z=t.get("theme");z!==null&&(o.theme=z);const B=t.get("sort");B!==null&&(o.sort=B);const q=t.get("smode");q!==null&&(o.searchMode=q);const G=Os(t,"slimit");G!==void 0&&(o.semanticLimit=G);const ae=t.get("sscore");if(ae!==null&&ae.trim()!==""){const Me=Number.parseFloat(ae);Number.isFinite(Me)&&(o.semanticMinScore=Me)}const Q=tA(t,"since");Q!==void 0&&(o.sinceMs=Q);const H=tA(t,"until");H!==void 0&&(o.untilMs=H);const oe=Ude(Bde(e,"names"));oe!==void 0&&(o.deviceNames=oe);const we=YN.safeParse(o);return we.success?{ok:!0,patch:we.data}:{ok:!1,error:we.error.issues.map(Me=>`${Me.path.join(".")||"(root)"}: ${Me.message}`).join("; ")}}function $de(e,t,n,a=""){const o=d5(e);if(o===null)return null;if(!o.ok)return{ok:!1,error:o.error};const p=gce(n,a,Dde),f=Hde(t);return f===null&&!w0(p)?null:XN({serverUrl:p,...f!==null?{token:f}:{},fields:GN,...o.patch})}function Qde(){const e=$de(location.search,location.hash,location.origin,location.pathname);return e!==null&&location.hash!==""&&history.replaceState(null,"",location.pathname+location.search),e}function Vde(){const e=d5(location.search);return e===null||!e.ok?null:e.patch}function Gde(e,t){return!e.ok||t===null?e:{ok:!0,config:By(e.config,t)}}const nA=5,aA=3,Zde=[300,900];let Kde=0;function Wde(e){if(typeof e!="object"||e===null)return!1;const t=e;return"tracks"in t&&(t.nextCursor===null||typeof t.nextCursor=="string")}const Yde=/^(10\.|127\.|192\.168\.|169\.254\.|172\.(1[6-9]|2\d|3[01])\.)/;function Xde(e){let t;try{const p=w0(e)&&typeof location<"u"?location.href:void 0;t=new URL(e,p).host}catch{return"unknown:(unparseable)"}const n=t.trim().toLowerCase().replace(/^\[([^\]]*)\].*$/,"$1"),a=n.lastIndexOf(":"),o=a!==-1&&n.indexOf(":")===a?n.slice(0,a):n;return o==="localhost"||o==="::1"||o.startsWith("127.")?`loopback:${t}`:Yde.test(o)||/^f[cd][0-9a-f]{2}:/.test(o)||o.startsWith("fe80:")||o.endsWith(".local")?`lan:${t}`:o.includes(".")?`public:${t}`:`unknown:${t}`}function Jde(e){const{client:t,deviceIds:n,nameById:a,pageSize:o,maxRows:p,refreshMs:f,maxAgeMs:m}=e,{sinceMs:h,untilMs:u,devicesResolved:x}=e,w=e.includeStationary===!0,[C,A]=T.useState(Mc),[R,I]=T.useState(!1),[O,D]=T.useState(!1),[z,B]=T.useState(null),[q,G]=T.useState(0),[ae,Q]=T.useState(p),H=T.useRef(p);H.current=ae;const oe=T.useRef(Mc);oe.current=C;const we=T.useRef(!1),Me=T.useRef(!1),Ae=T.useRef(0),Ce=T.useRef(null),re=T.useRef(Date.now()),Te=T.useRef(a);Te.current=a;const F=T.useRef(e.channel);F.current=e.channel;const ue=T.useRef(null);T.useEffect(()=>{Due()},[]);const ke=n.join(","),Ee=T.useCallback(async(Ve,Ie=0)=>{const bt=`feed-${String(++Kde)}`,Re=performance.now();try{const Le=await t.listRecentTracks(Ve),lt=performance.now(),st=$y(lt-Re,Qy(Re,lt)),Pt={requestId:bt,waitMs:Math.round(Ie),...st};return Wde(Le)?{ok:!0,page:Le,timing:Pt}:(mi("request invalid",{...Pt,channel:F.current}),{ok:!1,message:"unexpected response shape"})}catch(Le){const lt=Le instanceof Error?Le.message:String(Le),st=performance.now();return mi("listRecentTracks failed",{error:lt,devices:Ve.deviceIds.length,limit:Ve.limit,since:Ve.since,cursor:Ve.cursor??null,requestId:bt,channel:F.current,waitMs:Math.round(Ie),...$y(st-Re,Qy(Re,st))}),{ok:!1,message:lt}}},[t]),fe=T.useCallback((Ve,Ie)=>{mi("request complete",{...Ve,channel:F.current,...Ie})},[]),L=T.useCallback(()=>{if(we.current){Me.current=!0,ue.current===null&&(ue.current=performance.now());return}const Ve=oe.current;if(!JC(Ve,H.current)||n.length===0)return;const Ie=ue.current;ue.current=null;const bt=Ie===null?0:performance.now()-Ie;we.current=!0,D(!0);const Re=YC(o,n.length),Le=pde({anchorMs:re.current,maxAgeMs:m,...h!==void 0?{sinceMs:h}:{},...u!==void 0?{untilMs:u}:{}}),lt=XC(Ve)!==null;Ee({deviceIds:[...n],since:Le.since,limit:Re,projection:"slim",...w?{includeStationary:!0}:{},...Le.until!==void 0?{until:Le.until}:{},...(()=>{const st=XC(Ve);return st!==null?{cursor:st}:{}})()},bt).then(st=>{if(st.ok){const Ca=performance.now(),Wa=UC(st.page.tracks,Te.current),$t=rde(oe.current,Wa,st.page.nextCursor);oe.current=$t,A($t),fe(st.timing,{rows:Wa.length,devices:n.length,limit:Re,paged:lt,parseMs:Math.round(performance.now()-Ca)}),Ae.current=0,B(null),I(!0);return}const Pt=Ae.current,Rt=Zde[Pt];if(Pt+1<aA&&Rt!==void 0){Ae.current=Pt+1,mi("page failed — retrying",{attempt:Pt+1,of:aA,backoffMs:Rt}),Ce.current=setTimeout(()=>{Ce.current=null,ee.current()},Rt);return}Ae.current=0;const gn=sde(oe.current);oe.current=gn,A(gn),B(st.message),I(!0)}).finally(()=>{if(we.current=!1,D(!1),lde(oe.current)){ee.current();return}Me.current&&(Me.current=!1,ee.current())})},[Ee,fe,n,ke,o,m,h,u,w]),ee=T.useRef(L);ee.current=L;const me=T.useCallback(()=>{if(we.current||n.length===0)return Promise.resolve();const Ve=ude(oe.current);if(Ve===null)return Oe.current(),Promise.resolve();we.current=!0;const Ie=YC(o,n.length);return(async()=>{let bt=null,Re=0,Le=!0;for(;Le&&Re<nA;){const lt=await Ee({deviceIds:[...n],since:Ve,limit:Ie,projection:"slim",...w?{includeStationary:!0}:{},...u!==void 0?{until:u}:{},...bt!==null?{cursor:bt}:{}});if(!lt.ok)return;const st=lt.page,Pt=performance.now(),Rt=UC(st.tracks,Te.current),gn=cde(oe.current,Rt,st.nextCursor);oe.current=gn.state,A(gn.state),fe(lt.timing,{rows:Rt.length,devices:n.length,limit:Ie,paged:bt!==null,delta:!0,parseMs:Math.round(performance.now()-Pt)}),B(null),Le=gn.gap,bt=gn.deltaCursor,Re+=1}Le&&mi("delta drain hit its page bound — newer rows may be missing",{since:Ve,pages:Re,bound:nA})})().finally(()=>{we.current=!1,Me.current&&(Me.current=!1,ee.current())})},[Ee,fe,n,ke,o,L,u,w]),be=T.useCallback(()=>{Ce.current!==null&&(clearTimeout(Ce.current),Ce.current=null),Ae.current=0},[]),X=T.useCallback(()=>{const Ve=H.current+Math.max(1,p);H.current=Ve,Q(Ve),ee.current()},[p]),xe=T.useCallback(()=>{be(),B(null),I(!1),ee.current()},[be]),Oe=T.useRef(()=>{}),le=T.useCallback(()=>{be(),re.current=Date.now(),Me.current=!1,oe.current=Mc,A(Mc),I(!1),D(!1),B(null),H.current=p,Q(p),G(Ve=>Ve+1)},[be,p]),ye=T.useCallback(()=>{be(),re.current=Date.now(),Me.current=!1;const Ve=ode(oe.current);oe.current=Ve,A(Ve),Ve.rows.length===0&&I(!1),D(!1),B(null),G(Ie=>Ie+1)},[be]),Be=`${ke}|${m}|${h??""}|${u??""}|${w?"1":"0"}`,ot=T.useRef(Be);return T.useEffect(()=>{ot.current!==Be&&(ot.current=Be,!(oe.current.rows.length===0&&!R)&&le())},[Be,le,R]),T.useEffect(()=>{if(n.length===0){x&&I(!0);return}L()},[q,ke,x]),T.useEffect(()=>{if(f<=0||n.length===0||!mde(u,Date.now()))return;const Ve=setInterval(()=>{me()},f);return()=>clearInterval(Ve)},[f,me,n.length,u]),Oe.current=xe,T.useEffect(()=>be,[be]),{rows:C.rows,retry:xe,loading:!R,loadingMore:O&&R,error:z,hasMore:JC(C,ae),tail:c5(C,ae),loadMore:L,loadOlder:X,refresh:me,reload:ye}}const epe=3,tpe=250;function npe(e){const{urls:t,token:n,paused:a,enabled:o}=e,p=T.useRef(0),f=T.useRef(0),m=T.useRef(!1),h=T.useRef(t),u=T.useRef(t[0]??"");h.current=t;const x=t[0]??"";u.current!==x&&(u.current=x,p.current=0),T.useEffect(()=>{if(m.current=!1,!o||a)return;let w=!1;const C=()=>{if(!(w||m.current))for(;f.current<epe;){const A=h.current,R=p.current;if(R>=A.length)return;p.current=R+1;const I=A[R];I===void 0||I.length===0||(f.current+=1,Wue(I,n).finally(()=>{f.current=Math.max(0,f.current-1),C()}))}};return C(),()=>{w=!0,m.current=!0}},[o,a,n,t.length])}const ape=.5,p5=56,ipe=88;function rpe(e){return e<=0?0:Math.min(e*ape,ipe)}function iA(e){return e>=p5}function ope(e,t,n){return e==="gallery"&&!t&&!n}function spe(e){const{root:t,onRefresh:n,enabled:a}=e,[o,p]=T.useState(0),f=T.useRef(null),m=T.useRef(0);m.current=o;const h=T.useRef(n);h.current=n;const u=T.useCallback(()=>{f.current=null,p(0)},[]);return T.useEffect(()=>{if(!a||t===null)return;const x=R=>{if(t.scrollTop>0){f.current=null;return}const I=R.touches[0];f.current=I!==void 0?I.clientY:null},w=R=>{const I=f.current;if(I===null)return;const O=R.touches[0];if(O!==void 0){if(t.scrollTop>0){f.current=null,p(0);return}p(rpe(O.clientY-I))}},C=()=>{if(f.current===null)return;const R=m.current;u(),iA(R)&&h.current()},A={passive:!0};return t.addEventListener("touchstart",x,A),t.addEventListener("touchmove",w,A),t.addEventListener("touchend",C,A),t.addEventListener("touchcancel",u,A),()=>{t.removeEventListener("touchstart",x),t.removeEventListener("touchmove",w),t.removeEventListener("touchend",C),t.removeEventListener("touchcancel",u)}},[t,a,u]),{distance:o,armed:iA(o)}}const js=8,rA=10,lpe=400;function cpe(e){return Math.max(lpe,Math.round(e))}function m5(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 oA(e,t,n){return{...m5(e,t),font:"inherit",fontSize:12,color:n.text,background:n.card,border:`1px solid ${n.border}`,borderRadius:8,cursor:"pointer"}}const upe=8;function sA({message:e,palette:t}){return T.useEffect(()=>{Da(bue(e)),Da(Tp("error",e))},[e]),v.jsxs("div",{style:{position:"fixed",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:t.background,color:"#f87171",fontFamily:"system-ui, sans-serif",fontSize:13,padding:16,textAlign:"center"},children:["Events embed config error: ",e]})}function dpe({client:e,initialConfig:t}){const[n,a]=T.useState(t),[o,p]=T.useState({}),[f,m]=T.useState(()=>window.matchMedia?.("(prefers-color-scheme: dark)").matches??!0),[h,u]=T.useState(()=>Date.now()),[x,w]=T.useState(null);T.useEffect(()=>{let ge=!1;return e.listDevices().then(_e=>{ge||w(_e)}).catch(()=>{ge||w([])}),()=>{ge=!0}},[e]);const C=T.useMemo(()=>{const ge=new Map;for(const _e of x??[])ge.set(_e.id,_ce(_e.id,_e.name??`Camera ${_e.id}`,n.deviceNames));for(const[_e,_t]of Object.entries(n.deviceNames)){const tn=Number(_e);Number.isInteger(tn)&&!ge.has(tn)&&_t.trim().length>0&&ge.set(tn,_t)}return ge},[x,n.deviceNames]),[A,R]=T.useState(()=>new Map),[I,O]=T.useState(()=>new Map),D=T.useMemo(()=>qce(n.kindLabels),[n.kindLabels]),z=T.useMemo(()=>rce(n.labels),[n.labels]),B=T.useMemo(()=>n.deviceIds.length>0?n.deviceIds:x===null?[]:rue(x),[n.deviceIds,x]);T.useEffect(()=>{if(B.length===0)return;let ge=!1;return e.listEventKinds([...B]).then(_e=>{ge||(R(Dce(_e)),O(zce(_e)))}).catch(()=>{mi("event-kind taxonomy unavailable — class filter is exact-id only")}),()=>{ge=!0}},[e,B]);const q=Jde({client:e,deviceIds:B,nameById:C,pageSize:n.pageSize,maxRows:Sce(n),refreshMs:n.refreshMs,maxAgeMs:n.maxAgeMs,channel:Xde(n.serverUrl),devicesResolved:n.deviceIds.length>0||x!==null,...n.showStationary?{includeStationary:!0}:{},...n.sinceMs!==void 0?{sinceMs:n.sinceMs}:{},...n.untilMs!==void 0?{untilMs:n.untilMs}:{}}),G=n.searchMode==="semantic"?n.search.trim():"",[ae,Q]=T.useState({query:"",rows:[],loading:!1});T.useEffect(()=>{if(G.length===0||B.length===0){Q({query:"",rows:[],loading:!1});return}let ge=!1;return Q(_e=>({..._e,query:G,loading:!0})),e.searchObjectEvents({text:G,limit:n.semanticLimit,minScore:n.semanticMinScore,...B.length===1&&B[0]!==void 0?{deviceId:B[0]}:{},...n.sinceMs!==void 0?{since:n.sinceMs}:{},...n.untilMs!==void 0?{until:n.untilMs}:{}}).then(_e=>{ge||Q({query:G,rows:kde(_e,C),loading:!1})}).catch(_e=>{ge||(mi("searchObjectEvents failed",{error:_e instanceof Error?_e.message:String(_e)}),Q({query:G,rows:[],loading:!1}))}),()=>{ge=!0}},[e,G,B,C,n.semanticLimit,n.semanticMinScore,n.sinceMs,n.untilMs]);const H=G.length>0,oe=T.useMemo(()=>new Set(n.reviewedTrackIds),[n.reviewedTrackIds]),we=ge=>oe.size===0?[...ge]:ge.map(_e=>oe.has(_e.trackId)?{..._e,reviewed:!0}:_e),Me=T.useMemo(()=>we($C(HC(q.rows,C),o)),[q.rows,C,oe,o]),Ae=T.useMemo(()=>we($C(HC(ae.rows,C),o)),[ae.rows,C,oe,o]),Ce=T.useMemo(()=>{const ge={debug:n.filterDebug,train:n.filterTrain,favourited:n.filterFavourited,reviewedTrackIds:n.reviewedTrackIds},_e=FC(Me,n.classes,n.search,A,n.attrs,ge);if(H){const _t=FC(Ae,n.classes,"",A,n.attrs,ge);return wde(_t,_e,n.sort)}return u5(_e,n.sort)},[H,Ae,Me,n.classes,n.attrs,n.filterDebug,n.filterTrain,n.filterFavourited,n.reviewedTrackIds,n.search,n.sort,A]),re=n5(n.theme,f),Te=T.useRef(null),[F,ue]=T.useState(null),ke=T.useRef(null),Ee=T.useRef(q.loadMore);Ee.current=q.loadMore;const fe=T.useRef(q.refresh);fe.current=q.refresh;const L=T.useRef(q.reload);L.current=q.reload;const[ee]=T.useState(()=>bde(Da)),me=T.useCallback(ge=>{if(ge.type==="setConfig"){a(_e=>By(_e,ge.patch));return}if(ge.type==="setWindow"){a(_e=>By(_e,Tue(ge)));return}if(ge.type==="setTrackFlagPatches"){p(ge.patches);return}if(ge.type==="setTrackListMode"){ee.setMode(ge.mode);return}if(ge.type==="refresh"){fe.current().finally(()=>Da(Cue()));return}if(ge.type==="reload"){L.current();return}if(ge.type==="loadMore"){Ee.current();return}if(ge.type==="ping"){Da(wue());return}Te.current?.scrollTo({top:0,left:0,behavior:"smooth"})},[ee]);T.useEffect(()=>(window.__camstackEvents={setConfig:ge=>{const _e=Sc({type:"setConfig",patch:ge});_e!==null&&me(_e)},setWindow:ge=>{const _e=Sc({type:"setWindow",...ge});_e!==null&&me(_e)},setTrackFlagPatches:ge=>{const _e=Sc({type:"setTrackFlagPatches",patches:ge});_e!==null&&me(_e)},setTrackListMode:ge=>{const _e=Sc({type:"setTrackListMode",mode:ge});_e!==null&&me(_e)},refresh:()=>me({type:"refresh"}),reload:()=>me({type:"reload"}),loadMore:()=>me({type:"loadMore"}),scrollToTop:()=>me({type:"scrollToTop"}),ping:()=>me({type:"ping"})},hu(ge=>{const _e=Sc(ge);_e!==null&&me(_e)})),[me]),T.useEffect(()=>{Da(yue(n.view))},[]),T.useEffect(()=>{Da(H?GC(ae.rows.length,Ce.length,!1,"semantic"):GC(q.rows.length,Ce.length,q.hasMore,"feed"))},[q.rows.length,Ce.length,q.hasMore,H,ae.rows.length]),T.useEffect(()=>{ee.report(Ce)},[ee,Ce]),T.useEffect(()=>{if(q.error!==null&&!H){Da(Tp("error",q.error));return}if(H?ae.loading:q.loading){Da(Tp("loading"));return}Da(Tp(Ce.length===0?"empty":"ready"))},[q.loading,q.error,Ce.length,H,ae.loading]),T.useEffect(()=>{const ge=window.matchMedia?.("(prefers-color-scheme: dark)");if(!ge)return;const _e=_t=>m(_t.matches);return ge.addEventListener("change",_e),()=>ge.removeEventListener("change",_e)},[]),T.useEffect(()=>{document.documentElement.style.colorScheme=re.colorScheme,document.body.style.background=re.background},[re]),T.useEffect(()=>{const ge="camstack-events-keyframes";if(document.getElementById(ge)!==null)return;const _e=document.createElement("style");_e.id=ge,_e.textContent="@keyframes camstack-spin{to{transform:rotate(360deg)}}",document.head.appendChild(_e)},[]),T.useEffect(()=>{const ge=setInterval(()=>u(Date.now()),6e4);return()=>clearInterval(ge)},[]);const[be,X]=T.useState(0);T.useEffect(()=>{const ge=F;if(ge===null)return;const _e=()=>{const tn=n.view==="reel"?ge.clientWidth:ge.clientHeight;X(Tt=>Tt===tn?Tt:tn)};if(_e(),typeof ResizeObserver!="function")return;const _t=new ResizeObserver(_e);return _t.observe(ge),()=>_t.disconnect()},[F,n.view]);const xe=Ce.length>0;T.useEffect(()=>{const ge=Te.current,_e=ke.current;if(!ge||!_e||H||!xe)return;const _t=cpe(n.view==="reel"?ge.clientWidth:ge.clientHeight),tn=new IntersectionObserver(Tt=>{Tt.some(In=>In.isIntersecting)&&Ee.current()},{root:ge,rootMargin:`${_t}px`});return tn.observe(_e),()=>tn.disconnect()},[n.view,q.hasMore,H,xe,be]);const Oe=T.useRef(0);T.useEffect(()=>{if(H||q.loading||q.loadingMore||!q.hasMore)return;const ge=Te.current;if(!ge||Ce.length===0)return;const _e=n.view==="reel";if((_e?ge.clientWidth:ge.clientHeight)===0)return;if(_e?ge.scrollWidth>ge.clientWidth+1:ge.scrollHeight>ge.clientHeight+1){Oe.current=0;return}Oe.current>=upe||(Oe.current+=1,Ee.current())},[Ce.length,q.loading,q.loadingMore,q.hasMore,H,n.view]);const le=spe({root:F,enabled:ope(n.view,H,n.nativePullToRefresh),onRefresh:()=>{fe.current()}}),ye=T.useRef(null);T.useEffect(()=>{const ge=F;if(!n.nativePullToRefresh||ge===null){ye.current=null;return}const _e=()=>{const _t=n.view==="gallery"&&!H&&ge.scrollTop<=0;ye.current!==_t&&(ye.current=_t,Da(Mue(_t)))};return _e(),ge.addEventListener("scroll",_e,{passive:!0}),()=>ge.removeEventListener("scroll",_e)},[F,n.nativePullToRefresh,n.view,H]);const Be=M0(n.thumbSize),ot=Rce(n.thumbSize),Ve=Mce(n.thumbSize,window.devicePixelRatio||1),Ie=n.view==="reel",[bt,Re]=T.useState(!1),[Le,lt]=T.useState({scrollLeft:0,scrollTop:0,viewportWidth:0,viewportHeight:0});T.useEffect(()=>{const ge=F;if(ge===null)return;let _e=null;const _t=()=>{lt({scrollLeft:ge.scrollLeft,scrollTop:ge.scrollTop,viewportWidth:ge.clientWidth,viewportHeight:ge.clientHeight})},tn=()=>{_t(),Re(!0),_e!==null&&clearTimeout(_e),_e=setTimeout(()=>Re(!1),tpe)};return _t(),ge.addEventListener("scroll",tn,{passive:!0}),window.addEventListener("resize",_t),()=>{ge.removeEventListener("scroll",tn),window.removeEventListener("resize",_t),_e!==null&&clearTimeout(_e)}},[F]);const st=T.useMemo(()=>Ade({viewportWidth:Le.viewportWidth,cardWidth:Be,gap:js,columns:n.columns}),[Le.viewportWidth,Be,n.columns]),Pt=Ie?0:Math.ceil(Ce.length/st.columns),Rt=jde({rowCount:Pt,scrollTop:Le.scrollTop,viewportHeight:Le.viewportHeight,fallbackRowPx:st.rowStridePx,geometryKey:`${st.columns}|${Be}|${n.fields.sublabel?"s":""}${n.fields.camera?"c":""}${n.fields.time?"t":""}${n.fields.badges?"b":""}`}),gn=T.useMemo(()=>Ie?Mde(Ce,{scrollLeft:Le.scrollLeft,viewportWidth:Le.viewportWidth,cardWidth:Be,gap:js,rowsPerColumn:n.rows}):Ode(Ce,Rt.window,st.columns),[Ie,Ce,Le.scrollLeft,Le.viewportWidth,Be,n.rows,Rt.window,st.columns]),Ca=T.useMemo(()=>gn.map(ge=>JN(n.serverUrl,ge.bestEventId,Ve)),[gn,n.serverUrl,Ve]);npe({urls:Ca,token:n.token,paused:bt,enabled:!q.loading&&Ce.length>0});const Wa=T.useCallback(ge=>{Da(Sue({trackId:ge.trackId,deviceId:ge.deviceId,bestEventId:ge.bestEventId,className:ge.className,firstSeen:ge.firstSeen,lastSeen:ge.lastSeen}))},[]),$t=Ie?{display:"grid",gridTemplateRows:`repeat(${n.rows}, ${ot}px)`,gridAutoFlow:"column",gridAutoColumns:`${Be}px`,gap:js,alignContent:"start"}:{display:"grid",gridTemplateColumns:`repeat(${st.columns}, minmax(0, 1fr))`,columnGap:js,rowGap:js,paddingBottom:js,alignContent:"start"},Ya=H?ae.loading:q.loading,Xa=!H&&q.loadingMore&&Ce.length>0,zn=!H&&q.error!==null,Kn=!H&&!q.loadingMore&&Ce.length>0,We=Kn&&zn,_n=Kn&&!zn&&q.tail==="exhausted",Aa=Kn&&!zn&&q.tail==="ceiling",Ja=zn&&Ce.length===0,yi=!Ya&&!zn&&Ce.length===0,vn=(ge,_e)=>v.jsx(ede,{row:ge,eagerImages:!Ie&&_e<8,serverUrl:n.serverUrl,token:n.token,thumbPx:Ve,width:Ie?`${Be}px`:"100%",heroPx:Be,variant:Ie?"reel":"gallery",iconId:Lce(ge.className,I,i5(ge)),kindLabels:D,labels:z,scrollRoot:F,fields:n.fields,showAdminFlags:n.showAdminFlags===!0,palette:re,nowMs:h,onClick:Wa},ge.trackId),Wn=v.jsxs(v.Fragment,{children:[Xa&&v.jsx("div",{"data-testid":"tail-loading","aria-label":z.loadingMore,style:{width:Ie?Be:"100%",height:Ie?ot:void 0,aspectRatio:Ie?void 0:"1 / 1",borderRadius:10,background:re.skeleton,border:`1px solid ${re.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 ${re.chip}`,borderTopColor:re.textMuted,animation:"camstack-spin 700ms linear infinite"}})}),_n&&v.jsx("div",{"data-testid":"tail-end",style:{...m5(Ie,Be),color:re.textMuted,fontSize:11,opacity:.75},children:Is(n,"end")}),Aa&&v.jsx("button",{type:"button","data-testid":"tail-more",onClick:()=>q.loadOlder(),style:oA(Ie,Be,re),children:Is(n,"loadOlder")}),We&&v.jsx("button",{type:"button","data-testid":"tail-error",onClick:()=>q.retry(),style:{...oA(Ie,Be,re),color:"#f87171"},children:Is(n,"retry")}),v.jsx("div",{ref:ke,style:{width:1,height:1,gridRow:Ie?1:"auto"},"aria-hidden":!0})]});return v.jsxs("div",{ref:ge=>{Te.current=ge,ue(_e=>_e===ge?_e:ge)},"data-testid":"events-scroller",className:Ie?"events-reel-scroller":void 0,style:{position:"fixed",inset:0,background:re.background,color:re.text,fontFamily:"system-ui, -apple-system, sans-serif",overflowX:Ie?"auto":"hidden",overflowY:Ie?"hidden":"auto",padding:Ie?`${Ece}px ${rA}px`:rA,boxSizing:"border-box",WebkitOverflowScrolling:"touch"},children:[le.distance>0&&v.jsx("div",{"data-testid":"pull-indicator","data-armed":le.armed?"true":"false","aria-hidden":!0,style:{position:"absolute",top:Math.max(0,le.distance-28),left:0,right:0,display:"flex",justifyContent:"center",pointerEvents:"none",zIndex:2,opacity:Math.min(1,le.distance/p5)},children:v.jsx("span",{style:{width:22,height:22,borderRadius:999,border:`2px solid ${re.chip}`,borderTopColor:re.textMuted,background:re.card,boxShadow:"0 1px 4px rgba(0,0,0,0.25)",transform:`rotate(${le.distance*4}deg)`,animation:q.loadingMore?"camstack-spin 700ms linear infinite":void 0}})}),Ja&&v.jsxs("div",{"data-testid":"state-error",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",color:"#f87171",fontSize:13,padding:16,textAlign:"center"},children:[v.jsx("span",{children:Is(n,"error")}),v.jsx("button",{type:"button","data-testid":"state-retry",onClick:()=>q.retry(),style:{marginTop:10,font:"inherit",fontSize:12,color:re.text,background:re.card,border:`1px solid ${re.border}`,borderRadius:8,padding:"5px 14px",cursor:"pointer"},children:Is(n,"retry")})]}),yi&&v.jsx("div",{"data-testid":"state-empty",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:re.textMuted,fontSize:13},children:Is(n,"empty")}),Ya&&Ce.length===0&&v.jsx("div",{"data-testid":"state-loading",style:$t,children:Array.from({length:Ie?8:12},(ge,_e)=>v.jsx("div",{style:{width:Ie?Be:"100%",height:Ie?ot:void 0,aspectRatio:Ie?void 0:"1 / 1",borderRadius:10,background:re.skeleton,border:`1px solid ${re.border}`,boxSizing:"border-box",opacity:.6}},`skeleton-${_e}`))}),Ie?v.jsxs("div",{style:$t,children:[Ce.map(vn),Wn]}):v.jsxs("div",{"data-testid":"events-gallery",children:[v.jsx("div",{"data-testid":"gallery-pad-top",style:{height:Rt.window.padTopPx},"aria-hidden":!0}),Array.from({length:Rt.window.endRow-Rt.window.startRow},(ge,_e)=>{const _t=Rt.window.startRow+_e,tn=_t*st.columns;return v.jsx("div",{"data-row-index":_t,ref:Rt.measureRow(_t),style:$t,children:Ce.slice(tn,tn+st.columns).map((Tt,In)=>vn(Tt,tn+In))},_t)}),v.jsx("div",{"data-testid":"gallery-pad-bottom",style:{height:Rt.window.padBottomPx},"aria-hidden":!0}),Wn]})]})}function ppe(){const e=Tm("events",()=>window.__CAMSTACK_EVENTS__,XN,Qde,{urlFirst:!0}),t=T.useMemo(()=>Vde(),[]),n=T.useMemo(()=>e===null?null:Gde(e,t),[e,t]),a=T.useMemo(()=>{if(n===null||!n.ok)return null;const p=bm({serverUrl:n.config.serverUrl,token:n.config.token});return{system:p,client:tde(p)}},[n]);T.useEffect(()=>{if(a)return()=>a.system.close()},[a]);const o=n5(n!==null&&n.ok?n.config.theme:"auto",window.matchMedia?.("(prefers-color-scheme: dark)").matches??!0);return n===null?null:n.ok?a?v.jsx(dpe,{client:a.client,initialConfig:n.config}):v.jsx(sA,{message:"Failed to initialise the events embed",palette:o}):v.jsx(sA,{message:n.error,palette:o})}const im={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"},mpe=Object.keys(im),fpe=Y(s(),s()).optional();function hpe(e){if(e===null||typeof e!="object")return im;const t=e,n={...im};for(const a of mpe){const o=t[a];typeof o=="string"&&o.trim()!==""&&(n[a]=o)}return n}const f5=j(["auto","high","mid","low"]).catch("auto"),gpe=nt([V("auto"),l().int().min(1)]),h5=d({enabled:E(),motion:E(),motionHoldSec:l().optional(),audio:j(["off","sensor","level"]),audioDb:l(),audioHoldSec:l(),detection:E(),detectionHoldSec:l(),detectionClasses:M(s()).optional(),appearance:d({motionColor:s(),audioColor:s(),detectionColor:s(),thickness:l()}).optional()}),pv=j(["off","top-left","top-center","top-right","left-center","right-center","bottom-left","bottom-center","bottom-right"]),vpe=d({motionBoxes:E().optional(),motionBadge:pv.optional(),audioMeter:pv.optional(),occupancy:pv.optional(),stats:E().optional()}),ype=d({cw:l(),ch:l()}),bpe=d({serverUrl:s().min(1),token:s().min(1).optional(),devices:M(l().int().nonnegative()).min(1),layout:gpe,quality:f5,showName:E(),showBadges:E(),muted:E(),paused:E(),highlight:h5.optional(),activeOnly:E().optional(),showBoxes:E().optional(),audioOnIds:M(l().int().nonnegative()).optional(),pausedIds:M(l().int().nonnegative()).optional(),snapshots:Y(s(),s()).optional(),ptzIds:M(l().int().nonnegative()).optional(),overlays:Y(s(),vpe).optional(),editable:E().optional(),cellPanels:E().optional(),spans:Y(s(),ype).optional(),labels:fpe}).superRefine(FN);function g5(e){if(e==null)return{ok:!1,error:"config is required"};const t=bpe.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(n=>`${n.path.join(".")||"(root)"}: ${n.message}`).join("; ")}}const Spe=1,v5=j(["auto","high","mid","low"]),xpe=nt([V("auto"),l().int().min(1)]),y5=d({enabled:E(),motion:E(),audio:j(["off","sensor","level"]),audioDb:l(),audioHoldSec:l(),detection:E(),detectionHoldSec:l(),detectionClasses:M(s()).optional(),appearance:d({motionColor:s(),audioColor:s(),detectionColor:s(),thickness:l()}).optional()}),kpe=d({devices:M(l().int().nonnegative()).min(1),layout:xpe,quality:v5,showName:E(),audioOnIds:M(l().int().nonnegative()).optional(),activeOnly:E().optional(),boxes:E().optional(),highlight:y5.optional()}),wpe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function Mpe(e){let t="",n=0;for(;n<e.length;){const a=e[n];if(a===void 0)return null;let o,p;if(a<128)o=a,p=0;else if((a&224)===192)o=a&31,p=1;else if((a&240)===224)o=a&15,p=2;else if((a&248)===240)o=a&7,p=3;else return null;for(let f=1;f<=p;f++){const m=e[n+f];if(m===void 0||(m&192)!==128)return null;o=o<<6|m&63}n+=p+1,t+=String.fromCodePoint(o)}return t}function Cpe(e){if(e.length%4===1)return null;const t=[];for(const o of e){const p=wpe.indexOf(o);if(p<0)return null;t.push(p)}const n=[];for(let o=0;o<t.length;o+=4){const p=t[o],f=t[o+1];if(p===void 0||f===void 0)return null;const m=t[o+2],h=t[o+3];n.push(p<<2|f>>4),m!==void 0&&n.push((f&15)<<4|m>>2),h!==void 0&&m!==void 0&&n.push((m&3)<<6|h)}const a=Mpe(n);if(a===null)return null;try{return JSON.parse(a)}catch{return null}}function R0(e,t){return e.startsWith(t)?e.slice(t.length):e}function b5(e){const n=new URLSearchParams(R0(e,"#")).get("t");return n!==null&&n.length>0?n:null}function Ape(e,t){return new URLSearchParams(R0(e,"?")).has("v")||b5(t)!==null}function lA(e){if(e.length===0)return null;const t=[];for(const n of e.split(",")){if(!/^\d+$/.test(n))return null;t.push(Number(n))}return t}function $a(e){return{ok:!1,error:e}}function Epe(e,t){const n=new URLSearchParams(R0(e,"?")),a=n.get("mode");if(a!==null&&a!=="grid")return $a(`unsupported mode "${a}"`);const o=n.get("v");if(o===null)return $a("missing share-link version (v)");if(o!==String(Spe))return $a(`unsupported share-link version "${o}"`);const p=n.get("devices"),f=p===null?null:lA(p);if(f===null||f.length===0)return $a("invalid or missing devices list");const m=n.get("layout");let h;if(m===null||m==="auto")h="auto";else if(/^\d+$/.test(m)&&Number(m)>=1)h=Number(m);else return $a(`invalid layout "${m}"`);const u=n.get("q")??"auto",x=v5.safeParse(u),w=x.success?x.data:"auto",C=n.get("names")??"0";if(C!=="0"&&C!=="1")return $a(`invalid names flag "${C}"`);const A=n.get("audio");let R;if(A!==null){const Q=lA(A);if(Q===null)return $a(`invalid audio list "${A}"`);R=Q}const I=n.get("activeOnly");if(I!==null&&I!=="0"&&I!=="1")return $a(`invalid activeOnly flag "${I}"`);const O=I==="1",D=n.get("boxes");if(D!==null&&D!=="0"&&D!=="1")return $a(`invalid boxes flag "${D}"`);const z=D==="1",B=n.get("hl");let q;if(B!==null){const Q=Cpe(B),H=y5.safeParse(Q);if(Q===null||!H.success)return $a("invalid highlight config (hl)");q=H.data}const G={devices:[...f],layout:h,quality:w,showName:C==="1",...R!==void 0&&R.length>0?{audioOnIds:[...R]}:{},...O?{activeOnly:!0}:{},...z?{boxes:!0}:{},...q!==void 0?{highlight:q}:{}},ae=kpe.safeParse(G);return ae.success?{ok:!0,params:ae.data,token:b5(t)}:$a(ae.error.issues.map(Q=>`${Q.path.join(".")||"(root)"}: ${Q.message}`).join("; "))}function Rpe(e,t,n){if(!Ape(e,t))return null;const a=Epe(e,t);if(!a.ok)return{ok:!1,error:a.error};if(a.token===null)return{ok:!1,error:"share token missing — the link must end with #t=<token>"};const o=a.params,p={serverUrl:n,token:a.token,devices:[...o.devices],layout:o.layout,quality:o.quality,showName:o.showName,showBadges:!0,muted:!0,paused:!1,...o.highlight!==void 0?{highlight:o.highlight}:{},...o.activeOnly===!0?{activeOnly:!0}:{},...o.boxes===!0?{showBoxes:!0}:{},...o.audioOnIds!==void 0&&o.audioOnIds.length>0?{audioOnIds:[...o.audioOnIds]}:{}};return g5(p)}function _pe(){const e=Rpe(location.search,location.hash,location.origin);return e!==null&&location.hash!==""&&history.replaceState(null,"",location.pathname+location.search),e}const rm=16/9,cA={cols:0,rows:0,cellW:0,cellH:0,wallW:0,wallH:0};function uA(e,t,n,a,o){const p=Math.min(a/e,o/t*rm),f=p/rm;return{cols:e,rows:t,cellW:p,cellH:f,wallW:Math.min(e,n)*p,wallH:t*f,empty:e*t-n}}function dA(e){return{cols:e.cols,rows:e.rows,cellW:e.cellW,cellH:e.cellH,wallW:e.wallW,wallH:e.wallH}}const pA=1e-9;function Tpe(e,t){const n=e.cellW*e.cellH,a=t.cellW*t.cellH,o=Math.max(n,a,1);return n-a>o*pA?!0:a-n>o*pA?!1:e.empty!==t.empty?e.empty<t.empty:e.rows<t.rows}function Ipe(e,t,n,a){if(e<=0||t<=0||n<=0)return cA;if(typeof a=="number"&&a>=1){const p=Math.floor(a);return dA(uA(p,Math.ceil(e/p),e,t,n))}let o=null;for(let p=1;p<=e;p++){const f=Math.ceil(e/p);if(Math.ceil(e/f)!==p)continue;const m=uA(f,p,e,t,n);(o===null||Tpe(m,o))&&(o=m)}return o===null?cA:dA(o)}function Npe(e,t){if(e.length===0)return[];const n=t>=1?Math.floor(t):e.length,a=[];for(let o=0;o<e.length;o+=n)a.push(e.slice(o,o+n));return a}function Ope(e,t){if(e.length===0||t.cellW<=0||t.cellH<=0)return[];const n=[];return Npe(e,t.cols).forEach((o,p)=>{const f=(t.wallW-o.length*t.cellW)/2;o.forEach((m,h)=>{n.push({deviceId:m,x:f+h*t.cellW,y:p*t.cellH,w:t.cellW,h:t.cellH})})}),n}const mA={wallW:0,wallH:0,placements:[]};function jpe(e,t){const n=e!==void 0&&Number.isFinite(e.cw)?Math.round(e.cw):1,a=e!==void 0&&Number.isFinite(e.ch)?Math.round(e.ch):1;return{cw:Math.min(Math.max(n,1),Math.max(t,1)),ch:Math.max(a,1)}}function Ppe(e){if(e===void 0)return!1;for(const t of Object.keys(e)){const n=e[t];if(n!==void 0&&(n.cw!==1||n.ch!==1))return!0}return!1}function Dpe(e,t,n){const a=new Set,o=[];let p=0;const f=(m,h,u,x)=>{for(let w=m;w<m+x;w++)for(let C=h;C<h+u;C++)if(a.has(`${w}:${C}`))return!1;return!0};for(const m of e){const{cw:h,ch:u}=jpe(t[String(m)],n),x=p+u+e.length;let w=!1;for(let C=0;C<=x&&!w;C++)for(let A=0;A+h<=n;A++)if(f(C,A,h,u)){for(let R=C;R<C+u;R++)for(let I=A;I<A+h;I++)a.add(`${R}:${I}`);o.push({deviceId:m,col:A,row:C,cw:h,ch:u}),p=Math.max(p,C+u),w=!0;break}}return{cells:o,rows:p,cols:n}}function zpe(e,t,n,a,o){const p=Ipe(e.length,t,n,a);if(!Ppe(o)||p.cols<=0)return{wallW:p.wallW,wallH:p.wallH,placements:Ope(e,p)};if(e.length===0||t<=0||n<=0)return mA;const f=Dpe(e,o??{},p.cols);if(f.rows<=0)return mA;const m=Math.min(t/f.cols,n/f.rows*rm),h=m/rm;return{wallW:f.cells.reduce((x,w)=>Math.max(x,w.col+w.cw),0)*m,wallH:f.rows*h,placements:f.cells.map(x=>({deviceId:x.deviceId,x:x.col*m,y:x.row*h,w:x.cw*m,h:x.ch*h}))}}function S5(){const[e,t]=T.useState(null),[n,a]=T.useState("idle"),o=T.useRef(null),p=T.useRef(null),f=T.useRef(null),m=T.useRef(0),h=T.useRef(null),u=zte(),x=Lte(),w=qte(),C=T.useRef({start:u.mutateAsync,answer:x.mutateAsync,stop:w.mutateAsync});C.current={start:u.mutateAsync,answer:x.mutateAsync,stop:w.mutateAsync};const A=T.useCallback(()=>{if(o.current){try{o.current.close()}catch{}o.current=null}if(p.current){for(const D of p.current.getTracks())try{D.stop()}catch{}p.current=null}},[]),R=T.useCallback(async()=>{const D=f.current;if(f.current=null,A(),D)try{await C.current.stop({deviceId:D.deviceId,sessionId:D.sessionId})}catch{}},[A]),I=T.useCallback(async D=>{if(h.current===D){m.current+=1,h.current=null,t(null),a("idle"),await R();return}m.current+=1;const z=m.current;h.current=D,t(D),a("starting");let B;try{B=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}catch{z===m.current&&(h.current=null,t(null),a("error"));return}if(z!==m.current){for(const G of B.getTracks())G.stop();return}if(await R(),z!==m.current){for(const G of B.getTracks())G.stop();return}let q=null;try{p.current=B;const G=await C.current.start({deviceId:D});if(z!==m.current){try{await C.current.stop({deviceId:D,sessionId:G.sessionId})}catch{}A();return}f.current={deviceId:D,sessionId:G.sessionId},q=new RTCPeerConnection,o.current=q,q.oniceconnectionstatechange=()=>{if(z!==m.current||!q)return;const Q=q.iceConnectionState;Q==="connected"||Q==="completed"?a("talking"):(Q==="failed"||Q==="closed"||Q==="disconnected")&&(h.current=null,t(null),a("idle"),R())};for(const Q of B.getAudioTracks())q.addTrack(Q,B);await q.setRemoteDescription({type:"offer",sdp:G.sdpOffer});const ae=await q.createAnswer();if(await q.setLocalDescription(ae),z!==m.current)return;await C.current.answer({deviceId:D,sessionId:G.sessionId,sdpAnswer:q.localDescription?.sdp??ae.sdp??""})}catch{if(q)try{q.close()}catch{}A();const G=f.current;if(f.current=null,G)try{await C.current.stop({deviceId:G.deviceId,sessionId:G.sessionId})}catch{}z===m.current&&(h.current=null,t(null),a("error"))}},[R,A]),O=T.useCallback(D=>{if(D===null){m.current+=1,h.current=null,t(null),a("idle"),R();return}h.current!==D&&I(D)},[R,I]);return T.useEffect(()=>()=>{m.current+=1,R()},[R]),{activeMicId:e,micState:n,toggleMic:D=>{I(D)},setActiveMic:O}}const Lpe=6e3,qpe=500;function Bpe(e,t){const n=T.useRef(new Map),[,a]=T.useState(0),o=t?.motion??!1,p=t?.audio??"off",f=t?.audioDb??-30,m=t?.audioHoldSec??5,h=t?.detection??!1,u=t?.detectionHoldSec??3,x=t?.detectionClasses??[],w=(R,I)=>{n.current.set(R,Date.now()+I),a(O=>O+1)};fi(Ke.MotionOnMotionChanged,R=>{if(!o)return;const I=R.data;I&&I.detected&&w(I.deviceId,Lpe)}),fi(Ke.PipelineAudioInferenceResult,R=>{if(p==="off")return;const I=R.data;if(!I)return;(p==="sensor"?I.frame.detections.length>0:(I.frame.level?.dbfs??Number.NEGATIVE_INFINITY)>=f)&&w(I.deviceId,m*1e3)}),fi(Ke.DetectionResult,R=>{if(!h)return;const I=R.data;if(!I)return;I.frame.detections.some(D=>x.length===0||x.includes(D.macroClass))&&w(I.frame.deviceId,u*1e3)}),T.useEffect(()=>{const R=setInterval(()=>a(I=>I+1),qpe);return()=>clearInterval(R)},[]);const C=Date.now(),A=new Set;for(const R of e){const I=n.current.get(R);I!==void 0&&C<I&&A.add(R)}return A}function Upe(e){return{type:"tileOpen",deviceId:e}}function Fpe(e){return{type:"audioToggle",deviceId:e}}function Hpe(e){return{type:"pauseToggle",deviceId:e}}function $pe(e){return{type:"ptzOpen",deviceId:e}}function Qpe(e,t){return{type:"cellPanelOpen",deviceId:e,panel:t}}function Vpe(e){return{type:"tileRemove",deviceId:e}}function Gpe(e,t,n){return{type:"tileResize",deviceId:e,cw:t,ch:n}}function x5(e,t,n){return{type:"state",state:e,...t!==void 0?{message:t}:{},...n!==void 0?{commands:n}:{}}}function Zpe(e){return{type:"layout",tiles:e}}function di(e){an(e)}const Kpe=["top-left","top-center","top-right","left-center","right-center","bottom-left","bottom-center","bottom-right"];function fA(e){return typeof e=="string"&&Kpe.includes(e)}const Wpe={"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 k5(e){return{position:"absolute",display:"flex",...Wpe[e]}}const w5=[-60,-53,-46,-39,-32,-24],Ype=w5.length,mv=["#22c55e","#84cc16","#eab308","#f59e0b","#f97316","#ef4444"];function Xpe(e){const t=Math.min(Math.max(0,e),mv.length-1);return mv[t]??mv[0]}function Jpe(e){if(e===null||!Number.isFinite(e))return 0;let t=0;for(const n of w5)e>=n&&(t+=1);return t}function eme(e){if(e==="off")return null;const t=e.split("-"),n=t.includes("top")?"top":t.includes("bottom")?"bottom":"center",a=t.includes("left")?"left":t.includes("right")?"right":"center";return n!=="center"&&a!=="center"?"compact":a==="center"?"horizontal":"vertical"}const hA=[8,11,14,17,21,26],fv={horizontal:{width:8,height:16},vertical:{width:24,height:7},compactWidth:4};function tme(e,t){if(e==="vertical")return fv.vertical;if(e==="horizontal")return fv.horizontal;const n=hA[t]??hA[0];return{width:fv.compactWidth,height:n}}function nme(e){const t=Array.from({length:Ype},(n,a)=>a);return e==="vertical"?[...t].reverse():t}function Co(e){return typeof e=="object"&&e!==null}function ame(e){if(!Co(e))return[];if(e.detected!==!0)return[];const t=typeof e.frameWidth=="number"?e.frameWidth:0,n=typeof e.frameHeight=="number"?e.frameHeight:0;if(t<=0||n<=0)return[];const a=e.regions;if(!Array.isArray(a))return[];const o=[];for(const p of a){if(!Co(p)||!Co(p.bbox))continue;const{x:f,y:m,w:h,h:u}=p.bbox;typeof f!="number"||typeof m!="number"||typeof h!="number"||typeof u!="number"||!(h>0)||!(u>0)||o.push({x:f/t,y:m/n,w:h/t,h:u/n,pixelCount:typeof p.pixelCount=="number"?p.pixelCount:0})}return o}function ime(e){return!Number.isFinite(e)||e<=0?.08:Math.min(.28,.08+e/4e3*.28)}function gA(e){if(!Co(e))return[];const t=Co(e.frame)?e.frame.byClass:void 0,n=Co(t)?t:e.byClass;if(!Co(n))return[];const a=[];for(const[o,p]of Object.entries(n))typeof p!="number"||!Number.isFinite(p)||p<=0||a.push({className:o,count:Math.round(p)});return a.sort((o,p)=>p.count-o.count||o.className.localeCompare(p.className))}function rme(e,t,n){if(n<=0)return 0;const a=t-e;return a<=0?0:Math.round(a*1e3/n)}function ome(e){if(e===null)return"—";const t=[e.resolution,`${e.fps}fps`];return e.dropped>0&&t.push(`${e.dropped} dropped`),t.join(" · ")}const sme=1200,lme=1e3;function cme({deviceId:e}){const[t,n]=T.useState([]),a=T.useRef(void 0);return fi(Ke.MotionAnalysis,o=>{const p=o.data;!p||p.deviceId!==e||(n(ame(p)),a.current&&clearTimeout(a.current),a.current=setTimeout(()=>n([]),sme))}),T.useEffect(()=>()=>{a.current&&clearTimeout(a.current)},[e]),t.length===0?null:v.jsx("div",{style:{position:"absolute",inset:0,overflow:"hidden",pointerEvents:"none"},children:t.map((o,p)=>v.jsx("div",{style:{position:"absolute",left:`${o.x*100}%`,top:`${o.y*100}%`,width:`${o.w*100}%`,height:`${o.h*100}%`,border:"1px dashed #f59e0b",borderRadius:2,background:`rgba(245,158,11,${ime(o.pixelCount)})`}},`${o.x}:${o.y}:${o.w}:${o.h}:${p}`))})}function ume({deviceId:e,anchor:t}){const[n,a]=T.useState(null);fi(Ke.PipelineAudioInferenceResult,h=>{const u=h.data;!u||u.deviceId!==e||a(u.frame.level?.dbfs??null)});const o=Jpe(n),p=eme(t);if(p===null)return null;const f=p==="horizontal",m=p==="vertical";return v.jsx("div",{style:{...k5(t),pointerEvents:"none"},children:v.jsx("span",{style:{display:"flex",flexDirection:m?"column":"row",alignItems:m||f?"center":"flex-end",gap:m||f?4:3,padding:f||m?"4px 8px":"3px 6px",borderRadius:8,background:"rgba(0,0,0,0.7)"},children:nme(p).map(h=>{const u=h<o,x=tme(p,h);return v.jsx("span",{style:{width:x.width,height:x.height,borderRadius:2,background:u?Xpe(h):"#71717a",opacity:u?1:.35}},h)})})})}function dme(e,t){if(typeof e!="object"||e===null)return null;const n=Reflect.get(e,"zoneAnalytics");if(typeof n!="object"||n===null)return null;const a=Reflect.get(n,"getCurrentSnapshot");if(typeof a!="object"||a===null)return null;const o=Reflect.get(a,"query");if(typeof o!="function")return null;const p=o.call(a,{deviceId:t});return p instanceof Promise?p:Promise.resolve(p)}function pme({system:e,deviceId:t,anchor:n}){const[a,o]=T.useState([]);return T.useEffect(()=>{let p=!1;const f=dme(e.trpcClient,t);if(f!==null)return f.then(m=>{p||o(gA(m))}).catch(()=>{p||o([])}),()=>{p=!0}},[e,t]),fi(Ke.ZoneAnalyticsOccupancyChanged,p=>{const f=p.data;f.deviceId===t&&o(gA(f))}),a.length===0?null:v.jsx("div",{style:{...k5(n),gap:4,pointerEvents:"none"},children:a.slice(0,4).map(p=>v.jsx("span",{style:{padding:"2px 6px",borderRadius:6,background:"rgba(0,0,0,0.75)",color:"#fafaf9",fontSize:11,fontWeight:700,fontFamily:"system-ui, sans-serif",whiteSpace:"nowrap"},children:`${p.className} ${p.count}`},p.className))})}function mme({containerRef:e}){const[t,n]=T.useState(null),a=T.useRef(null);return T.useEffect(()=>{const o=()=>{const f=e.current?.querySelector("video");if(!f){n(null);return}const m=typeof f.getVideoPlaybackQuality=="function"?f.getVideoPlaybackQuality():null,h=m?.totalVideoFrames??0,u=Date.now(),x=a.current;a.current={frames:h,at:u},n({resolution:f.videoWidth>0?`${f.videoWidth}x${f.videoHeight}`:"—",fps:x===null?0:rme(x.frames,h,u-x.at),dropped:m?.droppedVideoFrames??0})};o();const p=setInterval(o,lme);return()=>{clearInterval(p),a.current=null}},[e]),v.jsx("div",{style:{position:"absolute",top:4,right:4,maxWidth:"90%",padding:"2px 6px",borderRadius:6,background:"rgba(0,0,0,0.7)",color:"#fafaf9",fontSize:10,fontWeight:600,fontFamily:"system-ui, sans-serif",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",pointerEvents:"none"},children:ome(t)})}const fme=1e4,vA=1e3,yA=[0,5e3,15e3,3e4],hme=4;function gme(e){const t=Math.max(0,Math.min(e,yA.length-1));return yA[t]??0}function vme(e){return!e.playing||e.lastFrameAt===null?!1:e.nowMs-e.lastFrameAt>=e.stallMs}function yme(e){const{containerRef:t,playing:n,onRecover:a,stallMs:o=fme}=e,p=e.now??Date.now,[f,m]=T.useState({recovering:!1,attempts:0}),h=T.useRef(null),u=T.useRef(0),x=T.useRef(0),w=T.useRef(a);w.current=a;const C=T.useRef(p);C.current=p;const A=T.useCallback(()=>{const R=C.current(),I=h.current;h.current=R,u.current>0&&I!==null&&R-I<o&&(u.current=0,m({recovering:!1,attempts:0}))},[o]);return T.useEffect(()=>{if(!n){h.current=null;return}const I=t.current?.querySelector("video");if(!I)return;let O=!1,D=null;if(typeof I.requestVideoFrameCallback=="function"){const q=()=>{O||(A(),D=I.requestVideoFrameCallback?.(q)??null)};return D=I.requestVideoFrameCallback(q),()=>{O=!0,D!==null&&I.cancelVideoFrameCallback?.(D)}}let z=I.currentTime;const B=setInterval(()=>{if(O)return;const q=I.currentTime;q!==z&&(z=q,A())},vA);return()=>{O=!0,clearInterval(B)}},[n,t,A]),T.useEffect(()=>{if(!n)return;const R=setInterval(()=>{const I=C.current();if(I<x.current||!vme({lastFrameAt:h.current,nowMs:I,stallMs:o,playing:n})||u.current>=hme)return;const O=u.current;u.current=O+1,h.current=I,x.current=I+gme(O+1)+o,m({recovering:!0,attempts:O+1}),w.current()},vA);return()=>clearInterval(R)},[n,o]),f}const bme=300,Sme=130,xme=["devices","viewOptions"],kme={inline:xme,overflow:!1},wme={inline:[],overflow:!0};function Mme(e,t){return e>=bme&&t>=Sme?kme:wme}const Cme=120,Ame=68;function Eme(e,t,n){return e&&t>=Cme&&n>=Ame}const Rme=16/9,_me={left:0,top:0,width:0,height:0},bA=.5;function Tme(e,t,n){if(!(e>0)||!(t>0))return _me;const a={left:0,top:0,width:e,height:t};if(!Number.isFinite(n))return a;const o=Math.min(e,t*n),p=o/n;return e-o<bA&&t-p<bA?a:{left:(e-o)/2,top:(t-p)/2,width:o,height:p}}const Ime=500;function M5(e,t,n){const{motion:a,detection:o}=Fle(e.trpcClient,t),p=T.useRef(0),f=T.useRef(0),m=T.useRef(0),h=T.useRef(!1),[,u]=T.useState(0),x=n?.audio??"off",w=n?.audioDb??-30,C=n?.audioHoldSec??5,A=n?.motionHoldSec??0,R=n?.detectionHoldSec??3,I=n?.detectionClasses??[],O=I.join(",");fi(Ke.MotionOnMotionChanged,B=>{const q=B.data;!q||q.deviceId!==t||!n?.motion||(q.detected===!0?(m.current=Date.now()+Math.max(1,A)*1e3,h.current=!0,u(G=>G+1)):q.detected===!1&&h.current&&(m.current=Date.now()+A*1e3,h.current=!1,u(G=>G+1)))}),fi(Ke.PipelineAudioInferenceResult,B=>{const q=B.data;if(!q||q.deviceId!==t||x==="off")return;(x==="sensor"?q.frame.detections.length>0:(q.frame.level?.dbfs??Number.NEGATIVE_INFINITY)>=w)&&(p.current=Date.now()+C*1e3,u(ae=>ae+1))}),T.useEffect(()=>{if(!o)return;o.detections.some(q=>I.length===0||I.includes(q.macroClass))&&(f.current=Date.now()+R*1e3,u(q=>q+1))},[o,R,O]),T.useEffect(()=>{const B=a!==null;(B||h.current)&&(m.current=Date.now()+A*1e3,B||u(q=>q+1)),h.current=B},[a,A]);const D=n?.enabled===!0;if(T.useEffect(()=>{if(!D)return;const B=setInterval(()=>u(q=>q+1),Ime);return()=>clearInterval(B)},[D]),!n?.enabled)return null;const z=Date.now();return n.detection&&z<f.current?"detection":x!=="off"&&z<p.current?"audio":n.motion&&(a!==null||z<m.current)?"motion":null}const Ws={motion:"#DC2626",audio:"#3B82F6",detection:"#22C55E"},Nme=2500,Ome={person:"#f59e0b",vehicle:"#3b82f6",animal:"#22c55e",face:"#a855f7",plate:"#ec4899"},jme="#ef4444";function Pme(e){return Ome[e]??jme}function Xd(e){return e<0?0:e>1?1:e}function Dme(e){if(e.width<=0||e.height<=0)return[];const t=[];for(const n of e.detections){const{bbox:a}=n,o=Xd(a.x/e.width),p=Xd(a.y/e.height),f=Xd((a.x+a.width)/e.width),m=Xd((a.y+a.height)/e.height);f<=o||m<=p||t.push({label:n.macroClass,score:n.score,x1:o,y1:p,x2:f,y2:m})}return t}function zme({deviceId:e}){const[t,n]=T.useState([]),a=T.useRef(void 0);return fi(Ke.DetectionResult,o=>{const p=o.data;!p||p.frame.deviceId!==e||(n(Dme(p.frame)),a.current&&clearTimeout(a.current),a.current=setTimeout(()=>n([]),Nme))}),T.useEffect(()=>()=>{a.current&&clearTimeout(a.current),n([])},[e]),t.length===0?null:v.jsx("div",{style:{position:"absolute",inset:0,overflow:"hidden",pointerEvents:"none"},children:t.map((o,p)=>{const f=Pme(o.label),m=Math.round(o.score*100);return v.jsx("div",{style:{position:"absolute",left:`${o.x1*100}%`,top:`${o.y1*100}%`,width:`${(o.x2-o.x1)*100}%`,height:`${(o.y2-o.y1)*100}%`,border:`2px solid ${f}`,borderRadius:3},children:v.jsx("span",{style:{position:"absolute",left:-2,bottom:"100%",background:f,color:"#fff",fontSize:10,fontWeight:700,fontFamily:"system-ui, sans-serif",lineHeight:"14px",padding:"0 4px",borderRadius:3,whiteSpace:"nowrap"},children:`${o.label} ${m}%`})},`${o.label}-${p}`)})})}function Lme(e,t,n,a){const o=Number.isFinite(e)&&e>0?e:0,p=Number.isFinite(t)&&t>0?t:0;if(!Number.isFinite(n)||!Number.isFinite(a)||n<=0||a<=0)return{width:o,height:p};const f=Math.min(o/n,p/a);return{width:n*f,height:a*f}}function qme(e,t,n){return!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(n)?0:Math.max(0,(n*t-e)/2)}function SA(e,t,n,a){if(!Number.isFinite(e))return 0;const o=qme(t,n,a);return Math.max(-o,Math.min(o,e))}const Bme=4,xA=8,Ume=300;function kA(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function Fme({children:e,onTap:t}){const n=T.useRef(null),a=T.useRef(null),o=T.useRef(new Map),p=T.useRef(1),f=T.useRef(0),m=T.useRef(0),h=T.useRef(null),u=T.useRef(null),x=T.useRef(0),w=()=>{const D=a.current;D&&(D.style.transform=`translate(${f.current}px, ${m.current}px) scale(${p.current})`)},C=()=>{const D=n.current?.getBoundingClientRect();if(!D||D.width<=0||D.height<=0)return;const z=a.current?.querySelector("video")??null,B=z?null:a.current?.querySelector("img")??null,q=z?.videoWidth??B?.naturalWidth??0,G=z?.videoHeight??B?.naturalHeight??0,ae=Lme(D.width,D.height,q,G);f.current=SA(f.current,D.width,ae.width,p.current),m.current=SA(m.current,D.height,ae.height,p.current)},A=()=>{p.current=1,f.current=0,m.current=0,w()},R=D=>{try{D.currentTarget.setPointerCapture(D.pointerId)}catch{}if(o.current.set(D.pointerId,{x:D.clientX,y:D.clientY}),o.current.size===2){const z=[...o.current.values()],B=z[0],q=z[1];B&&q&&(h.current={dist:kA(B,q),scale:p.current,cx:(B.x+q.x)/2,cy:(B.y+q.y)/2,tx:f.current,ty:m.current}),u.current=null}else o.current.size===1&&(u.current={x:D.clientX,y:D.clientY,tx:f.current,ty:m.current,moved:!1})},I=D=>{if(!o.current.has(D.pointerId))return;if(o.current.set(D.pointerId,{x:D.clientX,y:D.clientY}),o.current.size>=2&&h.current){const B=[...o.current.values()],q=B[0],G=B[1];if(!q||!G)return;const ae=kA(q,G);h.current.dist>0&&(p.current=Math.max(1,Math.min(Bme,h.current.scale*(ae/h.current.dist))));const Q=(q.x+G.x)/2,H=(q.y+G.y)/2;f.current=h.current.tx+(Q-h.current.cx),m.current=h.current.ty+(H-h.current.cy),C(),w();return}const z=u.current;if(o.current.size===1&&z){const B=D.clientX-z.x,q=D.clientY-z.y;(Math.abs(B)>xA||Math.abs(q)>xA)&&(z.moved=!0),p.current>1&&(f.current=z.tx+B,m.current=z.ty+q,C(),w())}},O=D=>{const z=o.current.size===1,B=u.current;if(o.current.delete(D.pointerId),o.current.size<2&&(h.current=null),o.current.size===0&&(u.current=null,z&&B&&!B.moved)){const q=Date.now();q-x.current<Ume?(x.current=0,A()):(x.current=q,t())}};return v.jsx("div",{ref:n,style:{position:"absolute",inset:0,overflow:"hidden",touchAction:"none"},onPointerDown:R,onPointerMove:I,onPointerUp:O,onPointerCancel:O,children:v.jsx("div",{ref:a,style:{width:"100%",height:"100%",transformOrigin:"center center",willChange:"transform"},children:e})})}function Hme(e,t){if(t==null||t.length===0)return null;if(/^https?:\/\//i.test(t))return t;const n=e.replace(/\/+$/,""),a=t.startsWith("/")?t:`/${t}`;return`${n}${a}`}function $me(e,t){const n=t[0];return n===void 0?null:Hme(e,n.url)}function Qme(e,t){return{handleOffer:(n,a,o)=>e(t,n,a,o),reoffer:(n,a,o,p)=>e(o,a,n,p)}}const Vme=3500;function Gme(e){return e==="auto"?{kind:"adaptive"}:{kind:"profile",profile:e}}function Zme({system:e,deviceId:t,name:n,online:a,quality:o,muted:p,paused:f,showName:m,audioActive:h,micActive:u,onTogglePause:x,onToggleAudio:w,onToggleMic:C,onOpen:A,ptzSupported:R,onPtz:I,cellW:O,cellH:D,onCellPanel:z,highlight:B,showBoxes:q,overlay:G,reconnectSignal:ae,onStall:Q,posterUrl:H,labels:oe=im,editable:we,span:Me,onRemove:Ae,onResize:Ce}){const{handleOffer:re,getIceServers:Te,addIceCandidate:F,getIceCandidates:ue,closeSession:ke,getSessionState:Ee}=qN(e.trpcClient,t),fe=M5(e,t,B),L=T.useRef(null),[ee,me]=T.useState(0),[be,X]=T.useState("idle"),xe=yme({containerRef:L,playing:be==="playing"&&!f,onRecover:()=>{me(We=>We+1),Q?.(t)}}),[Oe,le]=T.useState(void 0);T.useEffect(()=>{if(H||f)return;let We=!1;const _n=O!==void 0&&O>0?Math.round(O):void 0;return e.trpcClient.snapshot.getSnapshotLinks.query({targets:[{deviceId:t,..._n!==void 0?{width:_n}:{}}]}).then(Aa=>{if(We)return;const Ja=$me(e.serverUrl,Aa??[]);Ja!==null&&le(Ja)}).catch(()=>{}),()=>{We=!0}},[H,f,e,t,O]);const ye=H??Oe,Be=T.useMemo(()=>Gme(o),[o]),ot=`grid:${t}:${o}`,Ve=T.useMemo(()=>Qme(re,Be),[re,Be]),[Ie,bt]=T.useState(!1),Re=T.useRef(null),Le=()=>{Re.current&&clearTimeout(Re.current),Re.current=setTimeout(()=>bt(!1),Vme)},lt=()=>{bt(!0),Le()},st=()=>{bt(We=>{const _n=!We;return _n&&Le(),_n})},Pt=Mme(O??0,D??0),Rt=We=>{We.stopPropagation(),lt()},gn=O!==void 0&&D!==void 0&&O>0&&D>0,Ca=Tme(O??0,D??0,Rme),Wa=gn?{position:"absolute",left:Ca.left,top:Ca.top,width:Ca.width,height:Ca.height}:{position:"absolute",inset:0},$t=Math.max(1,Math.round(Me?.cw??1)),Ya=Math.max(1,Math.round(Me?.ch??1)),Xa=gn&&O!==void 0?O/$t:0,zn=gn&&D!==void 0?D/Ya:0,Kn=Eme(we===!0,O??0,D??0);return T.useEffect(()=>()=>{Re.current&&clearTimeout(Re.current)},[]),v.jsxs("div",{ref:L,"data-stall-recovering":xe.recovering?"true":void 0,style:{position:"relative",width:"100%",height:"100%",background:"#000"},children:[v.jsxs("div",{style:Wa,children:[v.jsx(Fme,{onTap:st,children:f?v.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:"#fafaf9"},children:v.jsx(MA,{size:28})}):v.jsx(_4,{serverUrl:e.serverUrl,streamKey:ot,autoPlay:!0,muted:p,showControls:!1,className:"w-full h-full",handleOffer:Ve.handleOffer,reoffer:Ve.reoffer,getSessionState:Ee,getIceServers:Te,addIceCandidate:F,getIceCandidates:ue,closeSession:ke,reconnectSignal:(ae??0)+ee,onStateChange:X,posterUrl:ye,onClientNetworkSample:o==="auto"?We=>{e.trpcClient.networkQuality.reportClientStats.mutate({deviceId:t,...We}).catch(()=>{})}:void 0},ot)}),q&&!f?v.jsx(zme,{deviceId:t}):null,G?.motionBoxes===!0&&!f?v.jsx(cme,{deviceId:t}):null]}),fA(G?.audioMeter)&&!f?v.jsx(ume,{deviceId:t,anchor:G.audioMeter}):null,fA(G?.occupancy)&&!f?v.jsx(pme,{system:e,deviceId:t,anchor:G.occupancy}):null,G?.stats===!0&&!f?v.jsx(mme,{containerRef:L}):null,fe&&(()=>{const We=B?.appearance,_n=fe==="motion"?We?.motionColor??Ws.motion:fe==="audio"?We?.audioColor??Ws.audio:We?.detectionColor??Ws.detection,Aa=We?.thickness??3;return v.jsx("div",{style:{position:"absolute",inset:0,border:`${Aa}px solid ${_n}`,boxShadow:`inset 0 0 12px ${_n}`,pointerEvents:"none"}})})(),(m||Ie)&&v.jsxs("div",{style:{position:"absolute",left:0,right:0,top:0,display:"flex",alignItems:"center",gap:6,padding:"4px 8px",background:"rgba(0,0,0,0.6)",color:"#fafaf9",fontSize:12,fontWeight:600,fontFamily:"system-ui, sans-serif",pointerEvents:"none",opacity:m||Ie?1:0,transition:"opacity 150ms ease"},children:[v.jsx("span",{style:{width:8,height:8,borderRadius:4,background:a?"#34d399":"#71717a"}}),v.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n})]}),v.jsxs("div",{style:{position:"absolute",inset:0,opacity:Ie?1:0,transition:"opacity 150ms ease",pointerEvents:"none"},children:[v.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"},children:v.jsx(Tr,{label:f?oe.play:oe.pause,big:!0,enabled:Ie,onClick:We=>{Rt(We),x(t)},children:f?v.jsx(MA,{size:22}):v.jsx(Kme,{size:22})})}),v.jsxs("div",{style:{position:"absolute",left:8,bottom:8,display:"flex",gap:8,pointerEvents:"none"},children:[v.jsx(Tr,{label:h?oe.mute:oe.listen,active:h,enabled:Ie,onClick:We=>{Rt(We),w(t)},children:h?v.jsx(Wme,{size:18}):v.jsx(Yme,{size:18})}),v.jsx(Tr,{label:u?oe.stopTalk:oe.talk,active:u,enabled:Ie,onClick:We=>{Rt(We),C(t)},children:v.jsx(Xme,{size:18,muted:!u})}),R&&I&&(!z||!Pt.overflow)?v.jsx(Tr,{label:oe.ptz,enabled:Ie,onClick:We=>{Rt(We),I(t)},children:v.jsx(ife,{size:18})}):null,z?Pt.inline.map(We=>v.jsx(Tr,{label:We==="devices"?oe.linkedDevices:oe.viewOptions,enabled:Ie,onClick:_n=>{Rt(_n),z(t,We)},children:We==="devices"?v.jsx(efe,{size:18}):v.jsx(tfe,{size:18})},We)):null,z&&Pt.overflow?v.jsx(Tr,{label:oe.moreActions,enabled:Ie,onClick:We=>{Rt(We),z(t,"actions")},children:v.jsx(nfe,{size:18})}):null]}),v.jsx("div",{style:{position:"absolute",right:8,bottom:8,pointerEvents:"none"},children:v.jsx(Tr,{label:oe.open,enabled:Ie,onClick:We=>{Rt(We),A(t)},children:v.jsx(Jme,{size:18})})}),Kn&&Ae?v.jsx("div",{style:{position:"absolute",right:8,top:8,pointerEvents:"none"},children:v.jsx(Tr,{label:oe.removeFromView,enabled:Ie,onClick:We=>{Rt(We),Ae(t)},children:v.jsx(afe,{size:18})})}):null,Kn&&Ce?v.jsxs(v.Fragment,{children:[v.jsx(wA,{axis:"x",label:oe.resizeWidth,enabled:Ie,track:Xa,span:$t,onSpan:We=>{lt(),Ce(t,We,Ya)}}),v.jsx(wA,{axis:"y",label:oe.resizeHeight,enabled:Ie,track:zn,span:Ya,onSpan:We=>{lt(),Ce(t,$t,We)}})]}):null]})]})}function wA({axis:e,label:t,enabled:n,track:a,span:o,onSpan:p}){const f=T.useRef(null),m=h=>e==="x"?h.clientX:h.clientY;return v.jsx("div",{role:"separator","aria-label":t,"aria-orientation":e==="x"?"vertical":"horizontal",onPointerDown:h=>{h.stopPropagation(),h.currentTarget.setPointerCapture(h.pointerId),f.current={origin:m(h),base:o}},onPointerMove:h=>{if(f.current===null||!(a>0))return;h.stopPropagation();const u=Math.round((m(h)-f.current.origin)/a),x=Math.max(1,f.current.base+u);x!==o&&p(x)},onPointerUp:h=>{f.current=null,h.currentTarget.hasPointerCapture(h.pointerId)&&h.currentTarget.releasePointerCapture(h.pointerId)},onPointerCancel:()=>{f.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,background:"rgba(0,0,0,0.55)",border:"1px solid rgba(250,250,249,0.35)",cursor:e==="x"?"ew-resize":"ns-resize",touchAction:"none",pointerEvents:n?"auto":"none"}})}function Tr({children:e,label:t,onClick:n,big:a=!1,active:o=!1,enabled:p=!0}){const f=a?52:40;return v.jsx("button",{type:"button","aria-label":t,onClick:n,style:{width:f,height:f,borderRadius:f/2,border:"none",display:"flex",alignItems:"center",justifyContent:"center",background:o?"rgba(59,130,246,0.85)":"rgba(0,0,0,0.55)",color:"#fafaf9",cursor:"pointer",padding:0,WebkitTapHighlightColor:"transparent",pointerEvents:p?"auto":"none"},children:e})}const Zr={fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};function MA({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 Kme({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 Wme({size:e}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",...Zr,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 Yme({size:e}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",...Zr,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 Xme({size:e,muted:t}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",...Zr,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 Jme({size:e}){return v.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",...Zr,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 efe({size:e}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",...Zr,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 tfe({size:e}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",...Zr,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 nfe({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 afe({size:e}){return v.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",...Zr,children:v.jsx("path",{d:"M18 6L6 18M6 6l12 12"})})}function ife({size:e}){return v.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",...Zr,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 rfe({wall:e,renderTile:t}){return v.jsx("div",{style:{position:"relative",width:e.wallW,height:e.wallH},children:e.placements.map(n=>v.jsx("div",{"data-device-id":n.deviceId,style:{position:"absolute",left:n.x,top:n.y,width:n.w,height:n.h},children:t(n.deviceId,n.w,n.h)},n.deviceId))})}function CA({message:e}){return T.useEffect(()=>di(x5("error",e)),[e]),v.jsxs("div",{style:{position:"fixed",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:"#000",color:"#f87171",fontFamily:"system-ui, sans-serif",fontSize:13,padding:16,textAlign:"center"},children:["Grid embed config error: ",e]})}const ofe=["setDevices","setSpans"];function sfe(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function lfe({system:e,config:t}){const[n,a]=T.useState(t.devices),[o,p]=T.useState(()=>new Set(t.audioOnIds??[])),f=S5(),m=T.useRef(f.setActiveMic);m.current=f.setActiveMic;const[h,u]=T.useState(()=>new Set(t.pausedIds??[])),[x,w]=T.useState(t.highlight),[C,A]=T.useState(t.activeOnly??!1),[R,I]=T.useState(t.showBoxes??!1),[O,D]=T.useState(()=>t.overlays??{}),[z,B]=T.useState(()=>t.spans??{}),q=Bpe(n,x),G=T.useMemo(()=>C?n.filter(X=>q.has(X)):n,[C,n,q]),[ae,Q]=T.useState(t.quality),[H,oe]=T.useState(t.layout),[we,Me]=T.useState(t.showName),[Ae,Ce]=T.useState(0),re=T.useMemo(()=>hpe(t.labels),[t.labels]),[Te,F]=T.useState(()=>t.snapshots??{}),ue=T.useMemo(()=>new Set(t.ptzIds??[]),[t.ptzIds]),[ke,Ee]=T.useState({w:window.innerWidth,h:window.innerHeight}),fe=re.camera,[L,ee]=T.useState({});T.useEffect(()=>{let X=!1;return e.trpcClient.deviceManager.listAll.query({deviceIds:[...n],projection:"slim"}).then(xe=>{if(X)return;const Oe={};for(const le of xe)Oe[le.id]={name:le.name??`${fe} ${le.id}`,online:le.online??!1};ee(Oe)}).catch(()=>{}),()=>{X=!0}},[e,n,fe]),T.useEffect(()=>(window.__camstackGrid={setAudioOn:X=>p(new Set(X)),setMutedAll:X=>{X&&p(new Set)},setActiveMic:X=>m.current(X),setHighlight:X=>w(X),setActiveOnly:X=>A(X),setShowBoxes:X=>I(X),setOverlays:X=>D(X),setPaused:X=>u(new Set(X)),setDevices:X=>a(xe=>sfe(xe,X)?xe:[...X]),setSpans:X=>B(X),setQuality:X=>Q(X),setLayout:X=>oe(X),setShowName:Me,setShowBadges:()=>{},setSnapshots:X=>F(X),fit:(X,xe)=>Ee({w:X,h:xe}),reconnect:()=>Ce(X=>X+1)},di(x5("ready",void 0,ofe)),()=>{window.__camstackGrid&&delete window.__camstackGrid}),[]),T.useEffect(()=>hu(X=>{const xe=window.__camstackGrid;if(!xe)return;switch(X.kind){case"setAudioOn":xe.setAudioOn(X.value);break;case"setMutedAll":xe.setMutedAll(X.value);break;case"setActiveMic":xe.setActiveMic(X.value);break;case"setHighlight":xe.setHighlight(X.value);break;case"setActiveOnly":xe.setActiveOnly(X.value);break;case"setShowBoxes":xe.setShowBoxes(X.value===!0);break;case"setOverlays":xe.setOverlays(X.value);break;case"setPaused":xe.setPaused(X.value);break;case"setDevices":xe.setDevices(X.value);break;case"setSpans":xe.setSpans(X.value);break;case"setQuality":xe.setQuality(f5.parse(X.value));break;case"setLayout":xe.setLayout(X.value);break;case"setShowName":xe.setShowName(X.value);break;case"setShowBadges":xe.setShowBadges(X.value);break;case"setSnapshots":xe.setSnapshots(X.value);break;case"fit":xe.fit(X.w,X.h);break;case"reconnect":xe.reconnect();break}}),[]);const me=T.useMemo(()=>zpe(G,ke.w,ke.h,H,z),[G,ke.w,ke.h,H,z]),be=T.useRef(null);return T.useEffect(()=>{const X=be.current;if(!X)return;const xe=[];X.querySelectorAll("[data-device-id]").forEach(Oe=>{const le=Number(Oe.dataset.deviceId),ye=Oe.getBoundingClientRect();xe.push({deviceId:le,rect:{x:ye.x,y:ye.y,w:ye.width,h:ye.height}})}),xe.length&&di(Zpe(xe))},[me,G]),v.jsxs("div",{ref:be,style:{position:"fixed",inset:0,background:"#000",display:"flex",alignItems:"center",justifyContent:"center"},children:[C&&G.length===0&&v.jsx("div",{style:{color:"#a1a1aa",fontFamily:"system-ui, sans-serif",fontSize:14,padding:24,textAlign:"center"},children:re.noActiveCameras}),v.jsx(rfe,{wall:me,renderTile:(X,xe,Oe)=>v.jsx(Zme,{system:e,deviceId:X,name:L[X]?.name??`${re.camera} ${X}`,online:L[X]?.online??!1,quality:ae,muted:!o.has(X),paused:h.has(X),showName:we,audioActive:o.has(X),micActive:f.activeMicId===X,onTogglePause:le=>di(Hpe(le)),onToggleAudio:le=>di(Fpe(le)),onToggleMic:f.toggleMic,onOpen:le=>di(Upe(le)),ptzSupported:ue.has(X),onPtz:le=>di($pe(le)),cellW:xe,cellH:Oe,onCellPanel:t.cellPanels===!1?void 0:(le,ye)=>di(Qpe(le,ye)),highlight:x,showBoxes:R,overlay:O[String(X)],reconnectSignal:Ae,posterUrl:Te[String(X)],editable:t.editable===!0,span:z[String(X)],onRemove:le=>di(Vpe(le)),onResize:(le,ye,Be)=>di(Gpe(le,ye,Be)),labels:re})})]})}function cfe(){const e=Tm("grid",()=>window.__CAMSTACK_GRID__,g5,_pe),t=T.useMemo(()=>{if(e===null||!e.ok)return null;const n=bm({serverUrl:e.config.serverUrl,token:e.config.token}),a=new wT({defaultOptions:{queries:{retry:!1,refetchOnWindowFocus:!1}}});return{system:n,queryClient:a}},[e]);return T.useEffect(()=>{if(t)return()=>t.system.close()},[t]),e===null?null:e.ok?t?v.jsx(sI,{system:t.system,children:v.jsx(CT,{client:t.queryClient,children:v.jsx(y.Provider,{client:t.system.trpcClient,queryClient:t.queryClient,children:v.jsx(lfe,{system:t.system,config:e.config})})})}):v.jsx(CA,{message:"Failed to initialise the grid embed"}):v.jsx(CA,{message:e.error})}const _0=nt([d({kind:V("adaptive")}),d({kind:V("profile"),profile:Rn})]),ufe=d({deviceId:l().int().nonnegative(),target:_0.optional(),muted:E().optional(),stats:E().optional(),snapshot:s().optional()});function dfe(e){const t=ufe.safeParse(e);return t.success?t.data:null}const pfe=["live","loading","playing","paused","gap","ended","error"];function mfe(e){return typeof e=="string"&&pfe.includes(e)}const bo="low",AA=5e3;class ffe{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;onMessage=t=>{if(this.disposed||typeof t.data!="string")return;let n;try{n=JSON.parse(t.data)}catch{return}if(typeof n!="object"||n===null)return;const a=n;if(a.t==="liveProfile"&&(a.profile==="high"||a.profile==="mid"||a.profile==="low")){this.deps.onLiveProfile?.(a.profile);return}if(a.t==="servedProfile"&&(a.profile==="high"||a.profile==="mid"||a.profile==="low")&&typeof a.requested=="string"){const o=a.requested;this.lastSentProfile=a.profile,this.degradedRequest=a.profile===o?null:o,this.degradedRequest!==null&&this.pendingUpgrade?.desiredProfile===this.degradedRequest&&(this.deps.onLog?.("scrub:playback-upgrade-vetoed",{to:this.degradedRequest}),this.cancelPlaybackUpgrade()),this.deps.onServedProfile?.({profile:a.profile,requested:o});return}if(a.t==="state"&&mfe(a.state)){this.lastState=a.state,a.state==="playing"||a.state==="paused"?(this.maybeArmPlaybackUpgrade(),this.playIntentAt!==null&&(this.deps.onLog?.("playback:ready",{kind:this.playIntentKind,state:a.state,waitMs:Math.round(performance.now()-this.playIntentAt),dragId:this.playIntentDragId}),this.playIntentAt=null,this.playIntentKind=null,this.playIntentDragId=void 0)):(a.state==="live"||a.state==="gap"||a.state==="ended"||a.state==="error")&&this.cancelPlaybackUpgrade(),this.deps.onState?.(a.state);return}a.t!=="position"||typeof a.epochMs!="number"||(this.lastCursorMs=a.epochMs,this.deps.onPosition?.(a.epochMs),typeof a.seq=="number"&&(this.lastPushSeq=a.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,n,a,o,p){const f=this.send({t:"playRecorded",deviceId:t,epoch:n,profile:a});return f&&(this.lastSentProfile=a,this.playIntentAt=performance.now(),this.playIntentKind=o,this.playIntentDragId=p,this.deps.onLog?.("playback:intent",{kind:o,deviceId:t,epochMs:n,profile:a,dragId:p})),f}maybeArmPlaybackUpgrade(){if(this.pendingUpgrade===null||this.upgradeTimer!==null||this.disposed)return;this.upgradeTimer=setTimeout(()=>this.firePlaybackUpgrade(),AA);const t=this.pendingUpgrade;this.upgradeWarmTimer=setTimeout(()=>{if(this.upgradeWarmTimer=null,this.pendingUpgrade===null||this.disposed)return;const n=this.lastCursorMs??t.landEpochMs;this.warm(n,t.desiredProfile)},Math.max(0,AA-1500))}firePlaybackUpgrade(){this.upgradeTimer=null;const t=this.pendingUpgrade;if(this.pendingUpgrade=null,!t||this.disposed)return;const n=this.lastCursorMs??t.landEpochMs;this.sendPlayRecorded(t.deviceId,n,t.desiredProfile,"upgrade"),this.deps.onLog?.("scrub:playback-upgrade",{from:bo,to:t.desiredProfile,epochMs:n})}cancelPlaybackUpgrade(){this.upgradeTimer!==null&&(clearTimeout(this.upgradeTimer),this.upgradeTimer=null),this.upgradeWarmTimer!==null&&(clearTimeout(this.upgradeWarmTimer),this.upgradeWarmTimer=null),this.pendingUpgrade=null}playRecorded(t,n,a){return this.cancelPlaybackUpgrade(),this.sendPlayRecorded(t,n,a,"play")}upgradePlayback(t,n,a){return a===this.lastSentProfile?!0:(this.cancelPlaybackUpgrade(),this.warm(n,a),this.sendPlayRecorded(t,n,a,"upgrade"))}landFromScrub(t,n,a,o){return this.end(),this.cancelPlaybackUpgrade(),this.sendPlayRecorded(t,n,bo,"land",o)?(this.lastCursorMs=n,a===this.degradedRequest?this.deps.onLog?.("scrub:playback-upgrade-vetoed",{to:a,epochMs:n}):a!==bo&&(this.pendingUpgrade={deviceId:t,desiredProfile:a,landEpochMs:n},this.warm(n,a),(this.lastState==="playing"||this.lastState==="paused")&&this.maybeArmPlaybackUpgrade()),!0):!1}seek(t){this.cancelPlaybackUpgrade();const n=this.send({t:"seek",epoch:t});return n&&(this.playIntentAt=performance.now(),this.playIntentKind="seek",this.playIntentDragId=void 0,this.deps.onLog?.("playback:intent",{kind:"seek",epochMs:t})),n}warm(t,n=bo){return this.send({t:"warm",epoch:t,profile:n})}setRate(t){return this.send({t:"setRate",rate:t})}stepFrame(t){return this.send({t:"stepFrame",dir:t})}commit(t,n){return this.end(),this.send(n!==void 0?{t:"scrubCommit",epoch:t,dragId:n}:{t:"scrubCommit",epoch:t})}goLive(){this.cancelPlaybackUpgrade();const t=this.send({t:"goLive"});return t&&this.deps.onLog?.("scrub:push-golive",{}),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!==bo&&(this.lastSentProfile=bo,this.send({t:"setProfile",profile:bo})),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,n){this.isActive()&&(this.retargets+=1,this.send(n?{t:"scrubTo",epoch:t,m:n.mode,v:Math.round(n.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 hfe(e,t,n,a){return e?.isOpen()?(e.warm(n),e.playRecorded(t,n,a)):!1}const gfe=24e4;function vfe(e,t=gfe){if(t<=0)return[e];const n=[];for(let a=0;a<e.length;a+=t)n.push(e.slice(a,a+t));return n.length===0?[""]:n}const yfe=["video/mp4;codecs=avc1.42E01E,mp4a.40.2","video/webm;codecs=vp8,opus","video/webm;codecs=vp9,opus"],EA=["video/mp4;codecs=avc1.42E01E","video/mp4","video/webm;codecs=vp8","video/webm"];function bfe(e=n=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(n),t){const n=t?.audio?[...yfe,...EA]:EA;for(const a of n)try{if(e(a))return a}catch{}return""}function Sfe(e,t){const n=[...e.getVideoTracks()],a=t?.getAudioTracks()??[],o=a.length>0?a.map(p=>{const f=p.clone();return"enabled"in f&&(f.enabled=!0),f}):[...e.getAudioTracks()];return[...n,...o]}function xfe(e,t=30){const n=e;try{if(typeof n.captureStream=="function"){const a=n.captureStream(t);if(a.getVideoTracks().length>0)return a}}catch{}try{if(typeof n.mozCaptureStream=="function"){const a=n.mozCaptureStream(t);if(a.getVideoTracks().length>0)return a}}catch{}return kfe(e,t)}function kfe(e,t){if(e.videoWidth<2||e.videoHeight<2||typeof document>"u")return null;const n=document.createElement("canvas");n.width=e.videoWidth,n.height=e.videoHeight;const a=n.getContext("2d");if(!a||typeof n.captureStream!="function")return null;let o=!0;const p=()=>{if(o){try{a.drawImage(e,0,0,n.width,n.height)}catch{}requestAnimationFrame(p)}};p();const f=n.captureStream(t),m=f.getVideoTracks()[0];if(m){const h=m.stop.bind(m);m.stop=()=>{o=!1,h()}}return f}function wfe(e){return new Promise((t,n)=>{const a=new FileReader;a.onload=()=>{const o=String(a.result??""),p=o.indexOf(",");t(p>=0?o.slice(p+1):o)},a.onerror=()=>n(a.error??new Error("read failed")),a.readAsDataURL(e)})}function Mfe(){return`c${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}function Cfe(e){let t=null,n=[],a=null,o="",p=!1;const f=()=>{if(t=null,n=[],p=!1,a){for(const h of a.getTracks())try{h.stop()}catch{}a=null}},m=h=>{f(),e.emit({type:"liveCaptureError",message:h})};return{start(){if(t)return;const h=e.getVideo();if(!h){m("no video");return}if(typeof MediaRecorder>"u"){m("MediaRecorder missing");return}const u=xfe(h);if(!u){m("no video");return}const x=h.srcObject instanceof MediaStream?h.srcObject:null,w=Sfe(u,x);if(x&&x.getAudioTracks().length>0)for(const I of u.getAudioTracks())try{I.stop()}catch{}const C=new MediaStream(w);a=C;const A=w.some(I=>I.kind==="audio"),R=bfe(void 0,{audio:A});try{t=R?new MediaRecorder(C,{mimeType:R,videoBitsPerSecond:25e5,...A?{audioBitsPerSecond:128e3}:{}}):new MediaRecorder(C)}catch(I){m(I instanceof Error?I.message:"MediaRecorder missing");return}n=[],o=Mfe(),p=!1,t.ondataavailable=I=>{I.data&&I.data.size>0&&n.push(I.data)},t.onerror=()=>m("MediaRecorder missing");try{t.start(1e3)}catch(I){m(I instanceof Error?I.message:"MediaRecorder missing")}},stop(){const h=t;if(!h||p){h||m("no video");return}p=!0;const u=o,x=h.mimeType||"video/mp4";h.onstop=()=>{const w=new Blob(n,{type:x});if(f(),w.size===0){e.emit({type:"liveCaptureError",message:"empty capture"});return}wfe(w).then(C=>{e.emit({type:"liveCaptureStart",id:u,mime:x});const A=vfe(C),R=A.length;A.forEach((I,O)=>{e.emit({type:"liveCaptureChunk",id:u,index:O,total:R,data:I})}),e.emit({type:"liveCaptureDone",id:u})}).catch(C=>{e.emit({type:"liveCaptureError",message:C instanceof Error?C.message:"encode failed"})})};try{typeof h.requestData=="function"&&h.requestData(),h.stop()}catch(w){m(w instanceof Error?w.message:"stop failed")}},abort(){if(t&&t.state!=="inactive")try{t.stop()}catch{}f()}}}const Afe=8,Efe=2.5;function Rfe(e){return e>=Afe?"high":e>=Efe?"mid":"low"}function _fe(e,t){return e.kind==="profile"?e.profile:"low"}function Tfe(e,t){return e.kind==="profile"?e.profile:Rfe(t)}const Ife=d({serverUrl:s().min(1),token:s().min(1),deviceId:l().int().nonnegative(),target:_0,muted:E(),stats:E().optional(),highlight:h5.optional(),snapshot:s().optional(),initialSeekMs:l().positive().optional()});function Wy(e,t){an(t!==void 0?{type:"state",state:e,message:t}:{type:"state",state:e})}function Nfe(e){switch(e){case"playing":return"playing";case"error":return"error";case"connecting":case"disconnected":case"idle":return"connecting"}}function RA(e,t){return _fe(e)}async function Ofe(){if(typeof window>"u")return null;const e=window.location.origin.replace(/\/+$/,""),t=new AbortController,n=window.setTimeout(()=>t.abort(),2500),a=performance.now();try{const o=await fetch(`${e}/adaptive-probe`,{signal:t.signal});if(!o.ok)return null;const p=await o.arrayBuffer(),f=Math.max(1,performance.now()-a);return p.byteLength<1024?null:p.byteLength*8/f/1e3}catch{return null}finally{window.clearTimeout(n)}}function _A(e,t,n,a){a.kind==="adaptive"&&Ofe().then(o=>{if(o===null)return;const p=Tfe(a,o);e.upgradePlayback(t,n,p)})}function jfe(e){return e.kind==="adaptive"?{kind:"adaptive"}:{kind:"profile",profile:e.profile}}function Pfe(e){return e.kind==="adaptive"?"embed:adaptive":`embed:profile:${e.profile}`}function Dfe(e){const t=Ife.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(n=>`${n.path.join(".")||"(root)"}: ${n.message}`).join("; ")}}function TA({message:e}){return T.useEffect(()=>{Wy("error",e)},[e]),v.jsxs("div",{style:{position:"fixed",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:"#000",color:"#f87171",fontFamily:"system-ui, sans-serif",fontSize:13,padding:16,textAlign:"center"},children:["Embed config error: ",e]})}function zfe({system:e,deviceId:t,initialTarget:n,initialMuted:a,initialStats:o,initialHighlight:p,initialSnapshot:f,initialSeekMs:m}){const[h,u]=T.useState(n);T.useEffect(()=>o5(t),[t]);const x=T.useRef(h);x.current=h;const[w,C]=T.useState(a),[A,R]=T.useState(o),[I,O]=T.useState(p),[D,z]=T.useState(f),[B,q]=T.useState(0),[G,ae]=T.useState({w:window.innerWidth,h:window.innerHeight}),Q=M5(e,t,I),H=S5(),oe=T.useRef(H.setActiveMic);oe.current=H.setActiveMic;const{handleOffer:we,getIceServers:Me,addIceCandidate:Ae,getIceCandidates:Ce,closeSession:re,getSessionState:Te}=qN(e.trpcClient,t),F=T.useMemo(()=>jfe(h),[h]),ue=T.useMemo(()=>(le,ye,Be)=>we(F,le,ye,Be),[we,F]),ke=T.useMemo(()=>(le,ye,Be,ot)=>we(Be,ye,le,ot),[we]),Ee=T.useRef(null),fe=T.useRef(null),L=T.useRef("low"),ee=T.useRef(!1),me=T.useRef(null),be=T.useRef(null),X=()=>{const le=me.current;if(le===null)return;const ye=L.current,Be=`${le.phase}|${le.viewportWidth??"-"}x${le.viewportHeight??"-"}|${le.devicePixelRatio??"-"}|${le.downlinkMbps??"-"}|${le.prefersTier??"-"}|${le.probeOrigin??"unreachable"}|${ye}`;Be!==be.current&&(be.current=Be,an({type:"log",scope:"adaptive",msg:"tier decision",data:{deviceId:t,requested:h.kind==="adaptive"?"adaptive":`pinned:${h.kind}`,phase:le.phase,viewportWidth:le.viewportWidth??null,viewportHeight:le.viewportHeight??null,devicePixelRatio:le.devicePixelRatio??null,downlinkMbps:le.downlinkMbps??null,prefersTier:le.prefersTier??null,probeOrigin:le.probeOrigin,liveProfile:ye}}))},xe=T.useRef(m??null);T.useEffect(()=>{if(!w)return;const le=setInterval(()=>{let ye=0;for(const Be of Array.from(document.querySelectorAll("video"))){Be.muted||(Be.muted=!0,ye++);const ot=Be.srcObject;if(ot instanceof MediaStream)for(const Ve of ot.getAudioTracks())Ve.enabled&&(Ve.enabled=!1,ye++)}ye>0&&an({type:"log",scope:"live-audio",msg:"re-muted",data:{corrected:ye}})},1e3);return()=>clearInterval(le)},[w]),T.useEffect(()=>()=>Ee.current?.dispose(),[]),T.useEffect(()=>{const le=()=>{const Re=Ee.current;return Re?.isOpen()?Re:null},ye=()=>RA(x.current,L.current),Be=(Re,Le)=>{_A(Re,t,Le,x.current)},ot=Re=>{ee.current||(ee.current=!0,an({type:"log",scope:"recorded:session",msg:"pointer move with no open session",data:{what:Re}}),an({type:"recState",state:"error"}))},Ve=(Re,Le)=>{const lt=le();return!lt||!Le(lt)?(ot(Re),!1):(ee.current=!1,!0)},Ie=(Re,Le)=>{Ve("scrubCommit",lt=>{const st=lt.landFromScrub(t,Re,ye(),Le);return st&&Be(lt,Re),st})},bt=Cfe({emit:an,getVideo:()=>fe.current});return window.__camstackEmbed={setMuted:Re=>C(Re),setTarget:Re=>{const Le=_0.safeParse(Re);Le.success&&u(Le.data)},setStats:Re=>R(Re),setHighlight:Re=>O(Re),setSnapshot:Re=>z(Re),setMic:Re=>oe.current(Re?t:null),fit:(Re,Le)=>ae({w:Re,h:Le}),reconnect:()=>q(Re=>Re+1),playRecorded:(Re,Le,lt)=>{Number.isFinite(Le)&&Ve("playRecorded",st=>st.playRecorded(Re,Le,lt))},seek:Re=>{Number.isFinite(Re)&&Ve("seek",Le=>{const lt=Le.playRecorded(t,Re,ye());return lt&&Be(Le,Re),lt})},scrubCommit:(Re,Le)=>{Number.isFinite(Re)&&Ie(Re,Le)},scrubStart:Re=>{an({type:"log",scope:"recorded:scrub",msg:"scrubStart",data:{dragId:Re}}),Ve("scrubStart",Le=>Le.begin(Re))},scrubTo:(Re,Le,lt)=>{if(!Number.isFinite(Re))return;const st=(Le==="fine"||Le==="coarse")&&Number.isFinite(lt)?{mode:Le,velocityPxPerS:lt}:void 0;Ve("scrubTo",Pt=>Pt.isActive()?(Pt.retarget(Re,st),!0):!1)},timelineWarm:Re=>{Number.isFinite(Re)&&le()?.warm(Re)},scrubEnd:Re=>{Number.isFinite(Re)&&Ie(Re)},setRate:Re=>{Number.isFinite(Re)&&Ve("setRate",Le=>Le.setRate(Re))},stepFrame:Re=>{Re!==1&&Re!==-1||Ve("stepFrame",Le=>Le.stepFrame(Re))},goLive:()=>{Ve("goLive",Re=>Re.goLive())&&an({type:"recState",state:"live"})},startLiveCapture:()=>bt.start(),stopLiveCapture:()=>bt.stop()},()=>{bt.abort(),window.__camstackEmbed&&delete window.__camstackEmbed}},[t]),T.useEffect(()=>{an({type:"micState",state:H.micState})},[H.micState]),T.useEffect(()=>hu(le=>{const ye=window.__camstackEmbed;if(!ye)return;switch(le.kind){case"setMuted":ye.setMuted(le.value);break;case"setTarget":ye.setTarget(le.value);break;case"setStats":ye.setStats(le.value);break;case"setHighlight":ye.setHighlight(le.value);break;case"setSnapshot":ye.setSnapshot(le.value);break;case"setMic":ye.setMic(le.value);break;case"fit":ye.fit(le.w,le.h);break;case"reconnect":ye.reconnect();break;case"playRecorded":ye.playRecorded(le.deviceId,le.epochMs,le.profile);break;case"seek":ye.seek(le.epochMs??le.value);break;case"scrubCommit":ye.scrubCommit(le.epochMs??le.value,le.dragId);break;case"scrubStart":ye.scrubStart(le.dragId);break;case"scrubTo":ye.scrubTo(le.epochMs??le.value,le.m,le.v);break;case"scrubEnd":ye.scrubEnd(le.epochMs??le.value);break;case"timelineWarm":ye.timelineWarm(le.epochMs??le.value);break;case"setRate":ye.setRate(le.rate??le.value);break;case"stepFrame":{const ot=le.dir;(ot===1||ot===-1)&&ye.stepFrame(ot);break}case"goLive":ye.goLive();break;case"startLiveCapture":ye.startLiveCapture();break;case"stopLiveCapture":ye.stopLiveCapture();break}}),[]);const Oe=Pfe(h);return v.jsxs("div",{style:{position:"fixed",left:0,top:0,width:G.w,height:G.h,background:"#000"},children:[v.jsx(_4,{serverUrl:e.serverUrl,streamKey:Oe,autoPlay:!0,muted:w,showControls:!1,showStats:A,onPlaybackStats:le=>an({type:"log",scope:"playback",msg:"stats",data:le}),onConnectTiming:le=>an({type:"log",scope:"webrtc-timing",msg:"connect",data:le}),onClientNetworkSample:h.kind==="adaptive"?le=>{e.trpcClient.networkQuality.reportClientStats.mutate({deviceId:t,...le}).catch(()=>{})}:void 0,className:"w-full h-full",onAdaptiveHints:le=>{me.current=le,X()},handleOffer:ue,reoffer:ke,getSessionState:Te,getIceServers:Me,addIceCandidate:Ae,getIceCandidates:Ce,closeSession:re,reconnectSignal:B,posterUrl:D,onStateChange:le=>Wy(Nfe(le)),onError:le=>Wy("error",le),onReconnectAttempt:le=>an({type:"log",scope:"live:retry",msg:le.kind==="retry"?"auto-retry scheduled":"auto-retry exhausted",data:le}),onControlChannel:le=>{if(Ee.current?.dispose(),ee.current=!1,Ee.current=new ffe({channel:le,video:()=>fe.current,onState:ye=>an({type:"recState",state:ye}),onPosition:ye=>an({type:"position",positionMs:ye}),onServedProfile:ye=>an({type:"servedProfile",profile:ye.profile,requested:ye.requested}),onLiveProfile:ye=>{L.current=ye,X()},onFirstFrame:()=>an({type:"scrubDrawn"}),onLog:(ye,Be)=>an({type:"log",scope:ye.startsWith("playback:")?"playback":"scrub",msg:ye,data:Be})}),xe.current!==null){const ye=()=>{const Be=xe.current;if(Be===null)return;const ot=RA(x.current,L.current);hfe(Ee.current,t,Be,ot)&&(xe.current=null,Ee.current&&_A(Ee.current,t,Be,x.current),an({type:"log",scope:"recorded:initial-seek",msg:"config-carried seek fired",data:{epochMs:Be,profile:ot}}))};le.readyState==="open"?ye():le.addEventListener("open",ye,{once:!0})}},onVideoElement:le=>{fe.current=le}}),Q&&(()=>{const le=I?.appearance,ye=Q==="motion"?le?.motionColor??Ws.motion:Q==="audio"?le?.audioColor??Ws.audio:le?.detectionColor??Ws.detection,Be=le?.thickness??3;return v.jsx("div",{style:{position:"absolute",inset:0,border:`${Be}px solid ${ye}`,boxShadow:`inset 0 0 12px ${ye}`,pointerEvents:"none",transform:"translateZ(0)"}})})()]})}function Lfe(){const e=Tm("player",()=>window.__CAMSTACK_EMBED__,Dfe),[t,n]=T.useState(null);T.useEffect(()=>{const u=w=>{const C=dfe(w);C&&n(C)};window.__camstackEmbedPage={setDevice:u};const x=hu(w=>{w.kind==="setDevice"&&u(w.value)});return()=>{window.__camstackEmbedPage&&delete window.__camstackEmbedPage,x()}},[]);const a=T.useMemo(()=>{if(e===null||!e.ok)return null;const u=bm({serverUrl:e.config.serverUrl,token:e.config.token}),x=new wT({defaultOptions:{queries:{retry:!1,refetchOnWindowFocus:!1}}});return{system:u,queryClient:x}},[e]);if(T.useEffect(()=>{if(a)return()=>{a.system.close()}},[a]),e===null)return null;if(!e.ok)return v.jsx(TA,{message:e.error});if(!a)return v.jsx(TA,{message:"Failed to initialise the embed player"});const o=t?.deviceId??e.config.deviceId,p=t?.target??e.config.target,f=t?.muted??e.config.muted,m=t?.stats??e.config.stats??!1,h=t!==null?t.snapshot:e.config.snapshot;return v.jsx(sI,{system:a.system,children:v.jsx(CT,{client:a.queryClient,children:v.jsx(y.Provider,{client:a.system.trpcClient,queryClient:a.queryClient,children:v.jsx(zfe,{system:a.system,deviceId:o,initialTarget:p,initialMuted:f,initialStats:m,initialHighlight:e.config.highlight,initialSnapshot:h,initialSeekMs:t===null?e.config.initialSeekMs:void 0},o)})})})}const qfe=d({serverUrl:s().min(1),token:s().min(1),deviceId:l().int().nonnegative(),startMs:l().int().nonnegative().optional()});function Bfe(e){if(e==null)return{ok:!1,error:"config is required"};const t=qfe.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(n=>`${n.path.join(".")||"(root)"}: ${n.message}`).join("; ")}}function Ufe(e,t){const n=(e-t)/1e3;return Number.isFinite(n)&&n>0?n:0}const IA=360*60*1e3,Ffe="scrub unavailable: no open RecordedTrackSession";function Qa(e){an(e)}function fn(e,t,n){try{an({type:"log",scope:e,msg:t,data:n})}catch{}try{console.debug(`[rec-embed:${e}] ${t}`,n??"")}catch{}}function Hfe({system:e,config:t}){T.useEffect(()=>o5(t.deviceId),[t.deviceId]);const n=T.useRef(null),a=T.useRef(0),o=T.useRef(0),p=T.useRef(0),[f,m]=T.useState({w:window.innerWidth,h:window.innerHeight}),h=T.useMemo(()=>async u=>{const x=n.current;if(!x)return;const w=++p.current;o.current=performance.now(),fn("loadAt","start",{epochMs:u,window:IA}),Qa({type:"state",state:"loading"});try{const C=await e.trpcClient.recording.getPlaybackManifest.query({deviceId:t.deviceId,fromMs:u,toMs:u+IA});if(w!==p.current){fn("loadAt","superseded",{epochMs:u});return}if(fn("loadAt","manifest",{playbackUrl:C?.playbackUrl??null,endpoints:C?.playbackEndpoints?.length??0,localMaster:!!C?.localMasterPath}),!C?.playbackUrl){Qa({type:"state",state:"error",message:"no footage"});return}x.src=C.playbackUrl;const A=()=>{if(w!==p.current)return;const R=typeof x.getStartDate=="function"?x.getStartDate():null,I=R instanceof Date&&!Number.isNaN(R.getTime())?R.getTime():u;a.current=I;const O=Ufe(u,I);if(O>0)try{x.currentTime=O}catch(D){fn("loadAt","seek-failed",{msg:String(D)})}x.play().catch(D=>{fn("loadAt","play-rejected",{msg:String(D)})}),fn("loadAt","seek",{epochMs:u,media0Ms:I,offsetSec:O})};x.readyState>=HTMLMediaElement.HAVE_METADATA?A():x.addEventListener("loadedmetadata",A,{once:!0}),fn("loadAt","src-set",{src:C.playbackUrl})}catch(C){fn("loadAt","error",{msg:C instanceof Error?C.message:String(C)}),Qa({type:"state",state:"error",message:C instanceof Error?C.message:String(C)})}},[e,t.deviceId]);return T.useEffect(()=>{fn("init","mounted",{deviceId:t.deviceId,startMs:t.startMs??null,ua:navigator.userAgent});const u=(x,w)=>{fn("scrub","unavailable",{command:x,...w===void 0?{}:{epochMs:w}}),Qa({type:"state",state:"error",message:Ffe})};return window.__camstackRecording={seekTo:x=>{fn("cmd","seekTo",{epochMs:x}),h(x)},play:()=>{fn("cmd","play"),n.current?.play().catch(()=>{})},pause:()=>{fn("cmd","pause"),n.current?.pause()},setRate:x=>{fn("cmd","setRate",{rate:x}),n.current&&(n.current.playbackRate=x)},fit:(x,w)=>{fn("cmd","fit",{w:x,h:w}),m({w:x,h:w})},scrubStart:()=>{fn("cmd","scrubStart"),u("scrubStart")},scrubTo:x=>{fn("cmd","scrubTo",{epochMs:x}),u("scrubTo",x)},scrubEnd:x=>{fn("cmd","scrubEnd",{epochMs:x}),u("scrubEnd",x)}},t.startMs&&t.startMs>0&&h(t.startMs),()=>{window.__camstackRecording&&delete window.__camstackRecording}},[h,t.startMs,t.deviceId]),T.useEffect(()=>hu(u=>{const x=window.__camstackRecording;if(!x)return;switch(u.kind){case"seekTo":x.seekTo(u.value);break;case"play":x.play();break;case"pause":x.pause();break;case"setRate":x.setRate(u.value);break;case"scrubStart":x.scrubStart();break;case"scrubTo":x.scrubTo(u.value);break;case"scrubEnd":x.scrubEnd(u.value);break;case"fit":x.fit(u.w,u.h);break}}),[]),v.jsx("div",{style:{position:"fixed",left:0,top:0,width:f.w,height:f.h,background:"#000"},children:v.jsx("video",{ref:n,playsInline:!0,controls:!1,style:{width:"100%",height:"100%",objectFit:"contain",background:"#000"},onLoadedMetadata:u=>fn("video","loadedmetadata",{w:u.currentTarget.videoWidth,h:u.currentTarget.videoHeight,dur:u.currentTarget.duration}),onPlaying:()=>{fn("video","playing",{vodStartMs:Math.round(performance.now()-o.current)}),Qa({type:"state",state:"playing"})},onPause:()=>Qa({type:"state",state:"paused"}),onEnded:()=>Qa({type:"state",state:"ended"}),onError:u=>{const x=u.currentTarget.error;fn("video","error",{code:x?.code??null,message:x?.message??null}),Qa({type:"state",state:"error",message:x?.message||"video error"})},onTimeUpdate:u=>Qa({type:"position",positionMs:a.current+u.currentTarget.currentTime*1e3})})})}function $fe(){const e=Tm("recording",()=>window.__CAMSTACK_RECORDING__,Bfe),t=T.useMemo(()=>e===null||!e.ok?null:(document.cookie=`camstack_session=${e.config.token}; path=/; SameSite=Lax`,bm({serverUrl:e.config.serverUrl,token:e.config.token})),[e]);return T.useEffect(()=>()=>t?.close(),[t]),e===null?null:e.ok?t?v.jsx(Hfe,{system:t,config:e.config}):(Qa({type:"state",state:"error",message:"init failed"}),null):(Qa({type:"state",state:"error",message:e.error}),null)}function Qfe(){const e=window.__CAMSTACK_EMBED_MODE__??new URLSearchParams(location.search).get("mode")??"grid";return e==="player"?v.jsx(Lfe,{}):e==="recording"?v.jsx($fe,{}):e==="events"?v.jsx(ppe,{}):v.jsx(cfe,{})}const NA=document.getElementById("root");NA&&qj.createRoot(NA).render(v.jsx(Qfe,{}));export{Iee as C,Bee as E,GT as I,Jfe as M,cte as R,du as S,lhe as T,ehe as W,Dte as a,uhe as b,K as c,Mte as d,To as e,che as f,she as g,ohe as h,the as i,v as j,ihe as k,qg as l,Yy as m,jj as n,Tj as o,kn as p,T as r,rhe as s,mu as u,kp as v};