livedesk 0.1.577 → 0.1.579

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,190 +0,0 @@
1
- import{r as Lk,a as d,M as am,S as Ea,R as vu,B as Pk,P as Vp,X as vr,b as fm,C as tl,F as jb,L as el,A as d0,c as _k,d as Db,E as Ib,T as Ok,D as mm,e as tr,f as Fk,g as f0,h as Bk,i as Hk,j as mo,k as nr,l as ah,m as rm,n as rh,o as rc,p as m0,q as p0,s as h0,t as Lb,u as zk,v as $k,H as fu,W as bh,w as Uk,x as qk,y as Id,z as Ld,K as Wk,G as uv,I as lc,J as g0,N as v0,O as Gk,Q as Vk,U as Kk,V as $v,Y as Qk,Z as Uv,_ as y0,$ as Yk,a0 as ps,a1 as Pb,a2 as qv,a3 as wh,a4 as pm,a5 as sm,a6 as b0,a7 as Xk,a8 as w0,a9 as Zk,aa as x0,ab as Jk,ac as dv,ad as eM,ae as fv,af as S0,ag as tM,ah as nM,ai as aM,aj as rM,ak as C0,al as sM,am as _b,an as iM,ao as oM,ap as lM,aq as k0,ar as Yf,as as Kp,at as cM,au as uM,av as Ob,aw as wg,ax as dM,ay as xg,az as Fb,aA as Bb,aB as fM,aC as M0,aD as mM,aE as pM}from"./icons-B1iPMwM_.js";import{r as A0}from"./react-y9mBC96w.js";import{c as hM}from"./supabase-C7qjtLN3.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))s(l);new MutationObserver(l=>{for(const u of l)if(u.type==="childList")for(const f of u.addedNodes)f.tagName==="LINK"&&f.rel==="modulepreload"&&s(f)}).observe(document,{childList:!0,subtree:!0});function r(l){const u={};return l.integrity&&(u.integrity=l.integrity),l.referrerPolicy&&(u.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?u.credentials="include":l.crossOrigin==="anonymous"?u.credentials="omit":u.credentials="same-origin",u}function s(l){if(l.ep)return;l.ep=!0;const u=r(l);fetch(l.href,u)}})();var Sg={exports:{}},$f={};var Hb;function gM(){if(Hb)return $f;Hb=1;var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.fragment");function r(s,l,u){var f=null;if(u!==void 0&&(f=""+u),l.key!==void 0&&(f=""+l.key),"key"in l){u={};for(var h in l)h!=="key"&&(u[h]=l[h])}else u=l;return l=u.ref,{$$typeof:t,type:s,key:f,ref:l!==void 0?l:null,props:u}}return $f.Fragment=n,$f.jsx=r,$f.jsxs=r,$f}var zb;function vM(){return zb||(zb=1,Sg.exports=gM()),Sg.exports}var o=vM(),Cg={exports:{}},Uf={},kg={exports:{}},Mg={};var $b;function yM(){return $b||($b=1,(function(t){function n(U,L){var le=U.length;U.push(L);e:for(;0<le;){var ve=le-1>>>1,J=U[ve];if(0<l(J,L))U[ve]=L,U[le]=J,le=ve;else break e}}function r(U){return U.length===0?null:U[0]}function s(U){if(U.length===0)return null;var L=U[0],le=U.pop();if(le!==L){U[0]=le;e:for(var ve=0,J=U.length,Ae=J>>>1;ve<Ae;){var ce=2*(ve+1)-1,Te=U[ce],Fe=ce+1,$e=U[Fe];if(0>l(Te,le))Fe<J&&0>l($e,Te)?(U[ve]=$e,U[Fe]=le,ve=Fe):(U[ve]=Te,U[ce]=le,ve=ce);else if(Fe<J&&0>l($e,le))U[ve]=$e,U[Fe]=le,ve=Fe;else break e}}return L}function l(U,L){var le=U.sortIndex-L.sortIndex;return le!==0?le:U.id-L.id}if(t.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var u=performance;t.unstable_now=function(){return u.now()}}else{var f=Date,h=f.now();t.unstable_now=function(){return f.now()-h}}var g=[],y=[],w=1,b=null,S=3,k=!1,A=!1,T=!1,j=!1,I=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,P=typeof setImmediate<"u"?setImmediate:null;function H(U){for(var L=r(y);L!==null;){if(L.callback===null)s(y);else if(L.startTime<=U)s(y),L.sortIndex=L.expirationTime,n(g,L);else break;L=r(y)}}function F(U){if(T=!1,H(U),!A)if(r(g)!==null)A=!0,$||($=!0,Y());else{var L=r(y);L!==null&&ee(F,L.startTime-U)}}var $=!1,D=-1,K=5,z=-1;function q(){return j?!0:!(t.unstable_now()-z<K)}function W(){if(j=!1,$){var U=t.unstable_now();z=U;var L=!0;try{e:{A=!1,T&&(T=!1,N(D),D=-1),k=!0;var le=S;try{t:{for(H(U),b=r(g);b!==null&&!(b.expirationTime>U&&q());){var ve=b.callback;if(typeof ve=="function"){b.callback=null,S=b.priorityLevel;var J=ve(b.expirationTime<=U);if(U=t.unstable_now(),typeof J=="function"){b.callback=J,H(U),L=!0;break t}b===r(g)&&s(g),H(U)}else s(g);b=r(g)}if(b!==null)L=!0;else{var Ae=r(y);Ae!==null&&ee(F,Ae.startTime-U),L=!1}}break e}finally{b=null,S=le,k=!1}L=void 0}}finally{L?Y():$=!1}}}var Y;if(typeof P=="function")Y=function(){P(W)};else if(typeof MessageChannel<"u"){var V=new MessageChannel,he=V.port2;V.port1.onmessage=W,Y=function(){he.postMessage(null)}}else Y=function(){I(W,0)};function ee(U,L){D=I(function(){U(t.unstable_now())},L)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(U){U.callback=null},t.unstable_forceFrameRate=function(U){0>U||125<U?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):K=0<U?Math.floor(1e3/U):5},t.unstable_getCurrentPriorityLevel=function(){return S},t.unstable_next=function(U){switch(S){case 1:case 2:case 3:var L=3;break;default:L=S}var le=S;S=L;try{return U()}finally{S=le}},t.unstable_requestPaint=function(){j=!0},t.unstable_runWithPriority=function(U,L){switch(U){case 1:case 2:case 3:case 4:case 5:break;default:U=3}var le=S;S=U;try{return L()}finally{S=le}},t.unstable_scheduleCallback=function(U,L,le){var ve=t.unstable_now();switch(typeof le=="object"&&le!==null?(le=le.delay,le=typeof le=="number"&&0<le?ve+le:ve):le=ve,U){case 1:var J=-1;break;case 2:J=250;break;case 5:J=1073741823;break;case 4:J=1e4;break;default:J=5e3}return J=le+J,U={id:w++,callback:L,priorityLevel:U,startTime:le,expirationTime:J,sortIndex:-1},le>ve?(U.sortIndex=le,n(y,U),r(g)===null&&U===r(y)&&(T?(N(D),D=-1):T=!0,ee(F,le-ve))):(U.sortIndex=J,n(g,U),A||k||(A=!0,$||($=!0,Y()))),U},t.unstable_shouldYield=q,t.unstable_wrapCallback=function(U){var L=S;return function(){var le=S;S=L;try{return U.apply(this,arguments)}finally{S=le}}}})(Mg)),Mg}var Ub;function bM(){return Ub||(Ub=1,kg.exports=yM()),kg.exports}var qb;function wM(){if(qb)return Uf;qb=1;var t=bM(),n=Lk(),r=A0();function s(e){var a="https://react.dev/errors/"+e;if(1<arguments.length){a+="?args[]="+encodeURIComponent(arguments[1]);for(var i=2;i<arguments.length;i++)a+="&args[]="+encodeURIComponent(arguments[i])}return"Minified React error #"+e+"; visit "+a+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function l(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function u(e){var a=e,i=e;if(e.alternate)for(;a.return;)a=a.return;else{e=a;do a=e,(a.flags&4098)!==0&&(i=a.return),e=a.return;while(e)}return a.tag===3?i:null}function f(e){if(e.tag===13){var a=e.memoizedState;if(a===null&&(e=e.alternate,e!==null&&(a=e.memoizedState)),a!==null)return a.dehydrated}return null}function h(e){if(e.tag===31){var a=e.memoizedState;if(a===null&&(e=e.alternate,e!==null&&(a=e.memoizedState)),a!==null)return a.dehydrated}return null}function g(e){if(u(e)!==e)throw Error(s(188))}function y(e){var a=e.alternate;if(!a){if(a=u(e),a===null)throw Error(s(188));return a!==e?null:e}for(var i=e,c=a;;){var p=i.return;if(p===null)break;var v=p.alternate;if(v===null){if(c=p.return,c!==null){i=c;continue}break}if(p.child===v.child){for(v=p.child;v;){if(v===i)return g(p),e;if(v===c)return g(p),a;v=v.sibling}throw Error(s(188))}if(i.return!==c.return)i=p,c=v;else{for(var M=!1,_=p.child;_;){if(_===i){M=!0,i=p,c=v;break}if(_===c){M=!0,c=p,i=v;break}_=_.sibling}if(!M){for(_=v.child;_;){if(_===i){M=!0,i=v,c=p;break}if(_===c){M=!0,c=v,i=p;break}_=_.sibling}if(!M)throw Error(s(189))}}if(i.alternate!==c)throw Error(s(190))}if(i.tag!==3)throw Error(s(188));return i.stateNode.current===i?e:a}function w(e){var a=e.tag;if(a===5||a===26||a===27||a===6)return e;for(e=e.child;e!==null;){if(a=w(e),a!==null)return a;e=e.sibling}return null}var b=Object.assign,S=Symbol.for("react.element"),k=Symbol.for("react.transitional.element"),A=Symbol.for("react.portal"),T=Symbol.for("react.fragment"),j=Symbol.for("react.strict_mode"),I=Symbol.for("react.profiler"),N=Symbol.for("react.consumer"),P=Symbol.for("react.context"),H=Symbol.for("react.forward_ref"),F=Symbol.for("react.suspense"),$=Symbol.for("react.suspense_list"),D=Symbol.for("react.memo"),K=Symbol.for("react.lazy"),z=Symbol.for("react.activity"),q=Symbol.for("react.memo_cache_sentinel"),W=Symbol.iterator;function Y(e){return e===null||typeof e!="object"?null:(e=W&&e[W]||e["@@iterator"],typeof e=="function"?e:null)}var V=Symbol.for("react.client.reference");function he(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===V?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case T:return"Fragment";case I:return"Profiler";case j:return"StrictMode";case F:return"Suspense";case $:return"SuspenseList";case z:return"Activity"}if(typeof e=="object")switch(e.$$typeof){case A:return"Portal";case P:return e.displayName||"Context";case N:return(e._context.displayName||"Context")+".Consumer";case H:var a=e.render;return e=e.displayName,e||(e=a.displayName||a.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case D:return a=e.displayName||null,a!==null?a:he(e.type)||"Memo";case K:a=e._payload,e=e._init;try{return he(e(a))}catch{}}return null}var ee=Array.isArray,U=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,L=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,le={pending:!1,data:null,method:null,action:null},ve=[],J=-1;function Ae(e){return{current:e}}function ce(e){0>J||(e.current=ve[J],ve[J]=null,J--)}function Te(e,a){J++,ve[J]=e.current,e.current=a}var Fe=Ae(null),$e=Ae(null),Ze=Ae(null),de=Ae(null);function Be(e,a){switch(Te(Ze,a),Te($e,e),Te(Fe,null),a.nodeType){case 9:case 11:e=(e=a.documentElement)&&(e=e.namespaceURI)?eb(e):0;break;default:if(e=a.tagName,a=a.namespaceURI)a=eb(a),e=tb(a,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}ce(Fe),Te(Fe,e)}function Ve(){ce(Fe),ce($e),ce(Ze)}function Je(e){e.memoizedState!==null&&Te(de,e);var a=Fe.current,i=tb(a,e.type);a!==i&&(Te($e,e),Te(Fe,i))}function Qe(e){$e.current===e&&(ce(Fe),ce($e)),de.current===e&&(ce(de),Ff._currentValue=le)}var yt,ne;function me(e){if(yt===void 0)try{throw Error()}catch(i){var a=i.stack.trim().match(/\n( *(at )?)/);yt=a&&a[1]||"",ne=-1<i.stack.indexOf(`
2
- at`)?" (<anonymous>)":-1<i.stack.indexOf("@")?"@unknown:0:0":""}return`
3
- `+yt+e+ne}var Ge=!1;function Se(e,a){if(!e||Ge)return"";Ge=!0;var i=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var c={DetermineComponentFrameRoot:function(){try{if(a){var _e=function(){throw Error()};if(Object.defineProperty(_e.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(_e,[])}catch(ke){var xe=ke}Reflect.construct(e,[],_e)}else{try{_e.call()}catch(ke){xe=ke}e.call(_e.prototype)}}else{try{throw Error()}catch(ke){xe=ke}(_e=e())&&typeof _e.catch=="function"&&_e.catch(function(){})}}catch(ke){if(ke&&xe&&typeof ke.stack=="string")return[ke.stack,xe.stack]}return[null,null]}};c.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var p=Object.getOwnPropertyDescriptor(c.DetermineComponentFrameRoot,"name");p&&p.configurable&&Object.defineProperty(c.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var v=c.DetermineComponentFrameRoot(),M=v[0],_=v[1];if(M&&_){var Z=M.split(`
4
- `),we=_.split(`
5
- `);for(p=c=0;c<Z.length&&!Z[c].includes("DetermineComponentFrameRoot");)c++;for(;p<we.length&&!we[p].includes("DetermineComponentFrameRoot");)p++;if(c===Z.length||p===we.length)for(c=Z.length-1,p=we.length-1;1<=c&&0<=p&&Z[c]!==we[p];)p--;for(;1<=c&&0<=p;c--,p--)if(Z[c]!==we[p]){if(c!==1||p!==1)do if(c--,p--,0>p||Z[c]!==we[p]){var Re=`
6
- `+Z[c].replace(" at new "," at ");return e.displayName&&Re.includes("<anonymous>")&&(Re=Re.replace("<anonymous>",e.displayName)),Re}while(1<=c&&0<=p);break}}}finally{Ge=!1,Error.prepareStackTrace=i}return(i=e?e.displayName||e.name:"")?me(i):""}function ge(e,a){switch(e.tag){case 26:case 27:case 5:return me(e.type);case 16:return me("Lazy");case 13:return e.child!==a&&a!==null?me("Suspense Fallback"):me("Suspense");case 19:return me("SuspenseList");case 0:case 15:return Se(e.type,!1);case 11:return Se(e.type.render,!1);case 1:return Se(e.type,!0);case 31:return me("Activity");default:return""}}function Ue(e){try{var a="",i=null;do a+=ge(e,i),i=e,e=e.return;while(e);return a}catch(c){return`
7
- Error generating stack: `+c.message+`
8
- `+c.stack}}var Me=Object.prototype.hasOwnProperty,rt=t.unstable_scheduleCallback,At=t.unstable_cancelCallback,O=t.unstable_shouldYield,qe=t.unstable_requestPaint,B=t.unstable_now,Oe=t.unstable_getCurrentPriorityLevel,We=t.unstable_ImmediatePriority,et=t.unstable_UserBlockingPriority,it=t.unstable_NormalPriority,ye=t.unstable_LowPriority,Ne=t.unstable_IdlePriority,He=t.log,pe=t.unstable_setDisableYieldValue,ae=null,fe=null;function Ee(e){if(typeof He=="function"&&pe(e),fe&&typeof fe.setStrictMode=="function")try{fe.setStrictMode(ae,e)}catch{}}var je=Math.clz32?Math.clz32:at,De=Math.log,Et=Math.LN2;function at(e){return e>>>=0,e===0?32:31-(De(e)/Et|0)|0}var ft=256,jt=262144,Ut=4194304;function wt(e){var a=e&42;if(a!==0)return a;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function Wt(e,a,i){var c=e.pendingLanes;if(c===0)return 0;var p=0,v=e.suspendedLanes,M=e.pingedLanes;e=e.warmLanes;var _=c&134217727;return _!==0?(c=_&~v,c!==0?p=wt(c):(M&=_,M!==0?p=wt(M):i||(i=_&~e,i!==0&&(p=wt(i))))):(_=c&~v,_!==0?p=wt(_):M!==0?p=wt(M):i||(i=c&~e,i!==0&&(p=wt(i)))),p===0?0:a!==0&&a!==p&&(a&v)===0&&(v=p&-p,i=a&-a,v>=i||v===32&&(i&4194048)!==0)?a:p}function gt(e,a){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&a)===0}function yn(e,a){switch(e){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function mt(){var e=Ut;return Ut<<=1,(Ut&62914560)===0&&(Ut=4194304),e}function ha(e){for(var a=[],i=0;31>i;i++)a.push(e);return a}function hn(e,a){e.pendingLanes|=a,a!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function na(e,a,i,c,p,v){var M=e.pendingLanes;e.pendingLanes=i,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=i,e.entangledLanes&=i,e.errorRecoveryDisabledLanes&=i,e.shellSuspendCounter=0;var _=e.entanglements,Z=e.expirationTimes,we=e.hiddenUpdates;for(i=M&~i;0<i;){var Re=31-je(i),_e=1<<Re;_[Re]=0,Z[Re]=-1;var xe=we[Re];if(xe!==null)for(we[Re]=null,Re=0;Re<xe.length;Re++){var ke=xe[Re];ke!==null&&(ke.lane&=-536870913)}i&=~_e}c!==0&&za(e,c,0),v!==0&&p===0&&e.tag!==0&&(e.suspendedLanes|=v&~(M&~a))}function za(e,a,i){e.pendingLanes|=a,e.suspendedLanes&=~a;var c=31-je(a);e.entangledLanes|=a,e.entanglements[c]=e.entanglements[c]|1073741824|i&261930}function G(e,a){var i=e.entangledLanes|=a;for(e=e.entanglements;i;){var c=31-je(i),p=1<<c;p&a|e[c]&a&&(e[c]|=a),i&=~p}}function ot(e,a){var i=a&-a;return i=(i&42)!==0?1:Pt(i),(i&(e.suspendedLanes|a))!==0?0:i}function Pt(e){switch(e){case 2:e=1;break;case 8:e=4;break;case 32:e=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:e=128;break;case 268435456:e=134217728;break;default:e=0}return e}function an(e){return e&=-e,2<e?8<e?(e&134217727)!==0?32:268435456:8:2}function Dr(){var e=L.p;return e!==0?e:(e=window.event,e===void 0?32:kb(e.type))}function _t(e,a){var i=L.p;try{return L.p=e,a()}finally{L.p=i}}var vn=Math.random().toString(36).slice(2),se="__reactFiber$"+vn,ze="__reactProps$"+vn,st="__reactContainer$"+vn,Lt="__reactEvents$"+vn,Sn="__reactListeners$"+vn,on="__reactHandles$"+vn,xt="__reactResources$"+vn,Jt="__reactMarker$"+vn;function In(e){delete e[se],delete e[ze],delete e[Lt],delete e[Sn],delete e[on]}function zn(e){var a=e[se];if(a)return a;for(var i=e.parentNode;i;){if(a=i[st]||i[se]){if(i=a.alternate,a.child!==null||i!==null&&i.child!==null)for(e=lb(e);e!==null;){if(i=e[se])return i;e=lb(e)}return a}e=i,i=e.parentNode}return null}function Cn(e){if(e=e[se]||e[st]){var a=e.tag;if(a===5||a===6||a===13||a===31||a===26||a===27||a===3)return e}return null}function bn(e){var a=e.tag;if(a===5||a===26||a===27||a===6)return e.stateNode;throw Error(s(33))}function kn(e){var a=e[xt];return a||(a=e[xt]={hoistableStyles:new Map,hoistableScripts:new Map}),a}function Ce(e){e[Jt]=!0}var Ln=new Set,En={};function $n(e,a){Un(e,a),Un(e+"Capture",a)}function Un(e,a){for(En[e]=a,e=0;e<a.length;e++)Ln.add(a[e])}var go=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"),jn={},ri={};function vo(e){return Me.call(ri,e)?!0:Me.call(jn,e)?!1:go.test(e)?ri[e]=!0:(jn[e]=!0,!1)}function si(e,a,i){if(vo(a))if(i===null)e.removeAttribute(a);else{switch(typeof i){case"undefined":case"function":case"symbol":e.removeAttribute(a);return;case"boolean":var c=a.toLowerCase().slice(0,5);if(c!=="data-"&&c!=="aria-"){e.removeAttribute(a);return}}e.setAttribute(a,""+i)}}function Ri(e,a,i){if(i===null)e.removeAttribute(a);else{switch(typeof i){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(a);return}e.setAttribute(a,""+i)}}function yr(e,a,i,c){if(c===null)e.removeAttribute(i);else{switch(typeof c){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(i);return}e.setAttributeNS(a,i,""+c)}}function Da(e){switch(typeof e){case"bigint":case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function vs(e){var a=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(a==="checkbox"||a==="radio")}function br(e,a,i){var c=Object.getOwnPropertyDescriptor(e.constructor.prototype,a);if(!e.hasOwnProperty(a)&&typeof c<"u"&&typeof c.get=="function"&&typeof c.set=="function"){var p=c.get,v=c.set;return Object.defineProperty(e,a,{configurable:!0,get:function(){return p.call(this)},set:function(M){i=""+M,v.call(this,M)}}),Object.defineProperty(e,a,{enumerable:c.enumerable}),{getValue:function(){return i},setValue:function(M){i=""+M},stopTracking:function(){e._valueTracker=null,delete e[a]}}}}function _s(e){if(!e._valueTracker){var a=vs(e)?"checked":"value";e._valueTracker=br(e,a,""+e[a])}}function ii(e){if(!e)return!1;var a=e._valueTracker;if(!a)return!0;var i=a.getValue(),c="";return e&&(c=vs(e)?e.checked?"true":"false":e.value),e=c,e!==i?(a.setValue(e),!0):!1}function ln(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}var Ei=/[\n"\\]/g;function nn(e){return e.replace(Ei,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function oi(e,a,i,c,p,v,M,_){e.name="",M!=null&&typeof M!="function"&&typeof M!="symbol"&&typeof M!="boolean"?e.type=M:e.removeAttribute("type"),a!=null?M==="number"?(a===0&&e.value===""||e.value!=a)&&(e.value=""+Da(a)):e.value!==""+Da(a)&&(e.value=""+Da(a)):M!=="submit"&&M!=="reset"||e.removeAttribute("value"),a!=null?Os(e,M,Da(a)):i!=null?Os(e,M,Da(i)):c!=null&&e.removeAttribute("value"),p==null&&v!=null&&(e.defaultChecked=!!v),p!=null&&(e.checked=p&&typeof p!="function"&&typeof p!="symbol"),_!=null&&typeof _!="function"&&typeof _!="symbol"&&typeof _!="boolean"?e.name=""+Da(_):e.removeAttribute("name")}function wr(e,a,i,c,p,v,M,_){if(v!=null&&typeof v!="function"&&typeof v!="symbol"&&typeof v!="boolean"&&(e.type=v),a!=null||i!=null){if(!(v!=="submit"&&v!=="reset"||a!=null)){_s(e);return}i=i!=null?""+Da(i):"",a=a!=null?""+Da(a):i,_||a===e.value||(e.value=a),e.defaultValue=a}c=c??p,c=typeof c!="function"&&typeof c!="symbol"&&!!c,e.checked=_?e.checked:!!c,e.defaultChecked=!!c,M!=null&&typeof M!="function"&&typeof M!="symbol"&&typeof M!="boolean"&&(e.name=M),_s(e)}function Os(e,a,i){a==="number"&&ln(e.ownerDocument)===e||e.defaultValue===""+i||(e.defaultValue=""+i)}function xr(e,a,i,c){if(e=e.options,a){a={};for(var p=0;p<i.length;p++)a["$"+i[p]]=!0;for(i=0;i<e.length;i++)p=a.hasOwnProperty("$"+e[i].value),e[i].selected!==p&&(e[i].selected=p),p&&c&&(e[i].defaultSelected=!0)}else{for(i=""+Da(i),a=null,p=0;p<e.length;p++){if(e[p].value===i){e[p].selected=!0,c&&(e[p].defaultSelected=!0);return}a!==null||e[p].disabled||(a=e[p])}a!==null&&(a.selected=!0)}}function Fs(e,a,i){if(a!=null&&(a=""+Da(a),a!==e.value&&(e.value=a),i==null)){e.defaultValue!==a&&(e.defaultValue=a);return}e.defaultValue=i!=null?""+Da(i):""}function rl(e,a,i,c){if(a==null){if(c!=null){if(i!=null)throw Error(s(92));if(ee(c)){if(1<c.length)throw Error(s(93));c=c[0]}i=c}i==null&&(i=""),a=i}i=Da(a),e.defaultValue=i,c=e.textContent,c===i&&c!==""&&c!==null&&(e.value=c),_s(e)}function qr(e,a){if(a){var i=e.firstChild;if(i&&i===e.lastChild&&i.nodeType===3){i.nodeValue=a;return}}e.textContent=a}var Ir=new Set("animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(" "));function Bs(e,a,i){var c=a.indexOf("--")===0;i==null||typeof i=="boolean"||i===""?c?e.setProperty(a,""):a==="float"?e.cssFloat="":e[a]="":c?e.setProperty(a,i):typeof i!="number"||i===0||Ir.has(a)?a==="float"?e.cssFloat=i:e[a]=(""+i).trim():e[a]=i+"px"}function hc(e,a,i){if(a!=null&&typeof a!="object")throw Error(s(62));if(e=e.style,i!=null){for(var c in i)!i.hasOwnProperty(c)||a!=null&&a.hasOwnProperty(c)||(c.indexOf("--")===0?e.setProperty(c,""):c==="float"?e.cssFloat="":e[c]="");for(var p in a)c=a[p],a.hasOwnProperty(p)&&i[p]!==c&&Bs(e,p,c)}else for(var v in a)a.hasOwnProperty(v)&&Bs(e,v,a[v])}function Wr(e){if(e.indexOf("-")===-1)return!1;switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var gc=new Map([["acceptCharset","accept-charset"],["htmlFor","for"],["httpEquiv","http-equiv"],["crossOrigin","crossorigin"],["accentHeight","accent-height"],["alignmentBaseline","alignment-baseline"],["arabicForm","arabic-form"],["baselineShift","baseline-shift"],["capHeight","cap-height"],["clipPath","clip-path"],["clipRule","clip-rule"],["colorInterpolation","color-interpolation"],["colorInterpolationFilters","color-interpolation-filters"],["colorProfile","color-profile"],["colorRendering","color-rendering"],["dominantBaseline","dominant-baseline"],["enableBackground","enable-background"],["fillOpacity","fill-opacity"],["fillRule","fill-rule"],["floodColor","flood-color"],["floodOpacity","flood-opacity"],["fontFamily","font-family"],["fontSize","font-size"],["fontSizeAdjust","font-size-adjust"],["fontStretch","font-stretch"],["fontStyle","font-style"],["fontVariant","font-variant"],["fontWeight","font-weight"],["glyphName","glyph-name"],["glyphOrientationHorizontal","glyph-orientation-horizontal"],["glyphOrientationVertical","glyph-orientation-vertical"],["horizAdvX","horiz-adv-x"],["horizOriginX","horiz-origin-x"],["imageRendering","image-rendering"],["letterSpacing","letter-spacing"],["lightingColor","lighting-color"],["markerEnd","marker-end"],["markerMid","marker-mid"],["markerStart","marker-start"],["overlinePosition","overline-position"],["overlineThickness","overline-thickness"],["paintOrder","paint-order"],["panose-1","panose-1"],["pointerEvents","pointer-events"],["renderingIntent","rendering-intent"],["shapeRendering","shape-rendering"],["stopColor","stop-color"],["stopOpacity","stop-opacity"],["strikethroughPosition","strikethrough-position"],["strikethroughThickness","strikethrough-thickness"],["strokeDasharray","stroke-dasharray"],["strokeDashoffset","stroke-dashoffset"],["strokeLinecap","stroke-linecap"],["strokeLinejoin","stroke-linejoin"],["strokeMiterlimit","stroke-miterlimit"],["strokeOpacity","stroke-opacity"],["strokeWidth","stroke-width"],["textAnchor","text-anchor"],["textDecoration","text-decoration"],["textRendering","text-rendering"],["transformOrigin","transform-origin"],["underlinePosition","underline-position"],["underlineThickness","underline-thickness"],["unicodeBidi","unicode-bidi"],["unicodeRange","unicode-range"],["unitsPerEm","units-per-em"],["vAlphabetic","v-alphabetic"],["vHanging","v-hanging"],["vIdeographic","v-ideographic"],["vMathematical","v-mathematical"],["vectorEffect","vector-effect"],["vertAdvY","vert-adv-y"],["vertOriginX","vert-origin-x"],["vertOriginY","vert-origin-y"],["wordSpacing","word-spacing"],["writingMode","writing-mode"],["xmlnsXlink","xmlns:xlink"],["xHeight","x-height"]]),yo=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;function Lr(e){return yo.test(""+e)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":e}function ys(){}var Cu=null;function bs(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Hs=null,Ct=null;function sl(e){var a=Cn(e);if(a&&(e=a.stateNode)){var i=e[ze]||null;e:switch(e=a.stateNode,a.type){case"input":if(oi(e,i.value,i.defaultValue,i.defaultValue,i.checked,i.defaultChecked,i.type,i.name),a=i.name,i.type==="radio"&&a!=null){for(i=e;i.parentNode;)i=i.parentNode;for(i=i.querySelectorAll('input[name="'+nn(""+a)+'"][type="radio"]'),a=0;a<i.length;a++){var c=i[a];if(c!==e&&c.form===e.form){var p=c[ze]||null;if(!p)throw Error(s(90));oi(c,p.value,p.defaultValue,p.defaultValue,p.checked,p.defaultChecked,p.type,p.name)}}for(a=0;a<i.length;a++)c=i[a],c.form===e.form&&ii(c)}break e;case"textarea":Fs(e,i.value,i.defaultValue);break e;case"select":a=i.value,a!=null&&xr(e,!!i.multiple,a,!1)}}}var Kn=!1;function bo(e,a,i){if(Kn)return e(a,i);Kn=!0;try{var c=e(a);return c}finally{if(Kn=!1,(Hs!==null||Ct!==null)&&(tp(),Hs&&(a=Hs,e=Ct,Ct=Hs=null,sl(a),e)))for(a=0;a<e.length;a++)sl(e[a])}}function Kt(e,a){var i=e.stateNode;if(i===null)return null;var c=i[ze]||null;if(c===null)return null;i=c[a];e:switch(a){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(c=!c.disabled)||(e=e.type,c=!(e==="button"||e==="input"||e==="select"||e==="textarea")),e=!c;break e;default:e=!1}if(e)return null;if(i&&typeof i!="function")throw Error(s(231,a,typeof i));return i}var $a=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),wo=!1;if($a)try{var Gr={};Object.defineProperty(Gr,"passive",{get:function(){wo=!0}}),window.addEventListener("test",Gr,Gr),window.removeEventListener("test",Gr,Gr)}catch{wo=!1}var Vr=null,$t=null,Ua=null;function Pr(){if(Ua)return Ua;var e,a=$t,i=a.length,c,p="value"in Vr?Vr.value:Vr.textContent,v=p.length;for(e=0;e<i&&a[e]===p[e];e++);var M=i-e;for(c=1;c<=M&&a[i-c]===p[v-c];c++);return Ua=p.slice(e,1<c?1-c:void 0)}function ji(e){var a=e.keyCode;return"charCode"in e?(e=e.charCode,e===0&&a===13&&(e=13)):e=a,e===10&&(e=13),32<=e||e===13?e:0}function Di(){return!0}function il(){return!1}function Pn(e){function a(i,c,p,v,M){this._reactName=i,this._targetInst=p,this.type=c,this.nativeEvent=v,this.target=M,this.currentTarget=null;for(var _ in e)e.hasOwnProperty(_)&&(i=e[_],this[_]=i?i(v):v[_]);return this.isDefaultPrevented=(v.defaultPrevented!=null?v.defaultPrevented:v.returnValue===!1)?Di:il,this.isPropagationStopped=il,this}return b(a.prototype,{preventDefault:function(){this.defaultPrevented=!0;var i=this.nativeEvent;i&&(i.preventDefault?i.preventDefault():typeof i.returnValue!="unknown"&&(i.returnValue=!1),this.isDefaultPrevented=Di)},stopPropagation:function(){var i=this.nativeEvent;i&&(i.stopPropagation?i.stopPropagation():typeof i.cancelBubble!="unknown"&&(i.cancelBubble=!0),this.isPropagationStopped=Di)},persist:function(){},isPersistent:Di}),a}var Qn={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},li=Pn(Qn),Kr=b({},Qn,{view:0,detail:0}),ku=Pn(Kr),ol,vc,xo,Ii=b({},Kr,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:cl,button:0,buttons:0,relatedTarget:function(e){return e.relatedTarget===void 0?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==xo&&(xo&&e.type==="mousemove"?(ol=e.screenX-xo.screenX,vc=e.screenY-xo.screenY):vc=ol=0,xo=e),ol)},movementY:function(e){return"movementY"in e?e.movementY:vc}}),yc=Pn(Ii),Li=b({},Ii,{dataTransfer:0}),$d=Pn(Li),bc=b({},Kr,{relatedTarget:0}),gn=Pn(bc),ir=b({},Qn,{animationName:0,elapsedTime:0,pseudoElement:0}),ci=Pn(ir),qn=b({},Qn,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),So=Pn(qn),Co=b({},Qn,{data:0}),zs=Pn(Co),Pi={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},ll={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},ko={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function $s(e){var a=this.nativeEvent;return a.getModifierState?a.getModifierState(e):(e=ko[e])?!!a[e]:!1}function cl(){return $s}var Mu=b({},Kr,{key:function(e){if(e.key){var a=Pi[e.key]||e.key;if(a!=="Unidentified")return a}return e.type==="keypress"?(e=ji(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?ll[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:cl,charCode:function(e){return e.type==="keypress"?ji(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?ji(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),_i=Pn(Mu),Sr=b({},Ii,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Ud=Pn(Sr),Au=b({},Kr,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:cl}),ul=Pn(Au),_r=b({},Qn,{propertyName:0,elapsedTime:0,pseudoElement:0}),wc=Pn(_r),qa=b({},Ii,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0}),dl=Pn(qa),xc=b({},Qn,{newState:0,oldState:0}),ui=Pn(xc),Tu=[9,13,27,32],fl=$a&&"CompositionEvent"in window,Mo=null;$a&&"documentMode"in document&&(Mo=document.documentMode);var km=$a&&"TextEvent"in window&&!Mo,Sc=$a&&(!fl||Mo&&8<Mo&&11>=Mo),Nu=" ",di=!1;function Cc(e,a){switch(e){case"keyup":return Tu.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function kc(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var fi=!1;function qd(e,a){switch(e){case"compositionend":return kc(a);case"keypress":return a.which!==32?null:(di=!0,Nu);case"textInput":return e=a.data,e===Nu&&di?null:e;default:return null}}function or(e,a){if(fi)return e==="compositionend"||!fl&&Cc(e,a)?(e=Pr(),Ua=$t=Vr=null,fi=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1<a.char.length)return a.char;if(a.which)return String.fromCharCode(a.which)}return null;case"compositionend":return Sc&&a.locale!=="ko"?null:a.data;default:return null}}var Ru={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function Mm(e){var a=e&&e.nodeName&&e.nodeName.toLowerCase();return a==="input"?!!Ru[e.type]:a==="textarea"}function Us(e,a,i,c){Hs?Ct?Ct.push(c):Ct=[c]:Hs=c,a=lp(a,"onChange"),0<a.length&&(i=new li("onChange","change",null,i,c),e.push({event:i,listeners:a}))}var ml=null,lr=null;function Qr(e){Ky(e,0)}function Wa(e){var a=bn(e);if(ii(a))return e}function pl(e,a){if(e==="change")return a}var Wd=!1;if($a){var Wn;if($a){var ga="oninput"in document;if(!ga){var Gd=document.createElement("div");Gd.setAttribute("oninput","return;"),ga=typeof Gd.oninput=="function"}Wn=ga}else Wn=!1;Wd=Wn&&(!document.documentMode||9<document.documentMode)}function Ao(){ml&&(ml.detachEvent("onpropertychange",Rt),lr=ml=null)}function Rt(e){if(e.propertyName==="value"&&Wa(lr)){var a=[];Us(a,lr,e,bs(e)),bo(Qr,a)}}function Yr(e,a,i){e==="focusin"?(Ao(),ml=a,lr=i,ml.attachEvent("onpropertychange",Rt)):e==="focusout"&&Ao()}function To(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return Wa(lr)}function hl(e,a){if(e==="click")return Wa(a)}function Mc(e,a){if(e==="input"||e==="change")return Wa(a)}function Oi(e,a){return e===a&&(e!==0||1/e===1/a)||e!==e&&a!==a}var la=typeof Object.is=="function"?Object.is:Oi;function Fi(e,a){if(la(e,a))return!0;if(typeof e!="object"||e===null||typeof a!="object"||a===null)return!1;var i=Object.keys(e),c=Object.keys(a);if(i.length!==c.length)return!1;for(c=0;c<i.length;c++){var p=i[c];if(!Me.call(a,p)||!la(e[p],a[p]))return!1}return!0}function No(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function ws(e,a){var i=No(e);e=0;for(var c;i;){if(i.nodeType===3){if(c=e+i.textContent.length,e<=a&&c>=a)return{node:i,offset:a-e};e=c}e:{for(;i;){if(i.nextSibling){i=i.nextSibling;break e}i=i.parentNode}i=void 0}i=No(i)}}function Bi(e,a){return e&&a?e===a?!0:e&&e.nodeType===3?!1:a&&a.nodeType===3?Bi(e,a.parentNode):"contains"in e?e.contains(a):e.compareDocumentPosition?!!(e.compareDocumentPosition(a)&16):!1:!1}function Hi(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var a=ln(e.document);a instanceof e.HTMLIFrameElement;){try{var i=typeof a.contentWindow.location.href=="string"}catch{i=!1}if(i)e=a.contentWindow;else break;a=ln(e.document)}return a}function zi(e){var a=e&&e.nodeName&&e.nodeName.toLowerCase();return a&&(a==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||a==="textarea"||e.contentEditable==="true")}var Ro=$a&&"documentMode"in document&&11>=document.documentMode,Ga=null,Xr=null,Eo=null,Ia=!1;function Am(e,a,i){var c=i.window===i?i.document:i.nodeType===9?i:i.ownerDocument;Ia||Ga==null||Ga!==ln(c)||(c=Ga,"selectionStart"in c&&zi(c)?c={start:c.selectionStart,end:c.selectionEnd}:(c=(c.ownerDocument&&c.ownerDocument.defaultView||window).getSelection(),c={anchorNode:c.anchorNode,anchorOffset:c.anchorOffset,focusNode:c.focusNode,focusOffset:c.focusOffset}),Eo&&Fi(Eo,c)||(Eo=c,c=lp(Xr,"onSelect"),0<c.length&&(a=new li("onSelect","select",null,a,i),e.push({event:a,listeners:c}),a.target=Ga)))}function Zr(e,a){var i={};return i[e.toLowerCase()]=a.toLowerCase(),i["Webkit"+e]="webkit"+a,i["Moz"+e]="moz"+a,i}var gl={animationend:Zr("Animation","AnimationEnd"),animationiteration:Zr("Animation","AnimationIteration"),animationstart:Zr("Animation","AnimationStart"),transitionrun:Zr("Transition","TransitionRun"),transitionstart:Zr("Transition","TransitionStart"),transitioncancel:Zr("Transition","TransitionCancel"),transitionend:Zr("Transition","TransitionEnd")},jo={},Ac={};$a&&(Ac=document.createElement("div").style,"AnimationEvent"in window||(delete gl.animationend.animation,delete gl.animationiteration.animation,delete gl.animationstart.animation),"TransitionEvent"in window||delete gl.transitionend.transition);function qs(e){if(jo[e])return jo[e];if(!gl[e])return e;var a=gl[e],i;for(i in a)if(a.hasOwnProperty(i)&&i in Ac)return jo[e]=a[i];return e}var Tc=qs("animationend"),Eu=qs("animationiteration"),ju=qs("animationstart"),Nc=qs("transitionrun"),Tm=qs("transitionstart"),Nm=qs("transitioncancel"),Ws=qs("transitionend"),Rc=new Map,$i="abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");$i.push("scrollEnd");function Va(e,a){Rc.set(e,a),$n(a,[e])}var Gs=typeof reportError=="function"?reportError:function(e){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var a=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof e=="object"&&e!==null&&typeof e.message=="string"?String(e.message):String(e),error:e});if(!window.dispatchEvent(a))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",e);return}console.error(e)},cn=[],xs=0,Du=0;function va(){for(var e=xs,a=Du=xs=0;a<e;){var i=cn[a];cn[a++]=null;var c=cn[a];cn[a++]=null;var p=cn[a];cn[a++]=null;var v=cn[a];if(cn[a++]=null,c!==null&&p!==null){var M=c.pending;M===null?p.next=p:(p.next=M.next,M.next=p),c.pending=p}v!==0&&Ui(i,p,v)}}function ya(e,a,i,c){cn[xs++]=e,cn[xs++]=a,cn[xs++]=i,cn[xs++]=c,Du|=c,e.lanes|=c,e=e.alternate,e!==null&&(e.lanes|=c)}function Iu(e,a,i,c){return ya(e,a,i,c),Ss(e)}function _n(e,a){return ya(e,null,null,a),Ss(e)}function Ui(e,a,i){e.lanes|=i;var c=e.alternate;c!==null&&(c.lanes|=i);for(var p=!1,v=e.return;v!==null;)v.childLanes|=i,c=v.alternate,c!==null&&(c.childLanes|=i),v.tag===22&&(e=v.stateNode,e===null||e._visibility&1||(p=!0)),e=v,v=v.return;return e.tag===3?(v=e.stateNode,p&&a!==null&&(p=31-je(i),e=v.hiddenUpdates,c=e[p],c===null?e[p]=[a]:c.push(a),a.lane=i|536870912),v):null}function Ss(e){if(50<jf)throw jf=0,qh=null,Error(s(185));for(var a=e.return;a!==null;)e=a,a=e.return;return e.tag===3?e.stateNode:null}var vl={};function Vd(e,a,i,c){this.tag=e,this.key=i,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=a,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=c,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Jr(e,a,i,c){return new Vd(e,a,i,c)}function Kd(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Cr(e,a){var i=e.alternate;return i===null?(i=Jr(e.tag,a,e.key,e.mode),i.elementType=e.elementType,i.type=e.type,i.stateNode=e.stateNode,i.alternate=e,e.alternate=i):(i.pendingProps=a,i.type=e.type,i.flags=0,i.subtreeFlags=0,i.deletions=null),i.flags=e.flags&65011712,i.childLanes=e.childLanes,i.lanes=e.lanes,i.child=e.child,i.memoizedProps=e.memoizedProps,i.memoizedState=e.memoizedState,i.updateQueue=e.updateQueue,a=e.dependencies,i.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext},i.sibling=e.sibling,i.index=e.index,i.ref=e.ref,i.refCleanup=e.refCleanup,i}function Rm(e,a){e.flags&=65011714;var i=e.alternate;return i===null?(e.childLanes=0,e.lanes=a,e.child=null,e.subtreeFlags=0,e.memoizedProps=null,e.memoizedState=null,e.updateQueue=null,e.dependencies=null,e.stateNode=null):(e.childLanes=i.childLanes,e.lanes=i.lanes,e.child=i.child,e.subtreeFlags=0,e.deletions=null,e.memoizedProps=i.memoizedProps,e.memoizedState=i.memoizedState,e.updateQueue=i.updateQueue,e.type=i.type,a=i.dependencies,e.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext}),e}function mi(e,a,i,c,p,v){var M=0;if(c=e,typeof e=="function")Kd(e)&&(M=1);else if(typeof e=="string")M=Sk(e,i,Fe.current)?26:e==="html"||e==="head"||e==="body"?27:5;else e:switch(e){case z:return e=Jr(31,i,a,p),e.elementType=z,e.lanes=v,e;case T:return pi(i.children,p,v,a);case j:M=8,p|=24;break;case I:return e=Jr(12,i,a,p|2),e.elementType=I,e.lanes=v,e;case F:return e=Jr(13,i,a,p),e.elementType=F,e.lanes=v,e;case $:return e=Jr(19,i,a,p),e.elementType=$,e.lanes=v,e;default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case P:M=10;break e;case N:M=9;break e;case H:M=11;break e;case D:M=14;break e;case K:M=16,c=null;break e}M=29,i=Error(s(130,e===null?"null":typeof e,"")),c=null}return a=Jr(M,i,a,p),a.elementType=e,a.type=c,a.lanes=v,a}function pi(e,a,i,c){return e=Jr(7,e,c,a),e.lanes=i,e}function Em(e,a,i){return e=Jr(6,e,null,a),e.lanes=i,e}function Lh(e){var a=Jr(18,null,null,0);return a.stateNode=e,a}function jm(e,a,i){return a=Jr(4,e.children!==null?e.children:[],e.key,a),a.lanes=i,a.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},a}var Dm=new WeakMap;function Or(e,a){if(typeof e=="object"&&e!==null){var i=Dm.get(e);return i!==void 0?i:(a={value:e,source:a,stack:Ue(a)},Dm.set(e,a),a)}return{value:e,source:a,stack:Ue(a)}}var Do=[],yl=0,Lu=null,Ec=0,kr=[],cr=0,Ka=null,ba=1,ca="";function es(e,a){Do[yl++]=Ec,Do[yl++]=Lu,Lu=e,Ec=a}function jc(e,a,i){kr[cr++]=ba,kr[cr++]=ca,kr[cr++]=Ka,Ka=e;var c=ba;e=ca;var p=32-je(c)-1;c&=~(1<<p),i+=1;var v=32-je(a)+p;if(30<v){var M=p-p%5;v=(c&(1<<M)-1).toString(32),c>>=M,p-=M,ba=1<<32-je(a)+p|i<<p|c,ca=v+e}else ba=1<<v|i<<p|c,ca=e}function Io(e){e.return!==null&&(es(e,1),jc(e,1,0))}function Pu(e){for(;e===Lu;)Lu=Do[--yl],Do[yl]=null,Ec=Do[--yl],Do[yl]=null;for(;e===Ka;)Ka=kr[--cr],kr[cr]=null,ca=kr[--cr],kr[cr]=null,ba=kr[--cr],kr[cr]=null}function Qd(e,a){kr[cr++]=ba,kr[cr++]=ca,kr[cr++]=Ka,ba=a.id,ca=a.overflow,Ka=e}var wa=null,rn=null,Vt=!1,Fr=null,ct=!1,_u=Error(s(519));function xa(e){var a=Error(s(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw Ou(Or(a,e)),_u}function Yd(e){var a=e.stateNode,i=e.type,c=e.memoizedProps;switch(a[se]=e,a[ze]=c,i){case"dialog":Xt("cancel",a),Xt("close",a);break;case"iframe":case"object":case"embed":Xt("load",a);break;case"video":case"audio":for(i=0;i<If.length;i++)Xt(If[i],a);break;case"source":Xt("error",a);break;case"img":case"image":case"link":Xt("error",a),Xt("load",a);break;case"details":Xt("toggle",a);break;case"input":Xt("invalid",a),wr(a,c.value,c.defaultValue,c.checked,c.defaultChecked,c.type,c.name,!0);break;case"select":Xt("invalid",a);break;case"textarea":Xt("invalid",a),rl(a,c.value,c.defaultValue,c.children)}i=c.children,typeof i!="string"&&typeof i!="number"&&typeof i!="bigint"||a.textContent===""+i||c.suppressHydrationWarning===!0||Zy(a.textContent,i)?(c.popover!=null&&(Xt("beforetoggle",a),Xt("toggle",a)),c.onScroll!=null&&Xt("scroll",a),c.onScrollEnd!=null&&Xt("scrollend",a),c.onClick!=null&&(a.onclick=ys),a=!0):a=!1,a||xa(e,!0)}function Im(e){for(wa=e.return;wa;)switch(wa.tag){case 5:case 31:case 13:ct=!1;return;case 27:case 3:ct=!0;return;default:wa=wa.return}}function ts(e){if(e!==wa)return!1;if(!Vt)return Im(e),Vt=!0,!1;var a=e.tag,i;if((i=a!==3&&a!==27)&&((i=a===5)&&(i=e.type,i=!(i!=="form"&&i!=="button")||sg(e.type,e.memoizedProps)),i=!i),i&&rn&&xa(e),Im(e),a===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(s(317));rn=ob(e)}else if(a===31){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(s(317));rn=ob(e)}else a===27?(a=rn,Vl(e.type)?(e=ug,ug=null,rn=e):rn=a):rn=wa?ti(e.stateNode.nextSibling):null;return!0}function ns(){rn=wa=null,Vt=!1}function bl(){var e=Fr;return e!==null&&(us===null?us=e:us.push.apply(us,e),Fr=null),e}function Ou(e){Fr===null?Fr=[e]:Fr.push(e)}var qi=Ae(null),hi=null,Ht=null;function ua(e,a,i){Te(qi,a._currentValue),a._currentValue=i}function Br(e){e._currentValue=qi.current,ce(qi)}function Wi(e,a,i){for(;e!==null;){var c=e.alternate;if((e.childLanes&a)!==a?(e.childLanes|=a,c!==null&&(c.childLanes|=a)):c!==null&&(c.childLanes&a)!==a&&(c.childLanes|=a),e===i)break;e=e.return}}function Xd(e,a,i,c){var p=e.child;for(p!==null&&(p.return=e);p!==null;){var v=p.dependencies;if(v!==null){var M=p.child;v=v.firstContext;e:for(;v!==null;){var _=v;v=p;for(var Z=0;Z<a.length;Z++)if(_.context===a[Z]){v.lanes|=i,_=v.alternate,_!==null&&(_.lanes|=i),Wi(v.return,i,e),c||(M=null);break e}v=_.next}}else if(p.tag===18){if(M=p.return,M===null)throw Error(s(341));M.lanes|=i,v=M.alternate,v!==null&&(v.lanes|=i),Wi(M,i,e),M=null}else M=p.child;if(M!==null)M.return=p;else for(M=p;M!==null;){if(M===e){M=null;break}if(p=M.sibling,p!==null){p.return=M.return,M=p;break}M=M.return}p=M}}function wl(e,a,i,c){e=null;for(var p=a,v=!1;p!==null;){if(!v){if((p.flags&524288)!==0)v=!0;else if((p.flags&262144)!==0)break}if(p.tag===10){var M=p.alternate;if(M===null)throw Error(s(387));if(M=M.memoizedProps,M!==null){var _=p.type;la(p.pendingProps.value,M.value)||(e!==null?e.push(_):e=[_])}}else if(p===de.current){if(M=p.alternate,M===null)throw Error(s(387));M.memoizedState.memoizedState!==p.memoizedState.memoizedState&&(e!==null?e.push(Ff):e=[Ff])}p=p.return}e!==null&&Xd(a,e,i,c),a.flags|=262144}function Lo(e){for(e=e.firstContext;e!==null;){if(!la(e.context._currentValue,e.memoizedValue))return!0;e=e.next}return!1}function Gi(e){hi=e,Ht=null,e=e.dependencies,e!==null&&(e.firstContext=null)}function Sa(e){return Cs(hi,e)}function Po(e,a){return hi===null&&Gi(e),Cs(e,a)}function Cs(e,a){var i=a._currentValue;if(a={context:a,memoizedValue:i,next:null},Ht===null){if(e===null)throw Error(s(308));Ht=a,e.dependencies={lanes:0,firstContext:a},e.flags|=524288}else Ht=Ht.next=a;return i}var Zd=typeof AbortController<"u"?AbortController:function(){var e=[],a=this.signal={aborted:!1,addEventListener:function(i,c){e.push(c)}};this.abort=function(){a.aborted=!0,e.forEach(function(i){return i()})}},St=t.unstable_scheduleCallback,Lm=t.unstable_NormalPriority,aa={$$typeof:P,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function Dc(){return{controller:new Zd,data:new Map,refCount:0}}function ks(e){e.refCount--,e.refCount===0&&St(Lm,function(){e.controller.abort()})}var xl=null,Sl=0,as=0,Yn=null;function Cl(e,a){if(xl===null){var i=xl=[];Sl=0,as=Yh(),Yn={status:"pending",value:void 0,then:function(c){i.push(c)}}}return Sl++,a.then(Ca,Ca),a}function Ca(){if(--Sl===0&&xl!==null){Yn!==null&&(Yn.status="fulfilled");var e=xl;xl=null,as=0,Yn=null;for(var a=0;a<e.length;a++)(0,e[a])()}}function Ms(e,a){var i=[],c={status:"pending",value:null,reason:null,then:function(p){i.push(p)}};return e.then(function(){c.status="fulfilled",c.value=a;for(var p=0;p<i.length;p++)(0,i[p])(a)},function(p){for(c.status="rejected",c.reason=p,p=0;p<i.length;p++)(0,i[p])(void 0)}),c}var Pe=U.S;U.S=function(e,a){Sy=B(),typeof a=="object"&&a!==null&&typeof a.then=="function"&&Cl(e,a),Pe!==null&&Pe(e,a)};var Vi=Ae(null);function Jd(){var e=Vi.current;return e!==null?e:ut.pooledCache}function Fu(e,a){a===null?Te(Vi,Vi.current):Te(Vi,a.pool)}function Bu(){var e=Jd();return e===null?null:{parent:aa._currentValue,pool:e}}var Qa=Error(s(460)),Pm=Error(s(474)),Vs=Error(s(542)),On={then:function(){}};function ef(e){return e=e.status,e==="fulfilled"||e==="rejected"}function Hu(e,a,i){switch(i=e[i],i===void 0?e.push(a):i!==a&&(a.then(ys,ys),a=i),a.status){case"fulfilled":return a.value;case"rejected":throw e=a.reason,sn(e),e;default:if(typeof a.status=="string")a.then(ys,ys);else{if(e=ut,e!==null&&100<e.shellSuspendCounter)throw Error(s(482));e=a,e.status="pending",e.then(function(c){if(a.status==="pending"){var p=a;p.status="fulfilled",p.value=c}},function(c){if(a.status==="pending"){var p=a;p.status="rejected",p.reason=c}})}switch(a.status){case"fulfilled":return a.value;case"rejected":throw e=a.reason,sn(e),e}throw _o=a,Qa}}function Ya(e){try{var a=e._init;return a(e._payload)}catch(i){throw i!==null&&typeof i=="object"&&typeof i.then=="function"?(_o=i,Qa):i}}var _o=null;function _m(){if(_o===null)throw Error(s(459));var e=_o;return _o=null,e}function sn(e){if(e===Qa||e===Vs)throw Error(s(483))}var As=null,Ic=0;function Mr(e){var a=Ic;return Ic+=1,As===null&&(As=[]),Hu(As,e,a)}function Oo(e,a){a=a.props.ref,e.ref=a!==void 0?a:null}function Ki(e,a){throw a.$$typeof===S?Error(s(525)):(e=Object.prototype.toString.call(a),Error(s(31,e==="[object Object]"?"object with keys {"+Object.keys(a).join(", ")+"}":e)))}function ur(e){function a(ue,re){if(e){var be=ue.deletions;be===null?(ue.deletions=[re],ue.flags|=16):be.push(re)}}function i(ue,re){if(!e)return null;for(;re!==null;)a(ue,re),re=re.sibling;return null}function c(ue){for(var re=new Map;ue!==null;)ue.key!==null?re.set(ue.key,ue):re.set(ue.index,ue),ue=ue.sibling;return re}function p(ue,re){return ue=Cr(ue,re),ue.index=0,ue.sibling=null,ue}function v(ue,re,be){return ue.index=be,e?(be=ue.alternate,be!==null?(be=be.index,be<re?(ue.flags|=67108866,re):be):(ue.flags|=67108866,re)):(ue.flags|=1048576,re)}function M(ue){return e&&ue.alternate===null&&(ue.flags|=67108866),ue}function _(ue,re,be,Le){return re===null||re.tag!==6?(re=Em(be,ue.mode,Le),re.return=ue,re):(re=p(re,be),re.return=ue,re)}function Z(ue,re,be,Le){var Tt=be.type;return Tt===T?Re(ue,re,be.props.children,Le,be.key):re!==null&&(re.elementType===Tt||typeof Tt=="object"&&Tt!==null&&Tt.$$typeof===K&&Ya(Tt)===re.type)?(re=p(re,be.props),Oo(re,be),re.return=ue,re):(re=mi(be.type,be.key,be.props,null,ue.mode,Le),Oo(re,be),re.return=ue,re)}function we(ue,re,be,Le){return re===null||re.tag!==4||re.stateNode.containerInfo!==be.containerInfo||re.stateNode.implementation!==be.implementation?(re=jm(be,ue.mode,Le),re.return=ue,re):(re=p(re,be.children||[]),re.return=ue,re)}function Re(ue,re,be,Le,Tt){return re===null||re.tag!==7?(re=pi(be,ue.mode,Le,Tt),re.return=ue,re):(re=p(re,be),re.return=ue,re)}function _e(ue,re,be){if(typeof re=="string"&&re!==""||typeof re=="number"||typeof re=="bigint")return re=Em(""+re,ue.mode,be),re.return=ue,re;if(typeof re=="object"&&re!==null){switch(re.$$typeof){case k:return be=mi(re.type,re.key,re.props,null,ue.mode,be),Oo(be,re),be.return=ue,be;case A:return re=jm(re,ue.mode,be),re.return=ue,re;case K:return re=Ya(re),_e(ue,re,be)}if(ee(re)||Y(re))return re=pi(re,ue.mode,be,null),re.return=ue,re;if(typeof re.then=="function")return _e(ue,Mr(re),be);if(re.$$typeof===P)return _e(ue,Po(ue,re),be);Ki(ue,re)}return null}function xe(ue,re,be,Le){var Tt=re!==null?re.key:null;if(typeof be=="string"&&be!==""||typeof be=="number"||typeof be=="bigint")return Tt!==null?null:_(ue,re,""+be,Le);if(typeof be=="object"&&be!==null){switch(be.$$typeof){case k:return be.key===Tt?Z(ue,re,be,Le):null;case A:return be.key===Tt?we(ue,re,be,Le):null;case K:return be=Ya(be),xe(ue,re,be,Le)}if(ee(be)||Y(be))return Tt!==null?null:Re(ue,re,be,Le,null);if(typeof be.then=="function")return xe(ue,re,Mr(be),Le);if(be.$$typeof===P)return xe(ue,re,Po(ue,be),Le);Ki(ue,be)}return null}function ke(ue,re,be,Le,Tt){if(typeof Le=="string"&&Le!==""||typeof Le=="number"||typeof Le=="bigint")return ue=ue.get(be)||null,_(re,ue,""+Le,Tt);if(typeof Le=="object"&&Le!==null){switch(Le.$$typeof){case k:return ue=ue.get(Le.key===null?be:Le.key)||null,Z(re,ue,Le,Tt);case A:return ue=ue.get(Le.key===null?be:Le.key)||null,we(re,ue,Le,Tt);case K:return Le=Ya(Le),ke(ue,re,be,Le,Tt)}if(ee(Le)||Y(Le))return ue=ue.get(be)||null,Re(re,ue,Le,Tt,null);if(typeof Le.then=="function")return ke(ue,re,be,Mr(Le),Tt);if(Le.$$typeof===P)return ke(ue,re,be,Po(re,Le),Tt);Ki(re,Le)}return null}function dt(ue,re,be,Le){for(var Tt=null,fn=null,vt=re,Gt=re=0,Zt=null;vt!==null&&Gt<be.length;Gt++){vt.index>Gt?(Zt=vt,vt=null):Zt=vt.sibling;var mn=xe(ue,vt,be[Gt],Le);if(mn===null){vt===null&&(vt=Zt);break}e&&vt&&mn.alternate===null&&a(ue,vt),re=v(mn,re,Gt),fn===null?Tt=mn:fn.sibling=mn,fn=mn,vt=Zt}if(Gt===be.length)return i(ue,vt),Vt&&es(ue,Gt),Tt;if(vt===null){for(;Gt<be.length;Gt++)vt=_e(ue,be[Gt],Le),vt!==null&&(re=v(vt,re,Gt),fn===null?Tt=vt:fn.sibling=vt,fn=vt);return Vt&&es(ue,Gt),Tt}for(vt=c(vt);Gt<be.length;Gt++)Zt=ke(vt,ue,Gt,be[Gt],Le),Zt!==null&&(e&&Zt.alternate!==null&&vt.delete(Zt.key===null?Gt:Zt.key),re=v(Zt,re,Gt),fn===null?Tt=Zt:fn.sibling=Zt,fn=Zt);return e&&vt.forEach(function(Zl){return a(ue,Zl)}),Vt&&es(ue,Gt),Tt}function Dt(ue,re,be,Le){if(be==null)throw Error(s(151));for(var Tt=null,fn=null,vt=re,Gt=re=0,Zt=null,mn=be.next();vt!==null&&!mn.done;Gt++,mn=be.next()){vt.index>Gt?(Zt=vt,vt=null):Zt=vt.sibling;var Zl=xe(ue,vt,mn.value,Le);if(Zl===null){vt===null&&(vt=Zt);break}e&&vt&&Zl.alternate===null&&a(ue,vt),re=v(Zl,re,Gt),fn===null?Tt=Zl:fn.sibling=Zl,fn=Zl,vt=Zt}if(mn.done)return i(ue,vt),Vt&&es(ue,Gt),Tt;if(vt===null){for(;!mn.done;Gt++,mn=be.next())mn=_e(ue,mn.value,Le),mn!==null&&(re=v(mn,re,Gt),fn===null?Tt=mn:fn.sibling=mn,fn=mn);return Vt&&es(ue,Gt),Tt}for(vt=c(vt);!mn.done;Gt++,mn=be.next())mn=ke(vt,ue,Gt,mn.value,Le),mn!==null&&(e&&mn.alternate!==null&&vt.delete(mn.key===null?Gt:mn.key),re=v(mn,re,Gt),fn===null?Tt=mn:fn.sibling=mn,fn=mn);return e&&vt.forEach(function(Ik){return a(ue,Ik)}),Vt&&es(ue,Gt),Tt}function Nn(ue,re,be,Le){if(typeof be=="object"&&be!==null&&be.type===T&&be.key===null&&(be=be.props.children),typeof be=="object"&&be!==null){switch(be.$$typeof){case k:e:{for(var Tt=be.key;re!==null;){if(re.key===Tt){if(Tt=be.type,Tt===T){if(re.tag===7){i(ue,re.sibling),Le=p(re,be.props.children),Le.return=ue,ue=Le;break e}}else if(re.elementType===Tt||typeof Tt=="object"&&Tt!==null&&Tt.$$typeof===K&&Ya(Tt)===re.type){i(ue,re.sibling),Le=p(re,be.props),Oo(Le,be),Le.return=ue,ue=Le;break e}i(ue,re);break}else a(ue,re);re=re.sibling}be.type===T?(Le=pi(be.props.children,ue.mode,Le,be.key),Le.return=ue,ue=Le):(Le=mi(be.type,be.key,be.props,null,ue.mode,Le),Oo(Le,be),Le.return=ue,ue=Le)}return M(ue);case A:e:{for(Tt=be.key;re!==null;){if(re.key===Tt)if(re.tag===4&&re.stateNode.containerInfo===be.containerInfo&&re.stateNode.implementation===be.implementation){i(ue,re.sibling),Le=p(re,be.children||[]),Le.return=ue,ue=Le;break e}else{i(ue,re);break}else a(ue,re);re=re.sibling}Le=jm(be,ue.mode,Le),Le.return=ue,ue=Le}return M(ue);case K:return be=Ya(be),Nn(ue,re,be,Le)}if(ee(be))return dt(ue,re,be,Le);if(Y(be)){if(Tt=Y(be),typeof Tt!="function")throw Error(s(150));return be=Tt.call(be),Dt(ue,re,be,Le)}if(typeof be.then=="function")return Nn(ue,re,Mr(be),Le);if(be.$$typeof===P)return Nn(ue,re,Po(ue,be),Le);Ki(ue,be)}return typeof be=="string"&&be!==""||typeof be=="number"||typeof be=="bigint"?(be=""+be,re!==null&&re.tag===6?(i(ue,re.sibling),Le=p(re,be),Le.return=ue,ue=Le):(i(ue,re),Le=Em(be,ue.mode,Le),Le.return=ue,ue=Le),M(ue)):i(ue,re)}return function(ue,re,be,Le){try{Ic=0;var Tt=Nn(ue,re,be,Le);return As=null,Tt}catch(vt){if(vt===Qa||vt===Vs)throw vt;var fn=Jr(29,vt,null,ue.mode);return fn.lanes=Le,fn.return=ue,fn}}}var Ks=ur(!0),Ph=ur(!1),Xa=!1;function kl(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Ml(e,a){e=e.updateQueue,a.updateQueue===e&&(a.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function da(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function La(e,a,i){var c=e.updateQueue;if(c===null)return null;if(c=c.shared,(tt&2)!==0){var p=c.pending;return p===null?a.next=a:(a.next=p.next,p.next=a),c.pending=a,a=Ss(e),Ui(e,null,i),a}return ya(e,c,a,i),Ss(e)}function Qi(e,a,i){if(a=a.updateQueue,a!==null&&(a=a.shared,(i&4194048)!==0)){var c=a.lanes;c&=e.pendingLanes,i|=c,a.lanes=i,G(e,i)}}function Fo(e,a){var i=e.updateQueue,c=e.alternate;if(c!==null&&(c=c.updateQueue,i===c)){var p=null,v=null;if(i=i.firstBaseUpdate,i!==null){do{var M={lane:i.lane,tag:i.tag,payload:i.payload,callback:null,next:null};v===null?p=v=M:v=v.next=M,i=i.next}while(i!==null);v===null?p=v=a:v=v.next=a}else p=v=a;i={baseState:c.baseState,firstBaseUpdate:p,lastBaseUpdate:v,shared:c.shared,callbacks:c.callbacks},e.updateQueue=i;return}e=i.lastBaseUpdate,e===null?i.firstBaseUpdate=a:e.next=a,i.lastBaseUpdate=a}var rs=!1;function ka(){if(rs){var e=Yn;if(e!==null)throw e}}function Pa(e,a,i,c){rs=!1;var p=e.updateQueue;Xa=!1;var v=p.firstBaseUpdate,M=p.lastBaseUpdate,_=p.shared.pending;if(_!==null){p.shared.pending=null;var Z=_,we=Z.next;Z.next=null,M===null?v=we:M.next=we,M=Z;var Re=e.alternate;Re!==null&&(Re=Re.updateQueue,_=Re.lastBaseUpdate,_!==M&&(_===null?Re.firstBaseUpdate=we:_.next=we,Re.lastBaseUpdate=Z))}if(v!==null){var _e=p.baseState;M=0,Re=we=Z=null,_=v;do{var xe=_.lane&-536870913,ke=xe!==_.lane;if(ke?(It&xe)===xe:(c&xe)===xe){xe!==0&&xe===as&&(rs=!0),Re!==null&&(Re=Re.next={lane:0,tag:_.tag,payload:_.payload,callback:null,next:null});e:{var dt=e,Dt=_;xe=a;var Nn=i;switch(Dt.tag){case 1:if(dt=Dt.payload,typeof dt=="function"){_e=dt.call(Nn,_e,xe);break e}_e=dt;break e;case 3:dt.flags=dt.flags&-65537|128;case 0:if(dt=Dt.payload,xe=typeof dt=="function"?dt.call(Nn,_e,xe):dt,xe==null)break e;_e=b({},_e,xe);break e;case 2:Xa=!0}}xe=_.callback,xe!==null&&(e.flags|=64,ke&&(e.flags|=8192),ke=p.callbacks,ke===null?p.callbacks=[xe]:ke.push(xe))}else ke={lane:xe,tag:_.tag,payload:_.payload,callback:_.callback,next:null},Re===null?(we=Re=ke,Z=_e):Re=Re.next=ke,M|=xe;if(_=_.next,_===null){if(_=p.shared.pending,_===null)break;ke=_,_=ke.next,ke.next=null,p.lastBaseUpdate=ke,p.shared.pending=null}}while(!0);Re===null&&(Z=_e),p.baseState=Z,p.firstBaseUpdate=we,p.lastBaseUpdate=Re,v===null&&(p.shared.lanes=0),$l|=M,e.lanes=M,e.memoizedState=_e}}function tf(e,a){if(typeof e!="function")throw Error(s(191,e));e.call(a)}function Om(e,a){var i=e.callbacks;if(i!==null)for(e.callbacks=null,e=0;e<i.length;e++)tf(i[e],a)}var Bo=Ae(null),gi=Ae(0);function zu(e,a){e=js,Te(gi,e),Te(Bo,a),js=e|a.baseLanes}function Al(){Te(gi,js),Te(Bo,Bo.current)}function Yi(){js=gi.current,ce(Bo),ce(gi)}var Za=Ae(null),wn=null;function Qs(e){var a=e.alternate;Te(un,un.current&1),Te(Za,e),wn===null&&(a===null||Bo.current!==null||a.memoizedState!==null)&&(wn=e)}function Ts(e){Te(un,un.current),Te(Za,e),wn===null&&(wn=e)}function Lc(e){e.tag===22?(Te(un,un.current),Te(Za,e),wn===null&&(wn=e)):Hr()}function Hr(){Te(un,un.current),Te(Za,Za.current)}function Gn(e){ce(Za),wn===e&&(wn=null),ce(un)}var un=Ae(0);function Ys(e){for(var a=e;a!==null;){if(a.tag===13){var i=a.memoizedState;if(i!==null&&(i=i.dehydrated,i===null||lg(i)||cg(i)))return a}else if(a.tag===19&&(a.memoizedProps.revealOrder==="forwards"||a.memoizedProps.revealOrder==="backwards"||a.memoizedProps.revealOrder==="unstable_legacy-backwards"||a.memoizedProps.revealOrder==="together")){if((a.flags&128)!==0)return a}else if(a.child!==null){a.child.return=a,a=a.child;continue}if(a===e)break;for(;a.sibling===null;){if(a.return===null||a.return===e)return null;a=a.return}a.sibling.return=a.return,a=a.sibling}return null}var Mn=0,Ot=null,Qt=null,Fn=null,Pc=!1,Tl=!1,Xs=!1,Ho=0,Nl=0,ss=null,Fm=0;function Bn(){throw Error(s(321))}function nf(e,a){if(a===null)return!1;for(var i=0;i<a.length&&i<e.length;i++)if(!la(e[i],a[i]))return!1;return!0}function Xi(e,a,i,c,p,v){return Mn=v,Ot=a,a.memoizedState=null,a.updateQueue=null,a.lanes=0,U.H=e===null||e.memoizedState===null?$m:Vc,Xs=!1,v=i(c,p),Xs=!1,Tl&&(v=af(a,i,c,p)),Bm(e),v}function Bm(e){U.H=Il;var a=Qt!==null&&Qt.next!==null;if(Mn=0,Fn=Qt=Ot=null,Pc=!1,Nl=0,ss=null,a)throw Error(s(300));e===null||Zn||(e=e.dependencies,e!==null&&Lo(e)&&(Zn=!0))}function af(e,a,i,c){Ot=e;var p=0;do{if(Tl&&(ss=null),Nl=0,Tl=!1,25<=p)throw Error(s(301));if(p+=1,Fn=Qt=null,e.updateQueue!=null){var v=e.updateQueue;v.lastEffect=null,v.events=null,v.stores=null,v.memoCache!=null&&(v.memoCache.index=0)}U.H=td,v=a(i,c)}while(Tl);return v}function _h(){var e=U.H,a=e.useState()[0];return a=typeof a.then=="function"?vi(a):a,e=e.useState()[0],(Qt!==null?Qt.memoizedState:null)!==e&&(Ot.flags|=1024),a}function $u(){var e=Ho!==0;return Ho=0,e}function rf(e,a,i){a.updateQueue=e.updateQueue,a.flags&=-2053,e.lanes&=~i}function Uu(e){if(Pc){for(e=e.memoizedState;e!==null;){var a=e.queue;a!==null&&(a.pending=null),e=e.next}Pc=!1}Mn=0,Fn=Qt=Ot=null,Tl=!1,Nl=Ho=0,ss=null}function Ma(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Fn===null?Ot.memoizedState=Fn=e:Fn=Fn.next=e,Fn}function Xn(){if(Qt===null){var e=Ot.alternate;e=e!==null?e.memoizedState:null}else e=Qt.next;var a=Fn===null?Ot.memoizedState:Fn.next;if(a!==null)Fn=a,Qt=e;else{if(e===null)throw Ot.alternate===null?Error(s(467)):Error(s(310));Qt=e,e={memoizedState:Qt.memoizedState,baseState:Qt.baseState,baseQueue:Qt.baseQueue,queue:Qt.queue,next:null},Fn===null?Ot.memoizedState=Fn=e:Fn=Fn.next=e}return Fn}function _c(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function vi(e){var a=Nl;return Nl+=1,ss===null&&(ss=[]),e=Hu(ss,e,a),a=Ot,(Fn===null?a.memoizedState:Fn.next)===null&&(a=a.alternate,U.H=a===null||a.memoizedState===null?$m:Vc),e}function Oc(e){if(e!==null&&typeof e=="object"){if(typeof e.then=="function")return vi(e);if(e.$$typeof===P)return Sa(e)}throw Error(s(438,String(e)))}function yi(e){var a=null,i=Ot.updateQueue;if(i!==null&&(a=i.memoCache),a==null){var c=Ot.alternate;c!==null&&(c=c.updateQueue,c!==null&&(c=c.memoCache,c!=null&&(a={data:c.data.map(function(p){return p.slice()}),index:0})))}if(a==null&&(a={data:[],index:0}),i===null&&(i=_c(),Ot.updateQueue=i),i.memoCache=a,i=a.data[a.index],i===void 0)for(i=a.data[a.index]=Array(e),c=0;c<e;c++)i[c]=q;return a.index++,i}function is(e,a){return typeof a=="function"?a(e):a}function Fc(e){var a=Xn();return Zi(a,Qt,e)}function Zi(e,a,i){var c=e.queue;if(c===null)throw Error(s(311));c.lastRenderedReducer=i;var p=e.baseQueue,v=c.pending;if(v!==null){if(p!==null){var M=p.next;p.next=v.next,v.next=M}a.baseQueue=p=v,c.pending=null}if(v=e.baseState,p===null)e.memoizedState=v;else{a=p.next;var _=M=null,Z=null,we=a,Re=!1;do{var _e=we.lane&-536870913;if(_e!==we.lane?(It&_e)===_e:(Mn&_e)===_e){var xe=we.revertLane;if(xe===0)Z!==null&&(Z=Z.next={lane:0,revertLane:0,gesture:null,action:we.action,hasEagerState:we.hasEagerState,eagerState:we.eagerState,next:null}),_e===as&&(Re=!0);else if((Mn&xe)===xe){we=we.next,xe===as&&(Re=!0);continue}else _e={lane:0,revertLane:we.revertLane,gesture:null,action:we.action,hasEagerState:we.hasEagerState,eagerState:we.eagerState,next:null},Z===null?(_=Z=_e,M=v):Z=Z.next=_e,Ot.lanes|=xe,$l|=xe;_e=we.action,Xs&&i(v,_e),v=we.hasEagerState?we.eagerState:i(v,_e)}else xe={lane:_e,revertLane:we.revertLane,gesture:we.gesture,action:we.action,hasEagerState:we.hasEagerState,eagerState:we.eagerState,next:null},Z===null?(_=Z=xe,M=v):Z=Z.next=xe,Ot.lanes|=_e,$l|=_e;we=we.next}while(we!==null&&we!==a);if(Z===null?M=v:Z.next=_,!la(v,e.memoizedState)&&(Zn=!0,Re&&(i=Yn,i!==null)))throw i;e.memoizedState=v,e.baseState=M,e.baseQueue=Z,c.lastRenderedState=v}return p===null&&(c.lanes=0),[e.memoizedState,c.dispatch]}function bi(e){var a=Xn(),i=a.queue;if(i===null)throw Error(s(311));i.lastRenderedReducer=e;var c=i.dispatch,p=i.pending,v=a.memoizedState;if(p!==null){i.pending=null;var M=p=p.next;do v=e(v,M.action),M=M.next;while(M!==p);la(v,a.memoizedState)||(Zn=!0),a.memoizedState=v,a.baseQueue===null&&(a.baseState=v),i.lastRenderedState=v}return[v,c]}function qu(e,a,i){var c=Ot,p=Xn(),v=Vt;if(v){if(i===void 0)throw Error(s(407));i=i()}else i=a();var M=!la((Qt||p).memoizedState,i);if(M&&(p.memoizedState=i,Zn=!0),p=p.queue,Vu(Rl.bind(null,c,p,e),[e]),p.getSnapshot!==a||M||Fn!==null&&Fn.memoizedState.tag&1){if(c.flags|=2048,to(9,{destroy:void 0},sf.bind(null,c,p,i,a),null),ut===null)throw Error(s(349));v||(Mn&127)!==0||Hm(c,a,i)}return i}function Hm(e,a,i){e.flags|=16384,e={getSnapshot:a,value:i},a=Ot.updateQueue,a===null?(a=_c(),Ot.updateQueue=a,a.stores=[e]):(i=a.stores,i===null?a.stores=[e]:i.push(e))}function sf(e,a,i,c){a.value=i,a.getSnapshot=c,Wu(a)&&El(e)}function Rl(e,a,i){return i(function(){Wu(a)&&El(e)})}function Wu(e){var a=e.getSnapshot;e=e.value;try{var i=a();return!la(e,i)}catch{return!0}}function El(e){var a=_n(e,2);a!==null&&ds(a,e,2)}function of(e){var a=Ma();if(typeof e=="function"){var i=e;if(e=i(),Xs){Ee(!0);try{i()}finally{Ee(!1)}}}return a.memoizedState=a.baseState=e,a.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:is,lastRenderedState:e},a}function Bc(e,a,i,c){return e.baseState=i,Zi(e,Qt,typeof c=="function"?c:is)}function Hc(e,a,i,c,p){if(mr(e))throw Error(s(485));if(e=a.action,e!==null){var v={payload:p,action:e,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(M){v.listeners.push(M)}};U.T!==null?i(!0):v.isTransition=!1,c(v),i=a.pending,i===null?(v.next=a.pending=v,zo(a,v)):(v.next=i.next,a.pending=i.next=v)}}function zo(e,a){var i=a.action,c=a.payload,p=e.state;if(a.isTransition){var v=U.T,M={};U.T=M;try{var _=i(p,c),Z=U.S;Z!==null&&Z(M,_),Gu(e,a,_)}catch(we){Ji(e,a,we)}finally{v!==null&&M.types!==null&&(v.types=M.types),U.T=v}}else try{v=i(p,c),Gu(e,a,v)}catch(we){Ji(e,a,we)}}function Gu(e,a,i){i!==null&&typeof i=="object"&&typeof i.then=="function"?i.then(function(c){zc(e,a,c)},function(c){return Ji(e,a,c)}):zc(e,a,i)}function zc(e,a,i){a.status="fulfilled",a.value=i,jl(a),e.state=i,a=e.pending,a!==null&&(i=a.next,i===a?e.pending=null:(i=i.next,a.next=i,zo(e,i)))}function Ji(e,a,i){var c=e.pending;if(e.pending=null,c!==null){c=c.next;do a.status="rejected",a.reason=i,jl(a),a=a.next;while(a!==c)}e.action=null}function jl(e){e=e.listeners;for(var a=0;a<e.length;a++)(0,e[a])()}function lf(e,a){return a}function eo(e,a){if(Vt){var i=ut.formState;if(i!==null){e:{var c=Ot;if(Vt){if(rn){t:{for(var p=rn,v=ct;p.nodeType!==8;){if(!v){p=null;break t}if(p=ti(p.nextSibling),p===null){p=null;break t}}v=p.data,p=v==="F!"||v==="F"?p:null}if(p){rn=ti(p.nextSibling),c=p.data==="F!";break e}}xa(c)}c=!1}c&&(a=i[0])}}return i=Ma(),i.memoizedState=i.baseState=a,c={pending:null,lanes:0,dispatch:null,lastRenderedReducer:lf,lastRenderedState:a},i.queue=c,i=no.bind(null,Ot,c),c.dispatch=i,c=of(!1),v=$r.bind(null,Ot,!1,c.queue),c=Ma(),p={state:a,dispatch:null,action:e,pending:null},c.queue=p,i=Hc.bind(null,Ot,p,v,i),p.dispatch=i,c.memoizedState=e,[a,i,!1]}function cf(e){var a=Xn();return uf(a,Qt,e)}function uf(e,a,i){if(a=Zi(e,a,lf)[0],e=Fc(is)[0],typeof a=="object"&&a!==null&&typeof a.then=="function")try{var c=vi(a)}catch(M){throw M===Qa?Vs:M}else c=a;a=Xn();var p=a.queue,v=p.dispatch;return i!==a.memoizedState&&(Ot.flags|=2048,to(9,{destroy:void 0},Ar.bind(null,p,i),null)),[c,v,e]}function Ar(e,a){e.action=a}function $c(e){var a=Xn(),i=Qt;if(i!==null)return uf(a,i,e);Xn(),a=a.memoizedState,i=Xn();var c=i.queue.dispatch;return i.memoizedState=e,[a,c,!1]}function to(e,a,i,c){return e={tag:e,create:i,deps:c,inst:a,next:null},a=Ot.updateQueue,a===null&&(a=_c(),Ot.updateQueue=a),i=a.lastEffect,i===null?a.lastEffect=e.next=e:(c=i.next,i.next=e,e.next=c,a.lastEffect=e),e}function $o(){return Xn().memoizedState}function dr(e,a,i,c){var p=Ma();Ot.flags|=e,p.memoizedState=to(1|a,{destroy:void 0},i,c===void 0?null:c)}function fr(e,a,i,c){var p=Xn();c=c===void 0?null:c;var v=p.memoizedState.inst;Qt!==null&&c!==null&&nf(c,Qt.memoizedState.deps)?p.memoizedState=to(a,v,i,c):(Ot.flags|=e,p.memoizedState=to(1|a,v,i,c))}function Uo(e,a){dr(8390656,8,e,a)}function Vu(e,a){fr(2048,8,e,a)}function Ku(e){Ot.flags|=4;var a=Ot.updateQueue;if(a===null)a=_c(),Ot.updateQueue=a,a.events=[e];else{var i=a.events;i===null?a.events=[e]:i.push(e)}}function zr(e){var a=Xn().memoizedState;return Ku({ref:a,nextImpl:e}),function(){if((tt&2)!==0)throw Error(s(440));return a.impl.apply(void 0,arguments)}}function Oh(e,a){return fr(4,2,e,a)}function df(e,a){return fr(4,4,e,a)}function Uc(e,a){if(typeof a=="function"){e=e();var i=a(e);return function(){typeof i=="function"?i():a(null)}}if(a!=null)return e=e(),a.current=e,function(){a.current=null}}function qc(e,a,i){i=i!=null?i.concat([e]):null,fr(4,4,Uc.bind(null,a,e),i)}function qo(){}function Wc(e,a){var i=Xn();a=a===void 0?null:a;var c=i.memoizedState;return a!==null&&nf(a,c[1])?c[0]:(i.memoizedState=[e,a],e)}function Qu(e,a){var i=Xn();a=a===void 0?null:a;var c=i.memoizedState;if(a!==null&&nf(a,c[1]))return c[0];if(c=e(),Xs){Ee(!0);try{e()}finally{Ee(!1)}}return i.memoizedState=[c,a],c}function Yu(e,a,i){return i===void 0||(Mn&1073741824)!==0&&(It&261930)===0?e.memoizedState=a:(e.memoizedState=i,e=ky(),Ot.lanes|=e,$l|=e,i)}function Ns(e,a,i,c){return la(i,a)?i:Bo.current!==null?(e=Yu(e,i,c),la(e,a)||(Zn=!0),e):(Mn&42)===0||(Mn&1073741824)!==0&&(It&261930)===0?(Zn=!0,e.memoizedState=i):(e=ky(),Ot.lanes|=e,$l|=e,a)}function ff(e,a,i,c,p){var v=L.p;L.p=v!==0&&8>v?v:8;var M=U.T,_={};U.T=_,$r(e,!1,a,i);try{var Z=p(),we=U.S;if(we!==null&&we(_,Z),Z!==null&&typeof Z=="object"&&typeof Z.then=="function"){var Re=Ms(Z,c);ra(e,a,Re,Is(e))}else ra(e,a,c,Is(e))}catch(_e){ra(e,a,{then:function(){},status:"rejected",reason:_e},Is())}finally{L.p=v,M!==null&&_.types!==null&&(M.types=_.types),U.T=M}}function mf(){}function Gc(e,a,i,c){if(e.tag!==5)throw Error(s(476));var p=Xu(e).queue;ff(e,p,a,le,i===null?mf:function(){return Zu(e),i(c)})}function Xu(e){var a=e.memoizedState;if(a!==null)return a;a={memoizedState:le,baseState:le,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:is,lastRenderedState:le},next:null};var i={};return a.next={memoizedState:i,baseState:i,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:is,lastRenderedState:i},next:null},e.memoizedState=a,e=e.alternate,e!==null&&(e.memoizedState=a),a}function Zu(e){var a=Xu(e);a.next===null&&(a=e.alternate.memoizedState),ra(e,a.next.queue,{},Is())}function Ju(){return Sa(Ff)}function Dl(){return Xn().memoizedState}function Rs(){return Xn().memoizedState}function pf(e){for(var a=e.return;a!==null;){switch(a.tag){case 24:case 3:var i=Is();e=da(i);var c=La(a,e,i);c!==null&&(ds(c,a,i),Qi(c,a,i)),a={cache:Dc()},e.payload=a;return}a=a.return}}function Es(e,a,i){var c=Is();i={lane:c,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null},mr(e)?ed(a,i):(i=Iu(e,a,i,c),i!==null&&(ds(i,e,c),zm(i,a,c)))}function no(e,a,i){var c=Is();ra(e,a,i,c)}function ra(e,a,i,c){var p={lane:c,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null};if(mr(e))ed(a,p);else{var v=e.alternate;if(e.lanes===0&&(v===null||v.lanes===0)&&(v=a.lastRenderedReducer,v!==null))try{var M=a.lastRenderedState,_=v(M,i);if(p.hasEagerState=!0,p.eagerState=_,la(_,M))return ya(e,a,p,0),ut===null&&va(),!1}catch{}if(i=Iu(e,a,p,c),i!==null)return ds(i,e,c),zm(i,a,c),!0}return!1}function $r(e,a,i,c){if(c={lane:2,revertLane:Yh(),gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},mr(e)){if(a)throw Error(s(479))}else a=Iu(e,i,c,2),a!==null&&ds(a,e,2)}function mr(e){var a=e.alternate;return e===Ot||a!==null&&a===Ot}function ed(e,a){Tl=Pc=!0;var i=e.pending;i===null?a.next=a:(a.next=i.next,i.next=a),e.pending=a}function zm(e,a,i){if((i&4194048)!==0){var c=a.lanes;c&=e.pendingLanes,i|=c,a.lanes=i,G(e,i)}}var Il={readContext:Sa,use:Oc,useCallback:Bn,useContext:Bn,useEffect:Bn,useImperativeHandle:Bn,useLayoutEffect:Bn,useInsertionEffect:Bn,useMemo:Bn,useReducer:Bn,useRef:Bn,useState:Bn,useDebugValue:Bn,useDeferredValue:Bn,useTransition:Bn,useSyncExternalStore:Bn,useId:Bn,useHostTransitionStatus:Bn,useFormState:Bn,useActionState:Bn,useOptimistic:Bn,useMemoCache:Bn,useCacheRefresh:Bn};Il.useEffectEvent=Bn;var $m={readContext:Sa,use:Oc,useCallback:function(e,a){return Ma().memoizedState=[e,a===void 0?null:a],e},useContext:Sa,useEffect:Uo,useImperativeHandle:function(e,a,i){i=i!=null?i.concat([e]):null,dr(4194308,4,Uc.bind(null,a,e),i)},useLayoutEffect:function(e,a){return dr(4194308,4,e,a)},useInsertionEffect:function(e,a){dr(4,2,e,a)},useMemo:function(e,a){var i=Ma();a=a===void 0?null:a;var c=e();if(Xs){Ee(!0);try{e()}finally{Ee(!1)}}return i.memoizedState=[c,a],c},useReducer:function(e,a,i){var c=Ma();if(i!==void 0){var p=i(a);if(Xs){Ee(!0);try{i(a)}finally{Ee(!1)}}}else p=a;return c.memoizedState=c.baseState=p,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:p},c.queue=e,e=e.dispatch=Es.bind(null,Ot,e),[c.memoizedState,e]},useRef:function(e){var a=Ma();return e={current:e},a.memoizedState=e},useState:function(e){e=of(e);var a=e.queue,i=no.bind(null,Ot,a);return a.dispatch=i,[e.memoizedState,i]},useDebugValue:qo,useDeferredValue:function(e,a){var i=Ma();return Yu(i,e,a)},useTransition:function(){var e=of(!1);return e=ff.bind(null,Ot,e.queue,!0,!1),Ma().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,a,i){var c=Ot,p=Ma();if(Vt){if(i===void 0)throw Error(s(407));i=i()}else{if(i=a(),ut===null)throw Error(s(349));(It&127)!==0||Hm(c,a,i)}p.memoizedState=i;var v={value:i,getSnapshot:a};return p.queue=v,Uo(Rl.bind(null,c,v,e),[e]),c.flags|=2048,to(9,{destroy:void 0},sf.bind(null,c,v,i,a),null),i},useId:function(){var e=Ma(),a=ut.identifierPrefix;if(Vt){var i=ca,c=ba;i=(c&~(1<<32-je(c)-1)).toString(32)+i,a="_"+a+"R_"+i,i=Ho++,0<i&&(a+="H"+i.toString(32)),a+="_"}else i=Fm++,a="_"+a+"r_"+i.toString(32)+"_";return e.memoizedState=a},useHostTransitionStatus:Ju,useFormState:eo,useActionState:eo,useOptimistic:function(e){var a=Ma();a.memoizedState=a.baseState=e;var i={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return a.queue=i,a=$r.bind(null,Ot,!0,i),i.dispatch=a,[e,a]},useMemoCache:yi,useCacheRefresh:function(){return Ma().memoizedState=pf.bind(null,Ot)},useEffectEvent:function(e){var a=Ma(),i={impl:e};return a.memoizedState=i,function(){if((tt&2)!==0)throw Error(s(440));return i.impl.apply(void 0,arguments)}}},Vc={readContext:Sa,use:Oc,useCallback:Wc,useContext:Sa,useEffect:Vu,useImperativeHandle:qc,useInsertionEffect:Oh,useLayoutEffect:df,useMemo:Qu,useReducer:Fc,useRef:$o,useState:function(){return Fc(is)},useDebugValue:qo,useDeferredValue:function(e,a){var i=Xn();return Ns(i,Qt.memoizedState,e,a)},useTransition:function(){var e=Fc(is)[0],a=Xn().memoizedState;return[typeof e=="boolean"?e:vi(e),a]},useSyncExternalStore:qu,useId:Dl,useHostTransitionStatus:Ju,useFormState:cf,useActionState:cf,useOptimistic:function(e,a){var i=Xn();return Bc(i,Qt,e,a)},useMemoCache:yi,useCacheRefresh:Rs};Vc.useEffectEvent=zr;var td={readContext:Sa,use:Oc,useCallback:Wc,useContext:Sa,useEffect:Vu,useImperativeHandle:qc,useInsertionEffect:Oh,useLayoutEffect:df,useMemo:Qu,useReducer:bi,useRef:$o,useState:function(){return bi(is)},useDebugValue:qo,useDeferredValue:function(e,a){var i=Xn();return Qt===null?Yu(i,e,a):Ns(i,Qt.memoizedState,e,a)},useTransition:function(){var e=bi(is)[0],a=Xn().memoizedState;return[typeof e=="boolean"?e:vi(e),a]},useSyncExternalStore:qu,useId:Dl,useHostTransitionStatus:Ju,useFormState:$c,useActionState:$c,useOptimistic:function(e,a){var i=Xn();return Qt!==null?Bc(i,Qt,e,a):(i.baseState=e,[e,i.queue.dispatch])},useMemoCache:yi,useCacheRefresh:Rs};td.useEffectEvent=zr;function An(e,a,i,c){a=e.memoizedState,i=i(c,a),i=i==null?a:b({},a,i),e.memoizedState=i,e.lanes===0&&(e.updateQueue.baseState=i)}var Kc={enqueueSetState:function(e,a,i){e=e._reactInternals;var c=Is(),p=da(c);p.payload=a,i!=null&&(p.callback=i),a=La(e,p,c),a!==null&&(ds(a,e,c),Qi(a,e,c))},enqueueReplaceState:function(e,a,i){e=e._reactInternals;var c=Is(),p=da(c);p.tag=1,p.payload=a,i!=null&&(p.callback=i),a=La(e,p,c),a!==null&&(ds(a,e,c),Qi(a,e,c))},enqueueForceUpdate:function(e,a){e=e._reactInternals;var i=Is(),c=da(i);c.tag=2,a!=null&&(c.callback=a),a=La(e,c,i),a!==null&&(ds(a,e,i),Qi(a,e,i))}};function Ll(e,a,i,c,p,v,M){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(c,v,M):a.prototype&&a.prototype.isPureReactComponent?!Fi(i,c)||!Fi(p,v):!0}function Qc(e,a,i,c){e=a.state,typeof a.componentWillReceiveProps=="function"&&a.componentWillReceiveProps(i,c),typeof a.UNSAFE_componentWillReceiveProps=="function"&&a.UNSAFE_componentWillReceiveProps(i,c),a.state!==e&&Kc.enqueueReplaceState(a,a.state,null)}function ao(e,a){var i=a;if("ref"in a){i={};for(var c in a)c!=="ref"&&(i[c]=a[c])}if(e=e.defaultProps){i===a&&(i=b({},i));for(var p in e)i[p]===void 0&&(i[p]=e[p])}return i}function hf(e){Gs(e)}function gf(e){console.error(e)}function Pl(e){Gs(e)}function Wo(e,a){try{var i=e.onUncaughtError;i(a.value,{componentStack:a.stack})}catch(c){setTimeout(function(){throw c})}}function Go(e,a,i){try{var c=e.onCaughtError;c(i.value,{componentStack:i.stack,errorBoundary:a.tag===1?a.stateNode:null})}catch(p){setTimeout(function(){throw p})}}function vf(e,a,i){return i=da(i),i.tag=3,i.payload={element:null},i.callback=function(){Wo(e,a)},i}function yf(e){return e=da(e),e.tag=3,e}function _l(e,a,i,c){var p=i.type.getDerivedStateFromError;if(typeof p=="function"){var v=c.value;e.payload=function(){return p(v)},e.callback=function(){Go(a,i,c)}}var M=i.stateNode;M!==null&&typeof M.componentDidCatch=="function"&&(e.callback=function(){Go(a,i,c),typeof p!="function"&&(Ul===null?Ul=new Set([this]):Ul.add(this));var _=c.stack;this.componentDidCatch(c.value,{componentStack:_!==null?_:""})})}function Fh(e,a,i,c,p){if(i.flags|=32768,c!==null&&typeof c=="object"&&typeof c.then=="function"){if(a=i.alternate,a!==null&&wl(a,i,p,!0),i=Za.current,i!==null){switch(i.tag){case 31:case 13:return wn===null?np():i.alternate===null&&ia===0&&(ia=3),i.flags&=-257,i.flags|=65536,i.lanes=p,c===On?i.flags|=16384:(a=i.updateQueue,a===null?i.updateQueue=new Set([c]):a.add(c),Vh(e,c,p)),!1;case 22:return i.flags|=65536,c===On?i.flags|=16384:(a=i.updateQueue,a===null?(a={transitions:null,markerInstances:null,retryQueue:new Set([c])},i.updateQueue=a):(i=a.retryQueue,i===null?a.retryQueue=new Set([c]):i.add(c)),Vh(e,c,p)),!1}throw Error(s(435,i.tag))}return Vh(e,c,p),np(),!1}if(Vt)return a=Za.current,a!==null?((a.flags&65536)===0&&(a.flags|=256),a.flags|=65536,a.lanes=p,c!==_u&&(e=Error(s(422),{cause:c}),Ou(Or(e,i)))):(c!==_u&&(a=Error(s(423),{cause:c}),Ou(Or(a,i))),e=e.current.alternate,e.flags|=65536,p&=-p,e.lanes|=p,c=Or(c,i),p=vf(e.stateNode,c,p),Fo(e,p),ia!==4&&(ia=2)),!1;var v=Error(s(520),{cause:c});if(v=Or(v,i),Ef===null?Ef=[v]:Ef.push(v),ia!==4&&(ia=2),a===null)return!0;c=Or(c,i),i=a;do{switch(i.tag){case 3:return i.flags|=65536,e=p&-p,i.lanes|=e,e=vf(i.stateNode,c,e),Fo(i,e),!1;case 1:if(a=i.type,v=i.stateNode,(i.flags&128)===0&&(typeof a.getDerivedStateFromError=="function"||v!==null&&typeof v.componentDidCatch=="function"&&(Ul===null||!Ul.has(v))))return i.flags|=65536,p&=-p,i.lanes|=p,p=yf(p),_l(p,e,i,c),Fo(i,p),!1}i=i.return}while(i!==null);return!1}var bf=Error(s(461)),Zn=!1;function _a(e,a,i,c){a.child=e===null?Ph(a,null,i,c):Ks(a,e.child,i,c)}function nd(e,a,i,c,p){i=i.render;var v=a.ref;if("ref"in c){var M={};for(var _ in c)_!=="ref"&&(M[_]=c[_])}else M=c;return Gi(a),c=Xi(e,a,i,M,v,p),_=$u(),e!==null&&!Zn?(rf(e,a,p),wi(e,a,p)):(Vt&&_&&Io(a),a.flags|=1,_a(e,a,c,p),a.child)}function ad(e,a,i,c,p){if(e===null){var v=i.type;return typeof v=="function"&&!Kd(v)&&v.defaultProps===void 0&&i.compare===null?(a.tag=15,a.type=v,Ol(e,a,v,c,p)):(e=mi(i.type,null,c,a,a.mode,p),e.ref=a.ref,e.return=a,a.child=e)}if(v=e.child,!Cf(e,p)){var M=v.memoizedProps;if(i=i.compare,i=i!==null?i:Fi,i(M,c)&&e.ref===a.ref)return wi(e,a,p)}return a.flags|=1,e=Cr(v,c),e.ref=a.ref,e.return=a,a.child=e}function Ol(e,a,i,c,p){if(e!==null){var v=e.memoizedProps;if(Fi(v,c)&&e.ref===a.ref)if(Zn=!1,a.pendingProps=c=v,Cf(e,p))(e.flags&131072)!==0&&(Zn=!0);else return a.lanes=e.lanes,wi(e,a,p)}return id(e,a,i,c,p)}function wf(e,a,i,c){var p=c.children,v=e!==null?e.memoizedState:null;if(e===null&&a.stateNode===null&&(a.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),c.mode==="hidden"){if((a.flags&128)!==0){if(v=v!==null?v.baseLanes|i:i,e!==null){for(c=a.child=e.child,p=0;c!==null;)p=p|c.lanes|c.childLanes,c=c.sibling;c=p&~v}else c=0,a.child=null;return Um(e,a,v,i,c)}if((i&536870912)!==0)a.memoizedState={baseLanes:0,cachePool:null},e!==null&&Fu(a,v!==null?v.cachePool:null),v!==null?zu(a,v):Al(),Lc(a);else return c=a.lanes=536870912,Um(e,a,v!==null?v.baseLanes|i:i,i,c)}else v!==null?(Fu(a,v.cachePool),zu(a,v),Hr(),a.memoizedState=null):(e!==null&&Fu(a,null),Al(),Hr());return _a(e,a,p,i),a.child}function Vo(e,a){return e!==null&&e.tag===22||a.stateNode!==null||(a.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),a.sibling}function Um(e,a,i,c,p){var v=Jd();return v=v===null?null:{parent:aa._currentValue,pool:v},a.memoizedState={baseLanes:i,cachePool:v},e!==null&&Fu(a,null),Al(),Lc(a),e!==null&&wl(e,a,c,!0),a.childLanes=p,null}function rd(e,a){return a=Xc({mode:a.mode,children:a.children},e.mode),a.ref=e.ref,e.child=a,a.return=e,a}function ro(e,a,i){return Ks(a,e.child,null,i),e=rd(a,a.pendingProps),e.flags|=2,Gn(a),a.memoizedState=null,e}function qm(e,a,i){var c=a.pendingProps,p=(a.flags&128)!==0;if(a.flags&=-129,e===null){if(Vt){if(c.mode==="hidden")return e=rd(a,c),a.lanes=536870912,Vo(null,e);if(Ts(a),(e=rn)?(e=ib(e,ct),e=e!==null&&e.data==="&"?e:null,e!==null&&(a.memoizedState={dehydrated:e,treeContext:Ka!==null?{id:ba,overflow:ca}:null,retryLane:536870912,hydrationErrors:null},i=Lh(e),i.return=a,a.child=i,wa=a,rn=null)):e=null,e===null)throw xa(a);return a.lanes=536870912,null}return rd(a,c)}var v=e.memoizedState;if(v!==null){var M=v.dehydrated;if(Ts(a),p)if(a.flags&256)a.flags&=-257,a=ro(e,a,i);else if(a.memoizedState!==null)a.child=e.child,a.flags|=128,a=null;else throw Error(s(558));else if(Zn||wl(e,a,i,!1),p=(i&e.childLanes)!==0,Zn||p){if(c=ut,c!==null&&(M=ot(c,i),M!==0&&M!==v.retryLane))throw v.retryLane=M,_n(e,M),ds(c,e,M),bf;np(),a=ro(e,a,i)}else e=v.treeContext,rn=ti(M.nextSibling),wa=a,Vt=!0,Fr=null,ct=!1,e!==null&&Qd(a,e),a=rd(a,c),a.flags|=4096;return a}return e=Cr(e.child,{mode:c.mode,children:c.children}),e.ref=a.ref,a.child=e,e.return=a,e}function sd(e,a){var i=a.ref;if(i===null)e!==null&&e.ref!==null&&(a.flags|=4194816);else{if(typeof i!="function"&&typeof i!="object")throw Error(s(284));(e===null||e.ref!==i)&&(a.flags|=4194816)}}function id(e,a,i,c,p){return Gi(a),i=Xi(e,a,i,c,void 0,p),c=$u(),e!==null&&!Zn?(rf(e,a,p),wi(e,a,p)):(Vt&&c&&Io(a),a.flags|=1,_a(e,a,i,p),a.child)}function Wm(e,a,i,c,p,v){return Gi(a),a.updateQueue=null,i=af(a,c,i,p),Bm(e),c=$u(),e!==null&&!Zn?(rf(e,a,v),wi(e,a,v)):(Vt&&c&&Io(a),a.flags|=1,_a(e,a,i,v),a.child)}function Yc(e,a,i,c,p){if(Gi(a),a.stateNode===null){var v=vl,M=i.contextType;typeof M=="object"&&M!==null&&(v=Sa(M)),v=new i(c,v),a.memoizedState=v.state!==null&&v.state!==void 0?v.state:null,v.updater=Kc,a.stateNode=v,v._reactInternals=a,v=a.stateNode,v.props=c,v.state=a.memoizedState,v.refs={},kl(a),M=i.contextType,v.context=typeof M=="object"&&M!==null?Sa(M):vl,v.state=a.memoizedState,M=i.getDerivedStateFromProps,typeof M=="function"&&(An(a,i,M,c),v.state=a.memoizedState),typeof i.getDerivedStateFromProps=="function"||typeof v.getSnapshotBeforeUpdate=="function"||typeof v.UNSAFE_componentWillMount!="function"&&typeof v.componentWillMount!="function"||(M=v.state,typeof v.componentWillMount=="function"&&v.componentWillMount(),typeof v.UNSAFE_componentWillMount=="function"&&v.UNSAFE_componentWillMount(),M!==v.state&&Kc.enqueueReplaceState(v,v.state,null),Pa(a,c,v,p),ka(),v.state=a.memoizedState),typeof v.componentDidMount=="function"&&(a.flags|=4194308),c=!0}else if(e===null){v=a.stateNode;var _=a.memoizedProps,Z=ao(i,_);v.props=Z;var we=v.context,Re=i.contextType;M=vl,typeof Re=="object"&&Re!==null&&(M=Sa(Re));var _e=i.getDerivedStateFromProps;Re=typeof _e=="function"||typeof v.getSnapshotBeforeUpdate=="function",_=a.pendingProps!==_,Re||typeof v.UNSAFE_componentWillReceiveProps!="function"&&typeof v.componentWillReceiveProps!="function"||(_||we!==M)&&Qc(a,v,c,M),Xa=!1;var xe=a.memoizedState;v.state=xe,Pa(a,c,v,p),ka(),we=a.memoizedState,_||xe!==we||Xa?(typeof _e=="function"&&(An(a,i,_e,c),we=a.memoizedState),(Z=Xa||Ll(a,i,Z,c,xe,we,M))?(Re||typeof v.UNSAFE_componentWillMount!="function"&&typeof v.componentWillMount!="function"||(typeof v.componentWillMount=="function"&&v.componentWillMount(),typeof v.UNSAFE_componentWillMount=="function"&&v.UNSAFE_componentWillMount()),typeof v.componentDidMount=="function"&&(a.flags|=4194308)):(typeof v.componentDidMount=="function"&&(a.flags|=4194308),a.memoizedProps=c,a.memoizedState=we),v.props=c,v.state=we,v.context=M,c=Z):(typeof v.componentDidMount=="function"&&(a.flags|=4194308),c=!1)}else{v=a.stateNode,Ml(e,a),M=a.memoizedProps,Re=ao(i,M),v.props=Re,_e=a.pendingProps,xe=v.context,we=i.contextType,Z=vl,typeof we=="object"&&we!==null&&(Z=Sa(we)),_=i.getDerivedStateFromProps,(we=typeof _=="function"||typeof v.getSnapshotBeforeUpdate=="function")||typeof v.UNSAFE_componentWillReceiveProps!="function"&&typeof v.componentWillReceiveProps!="function"||(M!==_e||xe!==Z)&&Qc(a,v,c,Z),Xa=!1,xe=a.memoizedState,v.state=xe,Pa(a,c,v,p),ka();var ke=a.memoizedState;M!==_e||xe!==ke||Xa||e!==null&&e.dependencies!==null&&Lo(e.dependencies)?(typeof _=="function"&&(An(a,i,_,c),ke=a.memoizedState),(Re=Xa||Ll(a,i,Re,c,xe,ke,Z)||e!==null&&e.dependencies!==null&&Lo(e.dependencies))?(we||typeof v.UNSAFE_componentWillUpdate!="function"&&typeof v.componentWillUpdate!="function"||(typeof v.componentWillUpdate=="function"&&v.componentWillUpdate(c,ke,Z),typeof v.UNSAFE_componentWillUpdate=="function"&&v.UNSAFE_componentWillUpdate(c,ke,Z)),typeof v.componentDidUpdate=="function"&&(a.flags|=4),typeof v.getSnapshotBeforeUpdate=="function"&&(a.flags|=1024)):(typeof v.componentDidUpdate!="function"||M===e.memoizedProps&&xe===e.memoizedState||(a.flags|=4),typeof v.getSnapshotBeforeUpdate!="function"||M===e.memoizedProps&&xe===e.memoizedState||(a.flags|=1024),a.memoizedProps=c,a.memoizedState=ke),v.props=c,v.state=ke,v.context=Z,c=Re):(typeof v.componentDidUpdate!="function"||M===e.memoizedProps&&xe===e.memoizedState||(a.flags|=4),typeof v.getSnapshotBeforeUpdate!="function"||M===e.memoizedProps&&xe===e.memoizedState||(a.flags|=1024),c=!1)}return v=c,sd(e,a),c=(a.flags&128)!==0,v||c?(v=a.stateNode,i=c&&typeof i.getDerivedStateFromError!="function"?null:v.render(),a.flags|=1,e!==null&&c?(a.child=Ks(a,e.child,null,p),a.child=Ks(a,null,i,p)):_a(e,a,i,p),a.memoizedState=v.state,e=a.child):e=wi(e,a,p),e}function xf(e,a,i,c){return ns(),a.flags|=256,_a(e,a,i,c),a.child}var od={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function ld(e){return{baseLanes:e,cachePool:Bu()}}function Sf(e,a,i){return e=e!==null?e.childLanes&~i:0,a&&(e|=Ds),e}function cd(e,a,i){var c=a.pendingProps,p=!1,v=(a.flags&128)!==0,M;if((M=v)||(M=e!==null&&e.memoizedState===null?!1:(un.current&2)!==0),M&&(p=!0,a.flags&=-129),M=(a.flags&32)!==0,a.flags&=-33,e===null){if(Vt){if(p?Qs(a):Hr(),(e=rn)?(e=ib(e,ct),e=e!==null&&e.data!=="&"?e:null,e!==null&&(a.memoizedState={dehydrated:e,treeContext:Ka!==null?{id:ba,overflow:ca}:null,retryLane:536870912,hydrationErrors:null},i=Lh(e),i.return=a,a.child=i,wa=a,rn=null)):e=null,e===null)throw xa(a);return cg(e)?a.lanes=32:a.lanes=536870912,null}var _=c.children;return c=c.fallback,p?(Hr(),p=a.mode,_=Xc({mode:"hidden",children:_},p),c=pi(c,p,i,null),_.return=a,c.return=a,_.sibling=c,a.child=_,c=a.child,c.memoizedState=ld(i),c.childLanes=Sf(e,M,i),a.memoizedState=od,Vo(null,c)):(Qs(a),Fl(a,_))}var Z=e.memoizedState;if(Z!==null&&(_=Z.dehydrated,_!==null)){if(v)a.flags&256?(Qs(a),a.flags&=-257,a=Zc(e,a,i)):a.memoizedState!==null?(Hr(),a.child=e.child,a.flags|=128,a=null):(Hr(),_=c.fallback,p=a.mode,c=Xc({mode:"visible",children:c.children},p),_=pi(_,p,i,null),_.flags|=2,c.return=a,_.return=a,c.sibling=_,a.child=c,Ks(a,e.child,null,i),c=a.child,c.memoizedState=ld(i),c.childLanes=Sf(e,M,i),a.memoizedState=od,a=Vo(null,c));else if(Qs(a),cg(_)){if(M=_.nextSibling&&_.nextSibling.dataset,M)var we=M.dgst;M=we,c=Error(s(419)),c.stack="",c.digest=M,Ou({value:c,source:null,stack:null}),a=Zc(e,a,i)}else if(Zn||wl(e,a,i,!1),M=(i&e.childLanes)!==0,Zn||M){if(M=ut,M!==null&&(c=ot(M,i),c!==0&&c!==Z.retryLane))throw Z.retryLane=c,_n(e,c),ds(M,e,c),bf;lg(_)||np(),a=Zc(e,a,i)}else lg(_)?(a.flags|=192,a.child=e.child,a=null):(e=Z.treeContext,rn=ti(_.nextSibling),wa=a,Vt=!0,Fr=null,ct=!1,e!==null&&Qd(a,e),a=Fl(a,c.children),a.flags|=4096);return a}return p?(Hr(),_=c.fallback,p=a.mode,Z=e.child,we=Z.sibling,c=Cr(Z,{mode:"hidden",children:c.children}),c.subtreeFlags=Z.subtreeFlags&65011712,we!==null?_=Cr(we,_):(_=pi(_,p,i,null),_.flags|=2),_.return=a,c.return=a,c.sibling=_,a.child=c,Vo(null,c),c=a.child,_=e.child.memoizedState,_===null?_=ld(i):(p=_.cachePool,p!==null?(Z=aa._currentValue,p=p.parent!==Z?{parent:Z,pool:Z}:p):p=Bu(),_={baseLanes:_.baseLanes|i,cachePool:p}),c.memoizedState=_,c.childLanes=Sf(e,M,i),a.memoizedState=od,Vo(e.child,c)):(Qs(a),i=e.child,e=i.sibling,i=Cr(i,{mode:"visible",children:c.children}),i.return=a,i.sibling=null,e!==null&&(M=a.deletions,M===null?(a.deletions=[e],a.flags|=16):M.push(e)),a.child=i,a.memoizedState=null,i)}function Fl(e,a){return a=Xc({mode:"visible",children:a},e.mode),a.return=e,e.child=a}function Xc(e,a){return e=Jr(22,e,null,a),e.lanes=0,e}function Zc(e,a,i){return Ks(a,e.child,null,i),e=Fl(a,a.pendingProps.children),e.flags|=2,a.memoizedState=null,e}function ud(e,a,i){e.lanes|=a;var c=e.alternate;c!==null&&(c.lanes|=a),Wi(e.return,a,i)}function Ke(e,a,i,c,p,v){var M=e.memoizedState;M===null?e.memoizedState={isBackwards:a,rendering:null,renderingStartTime:0,last:c,tail:i,tailMode:p,treeForkCount:v}:(M.isBackwards=a,M.rendering=null,M.renderingStartTime=0,M.last=c,M.tail=i,M.tailMode=p,M.treeForkCount=v)}function Jc(e,a,i){var c=a.pendingProps,p=c.revealOrder,v=c.tail;c=c.children;var M=un.current,_=(M&2)!==0;if(_?(M=M&1|2,a.flags|=128):M&=1,Te(un,M),_a(e,a,c,i),c=Vt?Ec:0,!_&&e!==null&&(e.flags&128)!==0)e:for(e=a.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&ud(e,i,a);else if(e.tag===19)ud(e,i,a);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===a)break e;for(;e.sibling===null;){if(e.return===null||e.return===a)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}switch(p){case"forwards":for(i=a.child,p=null;i!==null;)e=i.alternate,e!==null&&Ys(e)===null&&(p=i),i=i.sibling;i=p,i===null?(p=a.child,a.child=null):(p=i.sibling,i.sibling=null),Ke(a,!1,p,i,v,c);break;case"backwards":case"unstable_legacy-backwards":for(i=null,p=a.child,a.child=null;p!==null;){if(e=p.alternate,e!==null&&Ys(e)===null){a.child=p;break}e=p.sibling,p.sibling=i,i=p,p=e}Ke(a,!0,i,null,v,c);break;case"together":Ke(a,!1,null,null,void 0,c);break;default:a.memoizedState=null}return a.child}function wi(e,a,i){if(e!==null&&(a.dependencies=e.dependencies),$l|=a.lanes,(i&a.childLanes)===0)if(e!==null){if(wl(e,a,i,!1),(i&a.childLanes)===0)return null}else return null;if(e!==null&&a.child!==e.child)throw Error(s(153));if(a.child!==null){for(e=a.child,i=Cr(e,e.pendingProps),a.child=i,i.return=a;e.sibling!==null;)e=e.sibling,i=i.sibling=Cr(e,e.pendingProps),i.return=a;i.sibling=null}return a.child}function Cf(e,a){return(e.lanes&a)!==0?!0:(e=e.dependencies,!!(e!==null&&Lo(e)))}function wy(e,a,i){switch(a.tag){case 3:Be(a,a.stateNode.containerInfo),ua(a,aa,e.memoizedState.cache),ns();break;case 27:case 5:Je(a);break;case 4:Be(a,a.stateNode.containerInfo);break;case 10:ua(a,a.type,a.memoizedProps.value);break;case 31:if(a.memoizedState!==null)return a.flags|=128,Ts(a),null;break;case 13:var c=a.memoizedState;if(c!==null)return c.dehydrated!==null?(Qs(a),a.flags|=128,null):(i&a.child.childLanes)!==0?cd(e,a,i):(Qs(a),e=wi(e,a,i),e!==null?e.sibling:null);Qs(a);break;case 19:var p=(e.flags&128)!==0;if(c=(i&a.childLanes)!==0,c||(wl(e,a,i,!1),c=(i&a.childLanes)!==0),p){if(c)return Jc(e,a,i);a.flags|=128}if(p=a.memoizedState,p!==null&&(p.rendering=null,p.tail=null,p.lastEffect=null),Te(un,un.current),c)break;return null;case 22:return a.lanes=0,wf(e,a,i,a.pendingProps);case 24:ua(a,aa,e.memoizedState.cache)}return wi(e,a,i)}function dd(e,a,i){if(e!==null)if(e.memoizedProps!==a.pendingProps)Zn=!0;else{if(!Cf(e,i)&&(a.flags&128)===0)return Zn=!1,wy(e,a,i);Zn=(e.flags&131072)!==0}else Zn=!1,Vt&&(a.flags&1048576)!==0&&jc(a,Ec,a.index);switch(a.lanes=0,a.tag){case 16:e:{var c=a.pendingProps;if(e=Ya(a.elementType),a.type=e,typeof e=="function")Kd(e)?(c=ao(e,c),a.tag=1,a=Yc(null,a,e,c,i)):(a.tag=0,a=id(null,a,e,c,i));else{if(e!=null){var p=e.$$typeof;if(p===H){a.tag=11,a=nd(null,a,e,c,i);break e}else if(p===D){a.tag=14,a=ad(null,a,e,c,i);break e}}throw a=he(e)||e,Error(s(306,a,""))}}return a;case 0:return id(e,a,a.type,a.pendingProps,i);case 1:return c=a.type,p=ao(c,a.pendingProps),Yc(e,a,c,p,i);case 3:e:{if(Be(a,a.stateNode.containerInfo),e===null)throw Error(s(387));c=a.pendingProps;var v=a.memoizedState;p=v.element,Ml(e,a),Pa(a,c,null,i);var M=a.memoizedState;if(c=M.cache,ua(a,aa,c),c!==v.cache&&Xd(a,[aa],i,!0),ka(),c=M.element,v.isDehydrated)if(v={element:c,isDehydrated:!1,cache:M.cache},a.updateQueue.baseState=v,a.memoizedState=v,a.flags&256){a=xf(e,a,c,i);break e}else if(c!==p){p=Or(Error(s(424)),a),Ou(p),a=xf(e,a,c,i);break e}else for(e=a.stateNode.containerInfo,e.nodeType===9?e=e.body:e=e.nodeName==="HTML"?e.ownerDocument.body:e,rn=ti(e.firstChild),wa=a,Vt=!0,Fr=null,ct=!0,i=Ph(a,null,c,i),a.child=i;i;)i.flags=i.flags&-3|4096,i=i.sibling;else{if(ns(),c===p){a=wi(e,a,i);break e}_a(e,a,c,i)}a=a.child}return a;case 26:return sd(e,a),e===null?(i=fb(a.type,null,a.pendingProps,null))?a.memoizedState=i:Vt||(i=a.type,e=a.pendingProps,c=cp(Ze.current).createElement(i),c[se]=a,c[ze]=e,hr(c,i,e),Ce(c),a.stateNode=c):a.memoizedState=fb(a.type,e.memoizedProps,a.pendingProps,e.memoizedState),null;case 27:return Je(a),e===null&&Vt&&(c=a.stateNode=cb(a.type,a.pendingProps,Ze.current),wa=a,ct=!0,p=rn,Vl(a.type)?(ug=p,rn=ti(c.firstChild)):rn=p),_a(e,a,a.pendingProps.children,i),sd(e,a),e===null&&(a.flags|=4194304),a.child;case 5:return e===null&&Vt&&((p=c=rn)&&(c=ck(c,a.type,a.pendingProps,ct),c!==null?(a.stateNode=c,wa=a,rn=ti(c.firstChild),ct=!1,p=!0):p=!1),p||xa(a)),Je(a),p=a.type,v=a.pendingProps,M=e!==null?e.memoizedProps:null,c=v.children,sg(p,v)?c=null:M!==null&&sg(p,M)&&(a.flags|=32),a.memoizedState!==null&&(p=Xi(e,a,_h,null,null,i),Ff._currentValue=p),sd(e,a),_a(e,a,c,i),a.child;case 6:return e===null&&Vt&&((e=i=rn)&&(i=uk(i,a.pendingProps,ct),i!==null?(a.stateNode=i,wa=a,rn=null,e=!0):e=!1),e||xa(a)),null;case 13:return cd(e,a,i);case 4:return Be(a,a.stateNode.containerInfo),c=a.pendingProps,e===null?a.child=Ks(a,null,c,i):_a(e,a,c,i),a.child;case 11:return nd(e,a,a.type,a.pendingProps,i);case 7:return _a(e,a,a.pendingProps,i),a.child;case 8:return _a(e,a,a.pendingProps.children,i),a.child;case 12:return _a(e,a,a.pendingProps.children,i),a.child;case 10:return c=a.pendingProps,ua(a,a.type,c.value),_a(e,a,c.children,i),a.child;case 9:return p=a.type._context,c=a.pendingProps.children,Gi(a),p=Sa(p),c=c(p),a.flags|=1,_a(e,a,c,i),a.child;case 14:return ad(e,a,a.type,a.pendingProps,i);case 15:return Ol(e,a,a.type,a.pendingProps,i);case 19:return Jc(e,a,i);case 31:return qm(e,a,i);case 22:return wf(e,a,i,a.pendingProps);case 24:return Gi(a),c=Sa(aa),e===null?(p=Jd(),p===null&&(p=ut,v=Dc(),p.pooledCache=v,v.refCount++,v!==null&&(p.pooledCacheLanes|=i),p=v),a.memoizedState={parent:c,cache:p},kl(a),ua(a,aa,p)):((e.lanes&i)!==0&&(Ml(e,a),Pa(a,null,null,i),ka()),p=e.memoizedState,v=a.memoizedState,p.parent!==c?(p={parent:c,cache:c},a.memoizedState=p,a.lanes===0&&(a.memoizedState=a.updateQueue.baseState=p),ua(a,aa,c)):(c=v.cache,ua(a,aa,c),c!==p.cache&&Xd(a,[aa],i,!0))),_a(e,a,a.pendingProps.children,i),a.child;case 29:throw a.pendingProps}throw Error(s(156,a.tag))}function os(e){e.flags|=4}function fa(e,a,i,c,p){if((a=(e.mode&32)!==0)&&(a=!1),a){if(e.flags|=16777216,(p&335544128)===p)if(e.stateNode.complete)e.flags|=8192;else if(Ny())e.flags|=8192;else throw _o=On,Pm}else e.flags&=-16777217}function Tr(e,a){if(a.type!=="stylesheet"||(a.state.loading&4)!==0)e.flags&=-16777217;else if(e.flags|=16777216,!vb(a))if(Ny())e.flags|=8192;else throw _o=On,Pm}function kt(e,a){a!==null&&(e.flags|=4),e.flags&16384&&(a=e.tag!==22?mt():536870912,e.lanes|=a,gd|=a)}function eu(e,a){if(!Vt)switch(e.tailMode){case"hidden":a=e.tail;for(var i=null;a!==null;)a.alternate!==null&&(i=a),a=a.sibling;i===null?e.tail=null:i.sibling=null;break;case"collapsed":i=e.tail;for(var c=null;i!==null;)i.alternate!==null&&(c=i),i=i.sibling;c===null?a||e.tail===null?e.tail=null:e.tail.sibling=null:c.sibling=null}}function dn(e){var a=e.alternate!==null&&e.alternate.child===e.child,i=0,c=0;if(a)for(var p=e.child;p!==null;)i|=p.lanes|p.childLanes,c|=p.subtreeFlags&65011712,c|=p.flags&65011712,p.return=e,p=p.sibling;else for(p=e.child;p!==null;)i|=p.lanes|p.childLanes,c|=p.subtreeFlags,c|=p.flags,p.return=e,p=p.sibling;return e.subtreeFlags|=c,e.childLanes=i,a}function Gm(e,a,i){var c=a.pendingProps;switch(Pu(a),a.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return dn(a),null;case 1:return dn(a),null;case 3:return i=a.stateNode,c=null,e!==null&&(c=e.memoizedState.cache),a.memoizedState.cache!==c&&(a.flags|=2048),Br(aa),Ve(),i.pendingContext&&(i.context=i.pendingContext,i.pendingContext=null),(e===null||e.child===null)&&(ts(a)?os(a):e===null||e.memoizedState.isDehydrated&&(a.flags&256)===0||(a.flags|=1024,bl())),dn(a),null;case 26:var p=a.type,v=a.memoizedState;return e===null?(os(a),v!==null?(dn(a),Tr(a,v)):(dn(a),fa(a,p,null,c,i))):v?v!==e.memoizedState?(os(a),dn(a),Tr(a,v)):(dn(a),a.flags&=-16777217):(e=e.memoizedProps,e!==c&&os(a),dn(a),fa(a,p,e,c,i)),null;case 27:if(Qe(a),i=Ze.current,p=a.type,e!==null&&a.stateNode!=null)e.memoizedProps!==c&&os(a);else{if(!c){if(a.stateNode===null)throw Error(s(166));return dn(a),null}e=Fe.current,ts(a)?Yd(a):(e=cb(p,c,i),a.stateNode=e,os(a))}return dn(a),null;case 5:if(Qe(a),p=a.type,e!==null&&a.stateNode!=null)e.memoizedProps!==c&&os(a);else{if(!c){if(a.stateNode===null)throw Error(s(166));return dn(a),null}if(v=Fe.current,ts(a))Yd(a);else{var M=cp(Ze.current);switch(v){case 1:v=M.createElementNS("http://www.w3.org/2000/svg",p);break;case 2:v=M.createElementNS("http://www.w3.org/1998/Math/MathML",p);break;default:switch(p){case"svg":v=M.createElementNS("http://www.w3.org/2000/svg",p);break;case"math":v=M.createElementNS("http://www.w3.org/1998/Math/MathML",p);break;case"script":v=M.createElement("div"),v.innerHTML="<script><\/script>",v=v.removeChild(v.firstChild);break;case"select":v=typeof c.is=="string"?M.createElement("select",{is:c.is}):M.createElement("select"),c.multiple?v.multiple=!0:c.size&&(v.size=c.size);break;default:v=typeof c.is=="string"?M.createElement(p,{is:c.is}):M.createElement(p)}}v[se]=a,v[ze]=c;e:for(M=a.child;M!==null;){if(M.tag===5||M.tag===6)v.appendChild(M.stateNode);else if(M.tag!==4&&M.tag!==27&&M.child!==null){M.child.return=M,M=M.child;continue}if(M===a)break e;for(;M.sibling===null;){if(M.return===null||M.return===a)break e;M=M.return}M.sibling.return=M.return,M=M.sibling}a.stateNode=v;e:switch(hr(v,p,c),p){case"button":case"input":case"select":case"textarea":c=!!c.autoFocus;break e;case"img":c=!0;break e;default:c=!1}c&&os(a)}}return dn(a),fa(a,a.type,e===null?null:e.memoizedProps,a.pendingProps,i),null;case 6:if(e&&a.stateNode!=null)e.memoizedProps!==c&&os(a);else{if(typeof c!="string"&&a.stateNode===null)throw Error(s(166));if(e=Ze.current,ts(a)){if(e=a.stateNode,i=a.memoizedProps,c=null,p=wa,p!==null)switch(p.tag){case 27:case 5:c=p.memoizedProps}e[se]=a,e=!!(e.nodeValue===i||c!==null&&c.suppressHydrationWarning===!0||Zy(e.nodeValue,i)),e||xa(a,!0)}else e=cp(e).createTextNode(c),e[se]=a,a.stateNode=e}return dn(a),null;case 31:if(i=a.memoizedState,e===null||e.memoizedState!==null){if(c=ts(a),i!==null){if(e===null){if(!c)throw Error(s(318));if(e=a.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(s(557));e[se]=a}else ns(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;dn(a),e=!1}else i=bl(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=i),e=!0;if(!e)return a.flags&256?(Gn(a),a):(Gn(a),null);if((a.flags&128)!==0)throw Error(s(558))}return dn(a),null;case 13:if(c=a.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(p=ts(a),c!==null&&c.dehydrated!==null){if(e===null){if(!p)throw Error(s(318));if(p=a.memoizedState,p=p!==null?p.dehydrated:null,!p)throw Error(s(317));p[se]=a}else ns(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;dn(a),p=!1}else p=bl(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=p),p=!0;if(!p)return a.flags&256?(Gn(a),a):(Gn(a),null)}return Gn(a),(a.flags&128)!==0?(a.lanes=i,a):(i=c!==null,e=e!==null&&e.memoizedState!==null,i&&(c=a.child,p=null,c.alternate!==null&&c.alternate.memoizedState!==null&&c.alternate.memoizedState.cachePool!==null&&(p=c.alternate.memoizedState.cachePool.pool),v=null,c.memoizedState!==null&&c.memoizedState.cachePool!==null&&(v=c.memoizedState.cachePool.pool),v!==p&&(c.flags|=2048)),i!==e&&i&&(a.child.flags|=8192),kt(a,a.updateQueue),dn(a),null);case 4:return Ve(),e===null&&eg(a.stateNode.containerInfo),dn(a),null;case 10:return Br(a.type),dn(a),null;case 19:if(ce(un),c=a.memoizedState,c===null)return dn(a),null;if(p=(a.flags&128)!==0,v=c.rendering,v===null)if(p)eu(c,!1);else{if(ia!==0||e!==null&&(e.flags&128)!==0)for(e=a.child;e!==null;){if(v=Ys(e),v!==null){for(a.flags|=128,eu(c,!1),e=v.updateQueue,a.updateQueue=e,kt(a,e),a.subtreeFlags=0,e=i,i=a.child;i!==null;)Rm(i,e),i=i.sibling;return Te(un,un.current&1|2),Vt&&es(a,c.treeForkCount),a.child}e=e.sibling}c.tail!==null&&B()>Jm&&(a.flags|=128,p=!0,eu(c,!1),a.lanes=4194304)}else{if(!p)if(e=Ys(v),e!==null){if(a.flags|=128,p=!0,e=e.updateQueue,a.updateQueue=e,kt(a,e),eu(c,!0),c.tail===null&&c.tailMode==="hidden"&&!v.alternate&&!Vt)return dn(a),null}else 2*B()-c.renderingStartTime>Jm&&i!==536870912&&(a.flags|=128,p=!0,eu(c,!1),a.lanes=4194304);c.isBackwards?(v.sibling=a.child,a.child=v):(e=c.last,e!==null?e.sibling=v:a.child=v,c.last=v)}return c.tail!==null?(e=c.tail,c.rendering=e,c.tail=e.sibling,c.renderingStartTime=B(),e.sibling=null,i=un.current,Te(un,p?i&1|2:i&1),Vt&&es(a,c.treeForkCount),e):(dn(a),null);case 22:case 23:return Gn(a),Yi(),c=a.memoizedState!==null,e!==null?e.memoizedState!==null!==c&&(a.flags|=8192):c&&(a.flags|=8192),c?(i&536870912)!==0&&(a.flags&128)===0&&(dn(a),a.subtreeFlags&6&&(a.flags|=8192)):dn(a),i=a.updateQueue,i!==null&&kt(a,i.retryQueue),i=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(i=e.memoizedState.cachePool.pool),c=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(c=a.memoizedState.cachePool.pool),c!==i&&(a.flags|=2048),e!==null&&ce(Vi),null;case 24:return i=null,e!==null&&(i=e.memoizedState.cache),a.memoizedState.cache!==i&&(a.flags|=2048),Br(aa),dn(a),null;case 25:return null;case 30:return null}throw Error(s(156,a.tag))}function Vm(e,a){switch(Pu(a),a.tag){case 1:return e=a.flags,e&65536?(a.flags=e&-65537|128,a):null;case 3:return Br(aa),Ve(),e=a.flags,(e&65536)!==0&&(e&128)===0?(a.flags=e&-65537|128,a):null;case 26:case 27:case 5:return Qe(a),null;case 31:if(a.memoizedState!==null){if(Gn(a),a.alternate===null)throw Error(s(340));ns()}return e=a.flags,e&65536?(a.flags=e&-65537|128,a):null;case 13:if(Gn(a),e=a.memoizedState,e!==null&&e.dehydrated!==null){if(a.alternate===null)throw Error(s(340));ns()}return e=a.flags,e&65536?(a.flags=e&-65537|128,a):null;case 19:return ce(un),null;case 4:return Ve(),null;case 10:return Br(a.type),null;case 22:case 23:return Gn(a),Yi(),e!==null&&ce(Vi),e=a.flags,e&65536?(a.flags=e&-65537|128,a):null;case 24:return Br(aa),null;case 25:return null;default:return null}}function Ko(e,a){switch(Pu(a),a.tag){case 3:Br(aa),Ve();break;case 26:case 27:case 5:Qe(a);break;case 4:Ve();break;case 31:a.memoizedState!==null&&Gn(a);break;case 13:Gn(a);break;case 19:ce(un);break;case 10:Br(a.type);break;case 22:case 23:Gn(a),Yi(),e!==null&&ce(Vi);break;case 24:Br(aa)}}function Bl(e,a){try{var i=a.updateQueue,c=i!==null?i.lastEffect:null;if(c!==null){var p=c.next;i=p;do{if((i.tag&e)===e){c=void 0;var v=i.create,M=i.inst;c=v(),M.destroy=c}i=i.next}while(i!==p)}}catch(_){xn(a,a.return,_)}}function xi(e,a,i){try{var c=a.updateQueue,p=c!==null?c.lastEffect:null;if(p!==null){var v=p.next;c=v;do{if((c.tag&e)===e){var M=c.inst,_=M.destroy;if(_!==void 0){M.destroy=void 0,p=a;var Z=i,we=_;try{we()}catch(Re){xn(p,Z,Re)}}}c=c.next}while(c!==v)}}catch(Re){xn(a,a.return,Re)}}function kf(e){var a=e.updateQueue;if(a!==null){var i=e.stateNode;try{Om(a,i)}catch(c){xn(e,e.return,c)}}}function Mf(e,a,i){i.props=ao(e.type,e.memoizedProps),i.state=e.memoizedState;try{i.componentWillUnmount()}catch(c){xn(e,a,c)}}function Hl(e,a){try{var i=e.ref;if(i!==null){switch(e.tag){case 26:case 27:case 5:var c=e.stateNode;break;case 30:c=e.stateNode;break;default:c=e.stateNode}typeof i=="function"?e.refCleanup=i(c):i.current=c}}catch(p){xn(e,a,p)}}function pr(e,a){var i=e.ref,c=e.refCleanup;if(i!==null)if(typeof c=="function")try{c()}catch(p){xn(e,a,p)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof i=="function")try{i(null)}catch(p){xn(e,a,p)}else i.current=null}function zl(e){var a=e.type,i=e.memoizedProps,c=e.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":i.autoFocus&&c.focus();break e;case"img":i.src?c.src=i.src:i.srcSet&&(c.srcset=i.srcSet)}}catch(p){xn(e,e.return,p)}}function Af(e,a,i){try{var c=e.stateNode;ak(c,e.type,i,a),c[ze]=a}catch(p){xn(e,e.return,p)}}function Tf(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&Vl(e.type)||e.tag===4}function tu(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Tf(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&Vl(e.type)||e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Nf(e,a,i){var c=e.tag;if(c===5||c===6)e=e.stateNode,a?(i.nodeType===9?i.body:i.nodeName==="HTML"?i.ownerDocument.body:i).insertBefore(e,a):(a=i.nodeType===9?i.body:i.nodeName==="HTML"?i.ownerDocument.body:i,a.appendChild(e),i=i._reactRootContainer,i!=null||a.onclick!==null||(a.onclick=ys));else if(c!==4&&(c===27&&Vl(e.type)&&(i=e.stateNode,a=null),e=e.child,e!==null))for(Nf(e,a,i),e=e.sibling;e!==null;)Nf(e,a,i),e=e.sibling}function fd(e,a,i){var c=e.tag;if(c===5||c===6)e=e.stateNode,a?i.insertBefore(e,a):i.appendChild(e);else if(c!==4&&(c===27&&Vl(e.type)&&(i=e.stateNode),e=e.child,e!==null))for(fd(e,a,i),e=e.sibling;e!==null;)fd(e,a,i),e=e.sibling}function md(e){var a=e.stateNode,i=e.memoizedProps;try{for(var c=e.type,p=a.attributes;p.length;)a.removeAttributeNode(p[0]);hr(a,c,i),a[se]=e,a[ze]=i}catch(v){xn(e,e.return,v)}}var Zs=!1,sa=!1,Oa=!1,nu=typeof WeakSet=="function"?WeakSet:Set,Aa=null;function xy(e,a){if(e=e.containerInfo,ag=gp,e=Hi(e),zi(e)){if("selectionStart"in e)var i={start:e.selectionStart,end:e.selectionEnd};else e:{i=(i=e.ownerDocument)&&i.defaultView||window;var c=i.getSelection&&i.getSelection();if(c&&c.rangeCount!==0){i=c.anchorNode;var p=c.anchorOffset,v=c.focusNode;c=c.focusOffset;try{i.nodeType,v.nodeType}catch{i=null;break e}var M=0,_=-1,Z=-1,we=0,Re=0,_e=e,xe=null;t:for(;;){for(var ke;_e!==i||p!==0&&_e.nodeType!==3||(_=M+p),_e!==v||c!==0&&_e.nodeType!==3||(Z=M+c),_e.nodeType===3&&(M+=_e.nodeValue.length),(ke=_e.firstChild)!==null;)xe=_e,_e=ke;for(;;){if(_e===e)break t;if(xe===i&&++we===p&&(_=M),xe===v&&++Re===c&&(Z=M),(ke=_e.nextSibling)!==null)break;_e=xe,xe=_e.parentNode}_e=ke}i=_===-1||Z===-1?null:{start:_,end:Z}}else i=null}i=i||{start:0,end:0}}else i=null;for(rg={focusedElem:e,selectionRange:i},gp=!1,Aa=a;Aa!==null;)if(a=Aa,e=a.child,(a.subtreeFlags&1028)!==0&&e!==null)e.return=a,Aa=e;else for(;Aa!==null;){switch(a=Aa,v=a.alternate,e=a.flags,a.tag){case 0:if((e&4)!==0&&(e=a.updateQueue,e=e!==null?e.events:null,e!==null))for(i=0;i<e.length;i++)p=e[i],p.ref.impl=p.nextImpl;break;case 11:case 15:break;case 1:if((e&1024)!==0&&v!==null){e=void 0,i=a,p=v.memoizedProps,v=v.memoizedState,c=i.stateNode;try{var dt=ao(i.type,p);e=c.getSnapshotBeforeUpdate(dt,v),c.__reactInternalSnapshotBeforeUpdate=e}catch(Dt){xn(i,i.return,Dt)}}break;case 3:if((e&1024)!==0){if(e=a.stateNode.containerInfo,i=e.nodeType,i===9)og(e);else if(i===1)switch(e.nodeName){case"HEAD":case"HTML":case"BODY":og(e);break;default:e.textContent=""}}break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if((e&1024)!==0)throw Error(s(163))}if(e=a.sibling,e!==null){e.return=a.return,Aa=e;break}Aa=a.return}}function Km(e,a,i){var c=i.flags;switch(i.tag){case 0:case 11:case 15:Si(e,i),c&4&&Bl(5,i);break;case 1:if(Si(e,i),c&4)if(e=i.stateNode,a===null)try{e.componentDidMount()}catch(M){xn(i,i.return,M)}else{var p=ao(i.type,a.memoizedProps);a=a.memoizedState;try{e.componentDidUpdate(p,a,e.__reactInternalSnapshotBeforeUpdate)}catch(M){xn(i,i.return,M)}}c&64&&kf(i),c&512&&Hl(i,i.return);break;case 3:if(Si(e,i),c&64&&(e=i.updateQueue,e!==null)){if(a=null,i.child!==null)switch(i.child.tag){case 27:case 5:a=i.child.stateNode;break;case 1:a=i.child.stateNode}try{Om(e,a)}catch(M){xn(i,i.return,M)}}break;case 27:a===null&&c&4&&md(i);case 26:case 5:Si(e,i),a===null&&c&4&&zl(i),c&512&&Hl(i,i.return);break;case 12:Si(e,i);break;case 31:Si(e,i),c&4&&Ym(e,i);break;case 13:Si(e,i),c&4&&Xm(e,i),c&64&&(e=i.memoizedState,e!==null&&(e=e.dehydrated,e!==null&&(i=WC.bind(null,i),dk(e,i))));break;case 22:if(c=i.memoizedState!==null||Zs,!c){a=a!==null&&a.memoizedState!==null||sa,p=Zs;var v=sa;Zs=c,(sa=a)&&!v?Ci(e,i,(i.subtreeFlags&8772)!==0):Si(e,i),Zs=p,sa=v}break;case 30:break;default:Si(e,i)}}function Qm(e){var a=e.alternate;a!==null&&(e.alternate=null,Qm(a)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(a=e.stateNode,a!==null&&In(a)),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}var Dn=null,Fa=!1;function Ur(e,a,i){for(i=i.child;i!==null;)Rf(e,a,i),i=i.sibling}function Rf(e,a,i){if(fe&&typeof fe.onCommitFiberUnmount=="function")try{fe.onCommitFiberUnmount(ae,i)}catch{}switch(i.tag){case 26:sa||pr(i,a),Ur(e,a,i),i.memoizedState?i.memoizedState.count--:i.stateNode&&(i=i.stateNode,i.parentNode.removeChild(i));break;case 27:sa||pr(i,a);var c=Dn,p=Fa;Vl(i.type)&&(Dn=i.stateNode,Fa=!1),Ur(e,a,i),Pf(i.stateNode),Dn=c,Fa=p;break;case 5:sa||pr(i,a);case 6:if(c=Dn,p=Fa,Dn=null,Ur(e,a,i),Dn=c,Fa=p,Dn!==null)if(Fa)try{(Dn.nodeType===9?Dn.body:Dn.nodeName==="HTML"?Dn.ownerDocument.body:Dn).removeChild(i.stateNode)}catch(v){xn(i,a,v)}else try{Dn.removeChild(i.stateNode)}catch(v){xn(i,a,v)}break;case 18:Dn!==null&&(Fa?(e=Dn,rb(e.nodeType===9?e.body:e.nodeName==="HTML"?e.ownerDocument.body:e,i.stateNode),kd(e)):rb(Dn,i.stateNode));break;case 4:c=Dn,p=Fa,Dn=i.stateNode.containerInfo,Fa=!0,Ur(e,a,i),Dn=c,Fa=p;break;case 0:case 11:case 14:case 15:xi(2,i,a),sa||xi(4,i,a),Ur(e,a,i);break;case 1:sa||(pr(i,a),c=i.stateNode,typeof c.componentWillUnmount=="function"&&Mf(i,a,c)),Ur(e,a,i);break;case 21:Ur(e,a,i);break;case 22:sa=(c=sa)||i.memoizedState!==null,Ur(e,a,i),sa=c;break;default:Ur(e,a,i)}}function Ym(e,a){if(a.memoizedState===null&&(e=a.alternate,e!==null&&(e=e.memoizedState,e!==null))){e=e.dehydrated;try{kd(e)}catch(i){xn(a,a.return,i)}}}function Xm(e,a){if(a.memoizedState===null&&(e=a.alternate,e!==null&&(e=e.memoizedState,e!==null&&(e=e.dehydrated,e!==null))))try{kd(e)}catch(i){xn(a,a.return,i)}}function Bh(e){switch(e.tag){case 31:case 13:case 19:var a=e.stateNode;return a===null&&(a=e.stateNode=new nu),a;case 22:return e=e.stateNode,a=e._retryCache,a===null&&(a=e._retryCache=new nu),a;default:throw Error(s(435,e.tag))}}function Js(e,a){var i=Bh(e);a.forEach(function(c){if(!i.has(c)){i.add(c);var p=GC.bind(null,e,c);c.then(p,p)}})}function Hn(e,a){var i=a.deletions;if(i!==null)for(var c=0;c<i.length;c++){var p=i[c],v=e,M=a,_=M;e:for(;_!==null;){switch(_.tag){case 27:if(Vl(_.type)){Dn=_.stateNode,Fa=!1;break e}break;case 5:Dn=_.stateNode,Fa=!1;break e;case 3:case 4:Dn=_.stateNode.containerInfo,Fa=!0;break e}_=_.return}if(Dn===null)throw Error(s(160));Rf(v,M,p),Dn=null,Fa=!1,v=p.alternate,v!==null&&(v.return=null),p.return=null}if(a.subtreeFlags&13886)for(a=a.child;a!==null;)so(a,e),a=a.sibling}var ls=null;function so(e,a){var i=e.alternate,c=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:Hn(a,e),Ja(e),c&4&&(xi(3,e,e.return),Bl(3,e),xi(5,e,e.return));break;case 1:Hn(a,e),Ja(e),c&512&&(sa||i===null||pr(i,i.return)),c&64&&Zs&&(e=e.updateQueue,e!==null&&(c=e.callbacks,c!==null&&(i=e.shared.hiddenCallbacks,e.shared.hiddenCallbacks=i===null?c:i.concat(c))));break;case 26:var p=ls;if(Hn(a,e),Ja(e),c&512&&(sa||i===null||pr(i,i.return)),c&4){var v=i!==null?i.memoizedState:null;if(c=e.memoizedState,i===null)if(c===null)if(e.stateNode===null){e:{c=e.type,i=e.memoizedProps,p=p.ownerDocument||p;t:switch(c){case"title":v=p.getElementsByTagName("title")[0],(!v||v[Jt]||v[se]||v.namespaceURI==="http://www.w3.org/2000/svg"||v.hasAttribute("itemprop"))&&(v=p.createElement(c),p.head.insertBefore(v,p.querySelector("head > title"))),hr(v,c,i),v[se]=e,Ce(v),c=v;break e;case"link":var M=hb("link","href",p).get(c+(i.href||""));if(M){for(var _=0;_<M.length;_++)if(v=M[_],v.getAttribute("href")===(i.href==null||i.href===""?null:i.href)&&v.getAttribute("rel")===(i.rel==null?null:i.rel)&&v.getAttribute("title")===(i.title==null?null:i.title)&&v.getAttribute("crossorigin")===(i.crossOrigin==null?null:i.crossOrigin)){M.splice(_,1);break t}}v=p.createElement(c),hr(v,c,i),p.head.appendChild(v);break;case"meta":if(M=hb("meta","content",p).get(c+(i.content||""))){for(_=0;_<M.length;_++)if(v=M[_],v.getAttribute("content")===(i.content==null?null:""+i.content)&&v.getAttribute("name")===(i.name==null?null:i.name)&&v.getAttribute("property")===(i.property==null?null:i.property)&&v.getAttribute("http-equiv")===(i.httpEquiv==null?null:i.httpEquiv)&&v.getAttribute("charset")===(i.charSet==null?null:i.charSet)){M.splice(_,1);break t}}v=p.createElement(c),hr(v,c,i),p.head.appendChild(v);break;default:throw Error(s(468,c))}v[se]=e,Ce(v),c=v}e.stateNode=c}else gb(p,e.type,e.stateNode);else e.stateNode=pb(p,c,e.memoizedProps);else v!==c?(v===null?i.stateNode!==null&&(i=i.stateNode,i.parentNode.removeChild(i)):v.count--,c===null?gb(p,e.type,e.stateNode):pb(p,c,e.memoizedProps)):c===null&&e.stateNode!==null&&Af(e,e.memoizedProps,i.memoizedProps)}break;case 27:Hn(a,e),Ja(e),c&512&&(sa||i===null||pr(i,i.return)),i!==null&&c&4&&Af(e,e.memoizedProps,i.memoizedProps);break;case 5:if(Hn(a,e),Ja(e),c&512&&(sa||i===null||pr(i,i.return)),e.flags&32){p=e.stateNode;try{qr(p,"")}catch(dt){xn(e,e.return,dt)}}c&4&&e.stateNode!=null&&(p=e.memoizedProps,Af(e,p,i!==null?i.memoizedProps:p)),c&1024&&(Oa=!0);break;case 6:if(Hn(a,e),Ja(e),c&4){if(e.stateNode===null)throw Error(s(162));c=e.memoizedProps,i=e.stateNode;try{i.nodeValue=c}catch(dt){xn(e,e.return,dt)}}break;case 3:if(fp=null,p=ls,ls=up(a.containerInfo),Hn(a,e),ls=p,Ja(e),c&4&&i!==null&&i.memoizedState.isDehydrated)try{kd(a.containerInfo)}catch(dt){xn(e,e.return,dt)}Oa&&(Oa=!1,pd(e));break;case 4:c=ls,ls=up(e.stateNode.containerInfo),Hn(a,e),Ja(e),ls=c;break;case 12:Hn(a,e),Ja(e);break;case 31:Hn(a,e),Ja(e),c&4&&(c=e.updateQueue,c!==null&&(e.updateQueue=null,Js(e,c)));break;case 13:Hn(a,e),Ja(e),e.child.flags&8192&&e.memoizedState!==null!=(i!==null&&i.memoizedState!==null)&&(Zm=B()),c&4&&(c=e.updateQueue,c!==null&&(e.updateQueue=null,Js(e,c)));break;case 22:p=e.memoizedState!==null;var Z=i!==null&&i.memoizedState!==null,we=Zs,Re=sa;if(Zs=we||p,sa=Re||Z,Hn(a,e),sa=Re,Zs=we,Ja(e),c&8192)e:for(a=e.stateNode,a._visibility=p?a._visibility&-2:a._visibility|1,p&&(i===null||Z||Zs||sa||Qo(e)),i=null,a=e;;){if(a.tag===5||a.tag===26){if(i===null){Z=i=a;try{if(v=Z.stateNode,p)M=v.style,typeof M.setProperty=="function"?M.setProperty("display","none","important"):M.display="none";else{_=Z.stateNode;var _e=Z.memoizedProps.style,xe=_e!=null&&_e.hasOwnProperty("display")?_e.display:null;_.style.display=xe==null||typeof xe=="boolean"?"":(""+xe).trim()}}catch(dt){xn(Z,Z.return,dt)}}}else if(a.tag===6){if(i===null){Z=a;try{Z.stateNode.nodeValue=p?"":Z.memoizedProps}catch(dt){xn(Z,Z.return,dt)}}}else if(a.tag===18){if(i===null){Z=a;try{var ke=Z.stateNode;p?sb(ke,!0):sb(Z.stateNode,!1)}catch(dt){xn(Z,Z.return,dt)}}}else if((a.tag!==22&&a.tag!==23||a.memoizedState===null||a===e)&&a.child!==null){a.child.return=a,a=a.child;continue}if(a===e)break e;for(;a.sibling===null;){if(a.return===null||a.return===e)break e;i===a&&(i=null),a=a.return}i===a&&(i=null),a.sibling.return=a.return,a=a.sibling}c&4&&(c=e.updateQueue,c!==null&&(i=c.retryQueue,i!==null&&(c.retryQueue=null,Js(e,i))));break;case 19:Hn(a,e),Ja(e),c&4&&(c=e.updateQueue,c!==null&&(e.updateQueue=null,Js(e,c)));break;case 30:break;case 21:break;default:Hn(a,e),Ja(e)}}function Ja(e){var a=e.flags;if(a&2){try{for(var i,c=e.return;c!==null;){if(Tf(c)){i=c;break}c=c.return}if(i==null)throw Error(s(160));switch(i.tag){case 27:var p=i.stateNode,v=tu(e);fd(e,v,p);break;case 5:var M=i.stateNode;i.flags&32&&(qr(M,""),i.flags&=-33);var _=tu(e);fd(e,_,M);break;case 3:case 4:var Z=i.stateNode.containerInfo,we=tu(e);Nf(e,we,Z);break;default:throw Error(s(161))}}catch(Re){xn(e,e.return,Re)}e.flags&=-3}a&4096&&(e.flags&=-4097)}function pd(e){if(e.subtreeFlags&1024)for(e=e.child;e!==null;){var a=e;pd(a),a.tag===5&&a.flags&1024&&a.stateNode.reset(),e=e.sibling}}function Si(e,a){if(a.subtreeFlags&8772)for(a=a.child;a!==null;)Km(e,a.alternate,a),a=a.sibling}function Qo(e){for(e=e.child;e!==null;){var a=e;switch(a.tag){case 0:case 11:case 14:case 15:xi(4,a,a.return),Qo(a);break;case 1:pr(a,a.return);var i=a.stateNode;typeof i.componentWillUnmount=="function"&&Mf(a,a.return,i),Qo(a);break;case 27:Pf(a.stateNode);case 26:case 5:pr(a,a.return),Qo(a);break;case 22:a.memoizedState===null&&Qo(a);break;case 30:Qo(a);break;default:Qo(a)}e=e.sibling}}function Ci(e,a,i){for(i=i&&(a.subtreeFlags&8772)!==0,a=a.child;a!==null;){var c=a.alternate,p=e,v=a,M=v.flags;switch(v.tag){case 0:case 11:case 15:Ci(p,v,i),Bl(4,v);break;case 1:if(Ci(p,v,i),c=v,p=c.stateNode,typeof p.componentDidMount=="function")try{p.componentDidMount()}catch(we){xn(c,c.return,we)}if(c=v,p=c.updateQueue,p!==null){var _=c.stateNode;try{var Z=p.shared.hiddenCallbacks;if(Z!==null)for(p.shared.hiddenCallbacks=null,p=0;p<Z.length;p++)tf(Z[p],_)}catch(we){xn(c,c.return,we)}}i&&M&64&&kf(v),Hl(v,v.return);break;case 27:md(v);case 26:case 5:Ci(p,v,i),i&&c===null&&M&4&&zl(v),Hl(v,v.return);break;case 12:Ci(p,v,i);break;case 31:Ci(p,v,i),i&&M&4&&Ym(p,v);break;case 13:Ci(p,v,i),i&&M&4&&Xm(p,v);break;case 22:v.memoizedState===null&&Ci(p,v,i),Hl(v,v.return);break;case 30:break;default:Ci(p,v,i)}a=a.sibling}}function hd(e,a){var i=null;e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(i=e.memoizedState.cachePool.pool),e=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(e=a.memoizedState.cachePool.pool),e!==i&&(e!=null&&e.refCount++,i!=null&&ks(i))}function m(e,a){e=null,a.alternate!==null&&(e=a.alternate.memoizedState.cache),a=a.memoizedState.cache,a!==e&&(a.refCount++,e!=null&&ks(e))}function x(e,a,i,c){if(a.subtreeFlags&10256)for(a=a.child;a!==null;)C(e,a,i,c),a=a.sibling}function C(e,a,i,c){var p=a.flags;switch(a.tag){case 0:case 11:case 15:x(e,a,i,c),p&2048&&Bl(9,a);break;case 1:x(e,a,i,c);break;case 3:x(e,a,i,c),p&2048&&(e=null,a.alternate!==null&&(e=a.alternate.memoizedState.cache),a=a.memoizedState.cache,a!==e&&(a.refCount++,e!=null&&ks(e)));break;case 12:if(p&2048){x(e,a,i,c),e=a.stateNode;try{var v=a.memoizedProps,M=v.id,_=v.onPostCommit;typeof _=="function"&&_(M,a.alternate===null?"mount":"update",e.passiveEffectDuration,-0)}catch(Z){xn(a,a.return,Z)}}else x(e,a,i,c);break;case 31:x(e,a,i,c);break;case 13:x(e,a,i,c);break;case 23:break;case 22:v=a.stateNode,M=a.alternate,a.memoizedState!==null?v._visibility&2?x(e,a,i,c):E(e,a):v._visibility&2?x(e,a,i,c):(v._visibility|=2,R(e,a,i,c,(a.subtreeFlags&10256)!==0||!1)),p&2048&&hd(M,a);break;case 24:x(e,a,i,c),p&2048&&m(a.alternate,a);break;default:x(e,a,i,c)}}function R(e,a,i,c,p){for(p=p&&((a.subtreeFlags&10256)!==0||!1),a=a.child;a!==null;){var v=e,M=a,_=i,Z=c,we=M.flags;switch(M.tag){case 0:case 11:case 15:R(v,M,_,Z,p),Bl(8,M);break;case 23:break;case 22:var Re=M.stateNode;M.memoizedState!==null?Re._visibility&2?R(v,M,_,Z,p):E(v,M):(Re._visibility|=2,R(v,M,_,Z,p)),p&&we&2048&&hd(M.alternate,M);break;case 24:R(v,M,_,Z,p),p&&we&2048&&m(M.alternate,M);break;default:R(v,M,_,Z,p)}a=a.sibling}}function E(e,a){if(a.subtreeFlags&10256)for(a=a.child;a!==null;){var i=e,c=a,p=c.flags;switch(c.tag){case 22:E(i,c),p&2048&&hd(c.alternate,c);break;case 24:E(i,c),p&2048&&m(c.alternate,c);break;default:E(i,c)}a=a.sibling}}var X=8192;function Q(e,a,i){if(e.subtreeFlags&X)for(e=e.child;e!==null;)te(e,a,i),e=e.sibling}function te(e,a,i){switch(e.tag){case 26:Q(e,a,i),e.flags&X&&e.memoizedState!==null&&Ck(i,ls,e.memoizedState,e.memoizedProps);break;case 5:Q(e,a,i);break;case 3:case 4:var c=ls;ls=up(e.stateNode.containerInfo),Q(e,a,i),ls=c;break;case 22:e.memoizedState===null&&(c=e.alternate,c!==null&&c.memoizedState!==null?(c=X,X=16777216,Q(e,a,i),X=c):Q(e,a,i));break;default:Q(e,a,i)}}function oe(e){var a=e.alternate;if(a!==null&&(e=a.child,e!==null)){a.child=null;do a=e.sibling,e.sibling=null,e=a;while(e!==null)}}function ie(e){var a=e.deletions;if((e.flags&16)!==0){if(a!==null)for(var i=0;i<a.length;i++){var c=a[i];Aa=c,Ie(c,e)}oe(e)}if(e.subtreeFlags&10256)for(e=e.child;e!==null;)nt(e),e=e.sibling}function nt(e){switch(e.tag){case 0:case 11:case 15:ie(e),e.flags&2048&&xi(9,e,e.return);break;case 3:ie(e);break;case 12:ie(e);break;case 22:var a=e.stateNode;e.memoizedState!==null&&a._visibility&2&&(e.return===null||e.return.tag!==13)?(a._visibility&=-3,Ye(e)):ie(e);break;default:ie(e)}}function Ye(e){var a=e.deletions;if((e.flags&16)!==0){if(a!==null)for(var i=0;i<a.length;i++){var c=a[i];Aa=c,Ie(c,e)}oe(e)}for(e=e.child;e!==null;){switch(a=e,a.tag){case 0:case 11:case 15:xi(8,a,a.return),Ye(a);break;case 22:i=a.stateNode,i._visibility&2&&(i._visibility&=-3,Ye(a));break;default:Ye(a)}e=e.sibling}}function Ie(e,a){for(;Aa!==null;){var i=Aa;switch(i.tag){case 0:case 11:case 15:xi(8,i,a);break;case 23:case 22:if(i.memoizedState!==null&&i.memoizedState.cachePool!==null){var c=i.memoizedState.cachePool.pool;c!=null&&c.refCount++}break;case 24:ks(i.memoizedState.cache)}if(c=i.child,c!==null)c.return=i,Aa=c;else e:for(i=e;Aa!==null;){c=Aa;var p=c.sibling,v=c.return;if(Qm(c),c===i){Aa=null;break e}if(p!==null){p.return=v,Aa=p;break e}Aa=v}}}var Nt={getCacheForType:function(e){var a=Sa(aa),i=a.data.get(e);return i===void 0&&(i=e(),a.data.set(e,i)),i},cacheSignal:function(){return Sa(aa).controller.signal}},Yt=typeof WeakMap=="function"?WeakMap:Map,tt=0,ut=null,pt=null,It=0,en=0,Ba=null,ei=!1,Yo=!1,cs=!1,js=0,ia=0,$l=0,au=0,Hh=0,Ds=0,gd=0,Ef=null,us=null,zh=!1,Zm=0,Sy=0,Jm=1/0,ep=null,Ul=null,Ha=0,ql=null,vd=null,Xo=0,$h=0,Uh=null,Cy=null,jf=0,qh=null;function Is(){return(tt&2)!==0&&It!==0?It&-It:U.T!==null?Yh():Dr()}function ky(){if(Ds===0)if((It&536870912)===0||Vt){var e=jt;jt<<=1,(jt&3932160)===0&&(jt=262144),Ds=e}else Ds=536870912;return e=Za.current,e!==null&&(e.flags|=32),Ds}function ds(e,a,i){(e===ut&&(en===2||en===9)||e.cancelPendingCommit!==null)&&(yd(e,0),Wl(e,It,Ds,!1)),hn(e,i),((tt&2)===0||e!==ut)&&(e===ut&&((tt&2)===0&&(au|=i),ia===4&&Wl(e,It,Ds,!1)),io(e))}function My(e,a,i){if((tt&6)!==0)throw Error(s(327));var c=!i&&(a&127)===0&&(a&e.expiredLanes)===0||gt(e,a),p=c?$C(e,a):Gh(e,a,!0),v=c;do{if(p===0){Yo&&!c&&Wl(e,a,0,!1);break}else{if(i=e.current.alternate,v&&!HC(i)){p=Gh(e,a,!1),v=!1;continue}if(p===2){if(v=a,e.errorRecoveryDisabledLanes&v)var M=0;else M=e.pendingLanes&-536870913,M=M!==0?M:M&536870912?536870912:0;if(M!==0){a=M;e:{var _=e;p=Ef;var Z=_.current.memoizedState.isDehydrated;if(Z&&(yd(_,M).flags|=256),M=Gh(_,M,!1),M!==2){if(cs&&!Z){_.errorRecoveryDisabledLanes|=v,au|=v,p=4;break e}v=us,us=p,v!==null&&(us===null?us=v:us.push.apply(us,v))}p=M}if(v=!1,p!==2)continue}}if(p===1){yd(e,0),Wl(e,a,0,!0);break}e:{switch(c=e,v=p,v){case 0:case 1:throw Error(s(345));case 4:if((a&4194048)!==a)break;case 6:Wl(c,a,Ds,!ei);break e;case 2:us=null;break;case 3:case 5:break;default:throw Error(s(329))}if((a&62914560)===a&&(p=Zm+300-B(),10<p)){if(Wl(c,a,Ds,!ei),Wt(c,0,!0)!==0)break e;Xo=a,c.timeoutHandle=nb(Ay.bind(null,c,i,us,ep,zh,a,Ds,au,gd,ei,v,"Throttled",-0,0),p);break e}Ay(c,i,us,ep,zh,a,Ds,au,gd,ei,v,null,-0,0)}}break}while(!0);io(e)}function Ay(e,a,i,c,p,v,M,_,Z,we,Re,_e,xe,ke){if(e.timeoutHandle=-1,_e=a.subtreeFlags,_e&8192||(_e&16785408)===16785408){_e={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:ys},te(a,v,_e);var dt=(v&62914560)===v?Zm-B():(v&4194048)===v?Sy-B():0;if(dt=kk(_e,dt),dt!==null){Xo=v,e.cancelPendingCommit=dt(Ly.bind(null,e,a,v,i,c,p,M,_,Z,Re,_e,null,xe,ke)),Wl(e,v,M,!we);return}}Ly(e,a,v,i,c,p,M,_,Z)}function HC(e){for(var a=e;;){var i=a.tag;if((i===0||i===11||i===15)&&a.flags&16384&&(i=a.updateQueue,i!==null&&(i=i.stores,i!==null)))for(var c=0;c<i.length;c++){var p=i[c],v=p.getSnapshot;p=p.value;try{if(!la(v(),p))return!1}catch{return!1}}if(i=a.child,a.subtreeFlags&16384&&i!==null)i.return=a,a=i;else{if(a===e)break;for(;a.sibling===null;){if(a.return===null||a.return===e)return!0;a=a.return}a.sibling.return=a.return,a=a.sibling}}return!0}function Wl(e,a,i,c){a&=~Hh,a&=~au,e.suspendedLanes|=a,e.pingedLanes&=~a,c&&(e.warmLanes|=a),c=e.expirationTimes;for(var p=a;0<p;){var v=31-je(p),M=1<<v;c[v]=-1,p&=~M}i!==0&&za(e,i,a)}function tp(){return(tt&6)===0?(Df(0),!1):!0}function Wh(){if(pt!==null){if(en===0)var e=pt.return;else e=pt,Ht=hi=null,Uu(e),As=null,Ic=0,e=pt;for(;e!==null;)Ko(e.alternate,e),e=e.return;pt=null}}function yd(e,a){var i=e.timeoutHandle;i!==-1&&(e.timeoutHandle=-1,ik(i)),i=e.cancelPendingCommit,i!==null&&(e.cancelPendingCommit=null,i()),Xo=0,Wh(),ut=e,pt=i=Cr(e.current,null),It=a,en=0,Ba=null,ei=!1,Yo=gt(e,a),cs=!1,gd=Ds=Hh=au=$l=ia=0,us=Ef=null,zh=!1,(a&8)!==0&&(a|=a&32);var c=e.entangledLanes;if(c!==0)for(e=e.entanglements,c&=a;0<c;){var p=31-je(c),v=1<<p;a|=e[p],c&=~v}return js=a,va(),i}function Ty(e,a){Ot=null,U.H=Il,a===Qa||a===Vs?(a=_m(),en=3):a===Pm?(a=_m(),en=4):en=a===bf?8:a!==null&&typeof a=="object"&&typeof a.then=="function"?6:1,Ba=a,pt===null&&(ia=1,Wo(e,Or(a,e.current)))}function Ny(){var e=Za.current;return e===null?!0:(It&4194048)===It?wn===null:(It&62914560)===It||(It&536870912)!==0?e===wn:!1}function Ry(){var e=U.H;return U.H=Il,e===null?Il:e}function Ey(){var e=U.A;return U.A=Nt,e}function np(){ia=4,ei||(It&4194048)!==It&&Za.current!==null||(Yo=!0),($l&134217727)===0&&(au&134217727)===0||ut===null||Wl(ut,It,Ds,!1)}function Gh(e,a,i){var c=tt;tt|=2;var p=Ry(),v=Ey();(ut!==e||It!==a)&&(ep=null,yd(e,a)),a=!1;var M=ia;e:do try{if(en!==0&&pt!==null){var _=pt,Z=Ba;switch(en){case 8:Wh(),M=6;break e;case 3:case 2:case 9:case 6:Za.current===null&&(a=!0);var we=en;if(en=0,Ba=null,bd(e,_,Z,we),i&&Yo){M=0;break e}break;default:we=en,en=0,Ba=null,bd(e,_,Z,we)}}zC(),M=ia;break}catch(Re){Ty(e,Re)}while(!0);return a&&e.shellSuspendCounter++,Ht=hi=null,tt=c,U.H=p,U.A=v,pt===null&&(ut=null,It=0,va()),M}function zC(){for(;pt!==null;)jy(pt)}function $C(e,a){var i=tt;tt|=2;var c=Ry(),p=Ey();ut!==e||It!==a?(ep=null,Jm=B()+500,yd(e,a)):Yo=gt(e,a);e:do try{if(en!==0&&pt!==null){a=pt;var v=Ba;t:switch(en){case 1:en=0,Ba=null,bd(e,a,v,1);break;case 2:case 9:if(ef(v)){en=0,Ba=null,Dy(a);break}a=function(){en!==2&&en!==9||ut!==e||(en=7),io(e)},v.then(a,a);break e;case 3:en=7;break e;case 4:en=5;break e;case 7:ef(v)?(en=0,Ba=null,Dy(a)):(en=0,Ba=null,bd(e,a,v,7));break;case 5:var M=null;switch(pt.tag){case 26:M=pt.memoizedState;case 5:case 27:var _=pt;if(M?vb(M):_.stateNode.complete){en=0,Ba=null;var Z=_.sibling;if(Z!==null)pt=Z;else{var we=_.return;we!==null?(pt=we,ap(we)):pt=null}break t}}en=0,Ba=null,bd(e,a,v,5);break;case 6:en=0,Ba=null,bd(e,a,v,6);break;case 8:Wh(),ia=6;break e;default:throw Error(s(462))}}UC();break}catch(Re){Ty(e,Re)}while(!0);return Ht=hi=null,U.H=c,U.A=p,tt=i,pt!==null?0:(ut=null,It=0,va(),ia)}function UC(){for(;pt!==null&&!O();)jy(pt)}function jy(e){var a=dd(e.alternate,e,js);e.memoizedProps=e.pendingProps,a===null?ap(e):pt=a}function Dy(e){var a=e,i=a.alternate;switch(a.tag){case 15:case 0:a=Wm(i,a,a.pendingProps,a.type,void 0,It);break;case 11:a=Wm(i,a,a.pendingProps,a.type.render,a.ref,It);break;case 5:Uu(a);default:Ko(i,a),a=pt=Rm(a,js),a=dd(i,a,js)}e.memoizedProps=e.pendingProps,a===null?ap(e):pt=a}function bd(e,a,i,c){Ht=hi=null,Uu(a),As=null,Ic=0;var p=a.return;try{if(Fh(e,p,a,i,It)){ia=1,Wo(e,Or(i,e.current)),pt=null;return}}catch(v){if(p!==null)throw pt=p,v;ia=1,Wo(e,Or(i,e.current)),pt=null;return}a.flags&32768?(Vt||c===1?e=!0:Yo||(It&536870912)!==0?e=!1:(ei=e=!0,(c===2||c===9||c===3||c===6)&&(c=Za.current,c!==null&&c.tag===13&&(c.flags|=16384))),Iy(a,e)):ap(a)}function ap(e){var a=e;do{if((a.flags&32768)!==0){Iy(a,ei);return}e=a.return;var i=Gm(a.alternate,a,js);if(i!==null){pt=i;return}if(a=a.sibling,a!==null){pt=a;return}pt=a=e}while(a!==null);ia===0&&(ia=5)}function Iy(e,a){do{var i=Vm(e.alternate,e);if(i!==null){i.flags&=32767,pt=i;return}if(i=e.return,i!==null&&(i.flags|=32768,i.subtreeFlags=0,i.deletions=null),!a&&(e=e.sibling,e!==null)){pt=e;return}pt=e=i}while(e!==null);ia=6,pt=null}function Ly(e,a,i,c,p,v,M,_,Z){e.cancelPendingCommit=null;do rp();while(Ha!==0);if((tt&6)!==0)throw Error(s(327));if(a!==null){if(a===e.current)throw Error(s(177));if(v=a.lanes|a.childLanes,v|=Du,na(e,i,v,M,_,Z),e===ut&&(pt=ut=null,It=0),vd=a,ql=e,Xo=i,$h=v,Uh=p,Cy=c,(a.subtreeFlags&10256)!==0||(a.flags&10256)!==0?(e.callbackNode=null,e.callbackPriority=0,VC(it,function(){return By(),null})):(e.callbackNode=null,e.callbackPriority=0),c=(a.flags&13878)!==0,(a.subtreeFlags&13878)!==0||c){c=U.T,U.T=null,p=L.p,L.p=2,M=tt,tt|=4;try{xy(e,a,i)}finally{tt=M,L.p=p,U.T=c}}Ha=1,Py(),_y(),Oy()}}function Py(){if(Ha===1){Ha=0;var e=ql,a=vd,i=(a.flags&13878)!==0;if((a.subtreeFlags&13878)!==0||i){i=U.T,U.T=null;var c=L.p;L.p=2;var p=tt;tt|=4;try{so(a,e);var v=rg,M=Hi(e.containerInfo),_=v.focusedElem,Z=v.selectionRange;if(M!==_&&_&&_.ownerDocument&&Bi(_.ownerDocument.documentElement,_)){if(Z!==null&&zi(_)){var we=Z.start,Re=Z.end;if(Re===void 0&&(Re=we),"selectionStart"in _)_.selectionStart=we,_.selectionEnd=Math.min(Re,_.value.length);else{var _e=_.ownerDocument||document,xe=_e&&_e.defaultView||window;if(xe.getSelection){var ke=xe.getSelection(),dt=_.textContent.length,Dt=Math.min(Z.start,dt),Nn=Z.end===void 0?Dt:Math.min(Z.end,dt);!ke.extend&&Dt>Nn&&(M=Nn,Nn=Dt,Dt=M);var ue=ws(_,Dt),re=ws(_,Nn);if(ue&&re&&(ke.rangeCount!==1||ke.anchorNode!==ue.node||ke.anchorOffset!==ue.offset||ke.focusNode!==re.node||ke.focusOffset!==re.offset)){var be=_e.createRange();be.setStart(ue.node,ue.offset),ke.removeAllRanges(),Dt>Nn?(ke.addRange(be),ke.extend(re.node,re.offset)):(be.setEnd(re.node,re.offset),ke.addRange(be))}}}}for(_e=[],ke=_;ke=ke.parentNode;)ke.nodeType===1&&_e.push({element:ke,left:ke.scrollLeft,top:ke.scrollTop});for(typeof _.focus=="function"&&_.focus(),_=0;_<_e.length;_++){var Le=_e[_];Le.element.scrollLeft=Le.left,Le.element.scrollTop=Le.top}}gp=!!ag,rg=ag=null}finally{tt=p,L.p=c,U.T=i}}e.current=a,Ha=2}}function _y(){if(Ha===2){Ha=0;var e=ql,a=vd,i=(a.flags&8772)!==0;if((a.subtreeFlags&8772)!==0||i){i=U.T,U.T=null;var c=L.p;L.p=2;var p=tt;tt|=4;try{Km(e,a.alternate,a)}finally{tt=p,L.p=c,U.T=i}}Ha=3}}function Oy(){if(Ha===4||Ha===3){Ha=0,qe();var e=ql,a=vd,i=Xo,c=Cy;(a.subtreeFlags&10256)!==0||(a.flags&10256)!==0?Ha=5:(Ha=0,vd=ql=null,Fy(e,e.pendingLanes));var p=e.pendingLanes;if(p===0&&(Ul=null),an(i),a=a.stateNode,fe&&typeof fe.onCommitFiberRoot=="function")try{fe.onCommitFiberRoot(ae,a,void 0,(a.current.flags&128)===128)}catch{}if(c!==null){a=U.T,p=L.p,L.p=2,U.T=null;try{for(var v=e.onRecoverableError,M=0;M<c.length;M++){var _=c[M];v(_.value,{componentStack:_.stack})}}finally{U.T=a,L.p=p}}(Xo&3)!==0&&rp(),io(e),p=e.pendingLanes,(i&261930)!==0&&(p&42)!==0?e===qh?jf++:(jf=0,qh=e):jf=0,Df(0)}}function Fy(e,a){(e.pooledCacheLanes&=a)===0&&(a=e.pooledCache,a!=null&&(e.pooledCache=null,ks(a)))}function rp(){return Py(),_y(),Oy(),By()}function By(){if(Ha!==5)return!1;var e=ql,a=$h;$h=0;var i=an(Xo),c=U.T,p=L.p;try{L.p=32>i?32:i,U.T=null,i=Uh,Uh=null;var v=ql,M=Xo;if(Ha=0,vd=ql=null,Xo=0,(tt&6)!==0)throw Error(s(331));var _=tt;if(tt|=4,nt(v.current),C(v,v.current,M,i),tt=_,Df(0,!1),fe&&typeof fe.onPostCommitFiberRoot=="function")try{fe.onPostCommitFiberRoot(ae,v)}catch{}return!0}finally{L.p=p,U.T=c,Fy(e,a)}}function Hy(e,a,i){a=Or(i,a),a=vf(e.stateNode,a,2),e=La(e,a,2),e!==null&&(hn(e,2),io(e))}function xn(e,a,i){if(e.tag===3)Hy(e,e,i);else for(;a!==null;){if(a.tag===3){Hy(a,e,i);break}else if(a.tag===1){var c=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof c.componentDidCatch=="function"&&(Ul===null||!Ul.has(c))){e=Or(i,e),i=yf(2),c=La(a,i,2),c!==null&&(_l(i,c,a,e),hn(c,2),io(c));break}}a=a.return}}function Vh(e,a,i){var c=e.pingCache;if(c===null){c=e.pingCache=new Yt;var p=new Set;c.set(a,p)}else p=c.get(a),p===void 0&&(p=new Set,c.set(a,p));p.has(i)||(cs=!0,p.add(i),e=qC.bind(null,e,a,i),a.then(e,e))}function qC(e,a,i){var c=e.pingCache;c!==null&&c.delete(a),e.pingedLanes|=e.suspendedLanes&i,e.warmLanes&=~i,ut===e&&(It&i)===i&&(ia===4||ia===3&&(It&62914560)===It&&300>B()-Zm?(tt&2)===0&&yd(e,0):Hh|=i,gd===It&&(gd=0)),io(e)}function zy(e,a){a===0&&(a=mt()),e=_n(e,a),e!==null&&(hn(e,a),io(e))}function WC(e){var a=e.memoizedState,i=0;a!==null&&(i=a.retryLane),zy(e,i)}function GC(e,a){var i=0;switch(e.tag){case 31:case 13:var c=e.stateNode,p=e.memoizedState;p!==null&&(i=p.retryLane);break;case 19:c=e.stateNode;break;case 22:c=e.stateNode._retryCache;break;default:throw Error(s(314))}c!==null&&c.delete(a),zy(e,i)}function VC(e,a){return rt(e,a)}var sp=null,wd=null,Kh=!1,ip=!1,Qh=!1,Gl=0;function io(e){e!==wd&&e.next===null&&(wd===null?sp=wd=e:wd=wd.next=e),ip=!0,Kh||(Kh=!0,QC())}function Df(e,a){if(!Qh&&ip){Qh=!0;do for(var i=!1,c=sp;c!==null;){if(e!==0){var p=c.pendingLanes;if(p===0)var v=0;else{var M=c.suspendedLanes,_=c.pingedLanes;v=(1<<31-je(42|e)+1)-1,v&=p&~(M&~_),v=v&201326741?v&201326741|1:v?v|2:0}v!==0&&(i=!0,Wy(c,v))}else v=It,v=Wt(c,c===ut?v:0,c.cancelPendingCommit!==null||c.timeoutHandle!==-1),(v&3)===0||gt(c,v)||(i=!0,Wy(c,v));c=c.next}while(i);Qh=!1}}function KC(){$y()}function $y(){ip=Kh=!1;var e=0;Gl!==0&&sk()&&(e=Gl);for(var a=B(),i=null,c=sp;c!==null;){var p=c.next,v=Uy(c,a);v===0?(c.next=null,i===null?sp=p:i.next=p,p===null&&(wd=i)):(i=c,(e!==0||(v&3)!==0)&&(ip=!0)),c=p}Ha!==0&&Ha!==5||Df(e),Gl!==0&&(Gl=0)}function Uy(e,a){for(var i=e.suspendedLanes,c=e.pingedLanes,p=e.expirationTimes,v=e.pendingLanes&-62914561;0<v;){var M=31-je(v),_=1<<M,Z=p[M];Z===-1?((_&i)===0||(_&c)!==0)&&(p[M]=yn(_,a)):Z<=a&&(e.expiredLanes|=_),v&=~_}if(a=ut,i=It,i=Wt(e,e===a?i:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),c=e.callbackNode,i===0||e===a&&(en===2||en===9)||e.cancelPendingCommit!==null)return c!==null&&c!==null&&At(c),e.callbackNode=null,e.callbackPriority=0;if((i&3)===0||gt(e,i)){if(a=i&-i,a===e.callbackPriority)return a;switch(c!==null&&At(c),an(i)){case 2:case 8:i=et;break;case 32:i=it;break;case 268435456:i=Ne;break;default:i=it}return c=qy.bind(null,e),i=rt(i,c),e.callbackPriority=a,e.callbackNode=i,a}return c!==null&&c!==null&&At(c),e.callbackPriority=2,e.callbackNode=null,2}function qy(e,a){if(Ha!==0&&Ha!==5)return e.callbackNode=null,e.callbackPriority=0,null;var i=e.callbackNode;if(rp()&&e.callbackNode!==i)return null;var c=It;return c=Wt(e,e===ut?c:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),c===0?null:(My(e,c,a),Uy(e,B()),e.callbackNode!=null&&e.callbackNode===i?qy.bind(null,e):null)}function Wy(e,a){if(rp())return null;My(e,a,!0)}function QC(){ok(function(){(tt&6)!==0?rt(We,KC):$y()})}function Yh(){if(Gl===0){var e=as;e===0&&(e=ft,ft<<=1,(ft&261888)===0&&(ft=256)),Gl=e}return Gl}function Gy(e){return e==null||typeof e=="symbol"||typeof e=="boolean"?null:typeof e=="function"?e:Lr(""+e)}function Vy(e,a){var i=a.ownerDocument.createElement("input");return i.name=a.name,i.value=a.value,e.id&&i.setAttribute("form",e.id),a.parentNode.insertBefore(i,a),e=new FormData(e),i.parentNode.removeChild(i),e}function YC(e,a,i,c,p){if(a==="submit"&&i&&i.stateNode===p){var v=Gy((p[ze]||null).action),M=c.submitter;M&&(a=(a=M[ze]||null)?Gy(a.formAction):M.getAttribute("formAction"),a!==null&&(v=a,M=null));var _=new li("action","action",null,c,p);e.push({event:_,listeners:[{instance:null,listener:function(){if(c.defaultPrevented){if(Gl!==0){var Z=M?Vy(p,M):new FormData(p);Gc(i,{pending:!0,data:Z,method:p.method,action:v},null,Z)}}else typeof v=="function"&&(_.preventDefault(),Z=M?Vy(p,M):new FormData(p),Gc(i,{pending:!0,data:Z,method:p.method,action:v},v,Z))},currentTarget:p}]})}}for(var Xh=0;Xh<$i.length;Xh++){var Zh=$i[Xh],XC=Zh.toLowerCase(),ZC=Zh[0].toUpperCase()+Zh.slice(1);Va(XC,"on"+ZC)}Va(Tc,"onAnimationEnd"),Va(Eu,"onAnimationIteration"),Va(ju,"onAnimationStart"),Va("dblclick","onDoubleClick"),Va("focusin","onFocus"),Va("focusout","onBlur"),Va(Nc,"onTransitionRun"),Va(Tm,"onTransitionStart"),Va(Nm,"onTransitionCancel"),Va(Ws,"onTransitionEnd"),Un("onMouseEnter",["mouseout","mouseover"]),Un("onMouseLeave",["mouseout","mouseover"]),Un("onPointerEnter",["pointerout","pointerover"]),Un("onPointerLeave",["pointerout","pointerover"]),$n("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),$n("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),$n("onBeforeInput",["compositionend","keypress","textInput","paste"]),$n("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),$n("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),$n("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var If="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),JC=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(If));function Ky(e,a){a=(a&4)!==0;for(var i=0;i<e.length;i++){var c=e[i],p=c.event;c=c.listeners;e:{var v=void 0;if(a)for(var M=c.length-1;0<=M;M--){var _=c[M],Z=_.instance,we=_.currentTarget;if(_=_.listener,Z!==v&&p.isPropagationStopped())break e;v=_,p.currentTarget=we;try{v(p)}catch(Re){Gs(Re)}p.currentTarget=null,v=Z}else for(M=0;M<c.length;M++){if(_=c[M],Z=_.instance,we=_.currentTarget,_=_.listener,Z!==v&&p.isPropagationStopped())break e;v=_,p.currentTarget=we;try{v(p)}catch(Re){Gs(Re)}p.currentTarget=null,v=Z}}}}function Xt(e,a){var i=a[Lt];i===void 0&&(i=a[Lt]=new Set);var c=e+"__bubble";i.has(c)||(Qy(a,e,2,!1),i.add(c))}function Jh(e,a,i){var c=0;a&&(c|=4),Qy(i,e,c,a)}var op="_reactListening"+Math.random().toString(36).slice(2);function eg(e){if(!e[op]){e[op]=!0,Ln.forEach(function(i){i!=="selectionchange"&&(JC.has(i)||Jh(i,!1,e),Jh(i,!0,e))});var a=e.nodeType===9?e:e.ownerDocument;a===null||a[op]||(a[op]=!0,Jh("selectionchange",!1,a))}}function Qy(e,a,i,c){switch(kb(a)){case 2:var p=Tk;break;case 8:p=Nk;break;default:p=hg}i=p.bind(null,a,i,e),p=void 0,!wo||a!=="touchstart"&&a!=="touchmove"&&a!=="wheel"||(p=!0),c?p!==void 0?e.addEventListener(a,i,{capture:!0,passive:p}):e.addEventListener(a,i,!0):p!==void 0?e.addEventListener(a,i,{passive:p}):e.addEventListener(a,i,!1)}function tg(e,a,i,c,p){var v=c;if((a&1)===0&&(a&2)===0&&c!==null)e:for(;;){if(c===null)return;var M=c.tag;if(M===3||M===4){var _=c.stateNode.containerInfo;if(_===p)break;if(M===4)for(M=c.return;M!==null;){var Z=M.tag;if((Z===3||Z===4)&&M.stateNode.containerInfo===p)return;M=M.return}for(;_!==null;){if(M=zn(_),M===null)return;if(Z=M.tag,Z===5||Z===6||Z===26||Z===27){c=v=M;continue e}_=_.parentNode}}c=c.return}bo(function(){var we=v,Re=bs(i),_e=[];e:{var xe=Rc.get(e);if(xe!==void 0){var ke=li,dt=e;switch(e){case"keypress":if(ji(i)===0)break e;case"keydown":case"keyup":ke=_i;break;case"focusin":dt="focus",ke=gn;break;case"focusout":dt="blur",ke=gn;break;case"beforeblur":case"afterblur":ke=gn;break;case"click":if(i.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":ke=yc;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":ke=$d;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":ke=ul;break;case Tc:case Eu:case ju:ke=ci;break;case Ws:ke=wc;break;case"scroll":case"scrollend":ke=ku;break;case"wheel":ke=dl;break;case"copy":case"cut":case"paste":ke=So;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":ke=Ud;break;case"toggle":case"beforetoggle":ke=ui}var Dt=(a&4)!==0,Nn=!Dt&&(e==="scroll"||e==="scrollend"),ue=Dt?xe!==null?xe+"Capture":null:xe;Dt=[];for(var re=we,be;re!==null;){var Le=re;if(be=Le.stateNode,Le=Le.tag,Le!==5&&Le!==26&&Le!==27||be===null||ue===null||(Le=Kt(re,ue),Le!=null&&Dt.push(Lf(re,Le,be))),Nn)break;re=re.return}0<Dt.length&&(xe=new ke(xe,dt,null,i,Re),_e.push({event:xe,listeners:Dt}))}}if((a&7)===0){e:{if(xe=e==="mouseover"||e==="pointerover",ke=e==="mouseout"||e==="pointerout",xe&&i!==Cu&&(dt=i.relatedTarget||i.fromElement)&&(zn(dt)||dt[st]))break e;if((ke||xe)&&(xe=Re.window===Re?Re:(xe=Re.ownerDocument)?xe.defaultView||xe.parentWindow:window,ke?(dt=i.relatedTarget||i.toElement,ke=we,dt=dt?zn(dt):null,dt!==null&&(Nn=u(dt),Dt=dt.tag,dt!==Nn||Dt!==5&&Dt!==27&&Dt!==6)&&(dt=null)):(ke=null,dt=we),ke!==dt)){if(Dt=yc,Le="onMouseLeave",ue="onMouseEnter",re="mouse",(e==="pointerout"||e==="pointerover")&&(Dt=Ud,Le="onPointerLeave",ue="onPointerEnter",re="pointer"),Nn=ke==null?xe:bn(ke),be=dt==null?xe:bn(dt),xe=new Dt(Le,re+"leave",ke,i,Re),xe.target=Nn,xe.relatedTarget=be,Le=null,zn(Re)===we&&(Dt=new Dt(ue,re+"enter",dt,i,Re),Dt.target=be,Dt.relatedTarget=Nn,Le=Dt),Nn=Le,ke&&dt)t:{for(Dt=ek,ue=ke,re=dt,be=0,Le=ue;Le;Le=Dt(Le))be++;Le=0;for(var Tt=re;Tt;Tt=Dt(Tt))Le++;for(;0<be-Le;)ue=Dt(ue),be--;for(;0<Le-be;)re=Dt(re),Le--;for(;be--;){if(ue===re||re!==null&&ue===re.alternate){Dt=ue;break t}ue=Dt(ue),re=Dt(re)}Dt=null}else Dt=null;ke!==null&&Yy(_e,xe,ke,Dt,!1),dt!==null&&Nn!==null&&Yy(_e,Nn,dt,Dt,!0)}}e:{if(xe=we?bn(we):window,ke=xe.nodeName&&xe.nodeName.toLowerCase(),ke==="select"||ke==="input"&&xe.type==="file")var fn=pl;else if(Mm(xe))if(Wd)fn=Mc;else{fn=To;var vt=Yr}else ke=xe.nodeName,!ke||ke.toLowerCase()!=="input"||xe.type!=="checkbox"&&xe.type!=="radio"?we&&Wr(we.elementType)&&(fn=pl):fn=hl;if(fn&&(fn=fn(e,we))){Us(_e,fn,i,Re);break e}vt&&vt(e,xe,we),e==="focusout"&&we&&xe.type==="number"&&we.memoizedProps.value!=null&&Os(xe,"number",xe.value)}switch(vt=we?bn(we):window,e){case"focusin":(Mm(vt)||vt.contentEditable==="true")&&(Ga=vt,Xr=we,Eo=null);break;case"focusout":Eo=Xr=Ga=null;break;case"mousedown":Ia=!0;break;case"contextmenu":case"mouseup":case"dragend":Ia=!1,Am(_e,i,Re);break;case"selectionchange":if(Ro)break;case"keydown":case"keyup":Am(_e,i,Re)}var Gt;if(fl)e:{switch(e){case"compositionstart":var Zt="onCompositionStart";break e;case"compositionend":Zt="onCompositionEnd";break e;case"compositionupdate":Zt="onCompositionUpdate";break e}Zt=void 0}else fi?Cc(e,i)&&(Zt="onCompositionEnd"):e==="keydown"&&i.keyCode===229&&(Zt="onCompositionStart");Zt&&(Sc&&i.locale!=="ko"&&(fi||Zt!=="onCompositionStart"?Zt==="onCompositionEnd"&&fi&&(Gt=Pr()):(Vr=Re,$t="value"in Vr?Vr.value:Vr.textContent,fi=!0)),vt=lp(we,Zt),0<vt.length&&(Zt=new zs(Zt,e,null,i,Re),_e.push({event:Zt,listeners:vt}),Gt?Zt.data=Gt:(Gt=kc(i),Gt!==null&&(Zt.data=Gt)))),(Gt=km?qd(e,i):or(e,i))&&(Zt=lp(we,"onBeforeInput"),0<Zt.length&&(vt=new zs("onBeforeInput","beforeinput",null,i,Re),_e.push({event:vt,listeners:Zt}),vt.data=Gt)),YC(_e,e,we,i,Re)}Ky(_e,a)})}function Lf(e,a,i){return{instance:e,listener:a,currentTarget:i}}function lp(e,a){for(var i=a+"Capture",c=[];e!==null;){var p=e,v=p.stateNode;if(p=p.tag,p!==5&&p!==26&&p!==27||v===null||(p=Kt(e,i),p!=null&&c.unshift(Lf(e,p,v)),p=Kt(e,a),p!=null&&c.push(Lf(e,p,v))),e.tag===3)return c;e=e.return}return[]}function ek(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5&&e.tag!==27);return e||null}function Yy(e,a,i,c,p){for(var v=a._reactName,M=[];i!==null&&i!==c;){var _=i,Z=_.alternate,we=_.stateNode;if(_=_.tag,Z!==null&&Z===c)break;_!==5&&_!==26&&_!==27||we===null||(Z=we,p?(we=Kt(i,v),we!=null&&M.unshift(Lf(i,we,Z))):p||(we=Kt(i,v),we!=null&&M.push(Lf(i,we,Z)))),i=i.return}M.length!==0&&e.push({event:a,listeners:M})}var tk=/\r\n?/g,nk=/\u0000|\uFFFD/g;function Xy(e){return(typeof e=="string"?e:""+e).replace(tk,`
9
- `).replace(nk,"")}function Zy(e,a){return a=Xy(a),Xy(e)===a}function Tn(e,a,i,c,p,v){switch(i){case"children":typeof c=="string"?a==="body"||a==="textarea"&&c===""||qr(e,c):(typeof c=="number"||typeof c=="bigint")&&a!=="body"&&qr(e,""+c);break;case"className":Ri(e,"class",c);break;case"tabIndex":Ri(e,"tabindex",c);break;case"dir":case"role":case"viewBox":case"width":case"height":Ri(e,i,c);break;case"style":hc(e,c,v);break;case"data":if(a!=="object"){Ri(e,"data",c);break}case"src":case"href":if(c===""&&(a!=="a"||i!=="href")){e.removeAttribute(i);break}if(c==null||typeof c=="function"||typeof c=="symbol"||typeof c=="boolean"){e.removeAttribute(i);break}c=Lr(""+c),e.setAttribute(i,c);break;case"action":case"formAction":if(typeof c=="function"){e.setAttribute(i,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof v=="function"&&(i==="formAction"?(a!=="input"&&Tn(e,a,"name",p.name,p,null),Tn(e,a,"formEncType",p.formEncType,p,null),Tn(e,a,"formMethod",p.formMethod,p,null),Tn(e,a,"formTarget",p.formTarget,p,null)):(Tn(e,a,"encType",p.encType,p,null),Tn(e,a,"method",p.method,p,null),Tn(e,a,"target",p.target,p,null)));if(c==null||typeof c=="symbol"||typeof c=="boolean"){e.removeAttribute(i);break}c=Lr(""+c),e.setAttribute(i,c);break;case"onClick":c!=null&&(e.onclick=ys);break;case"onScroll":c!=null&&Xt("scroll",e);break;case"onScrollEnd":c!=null&&Xt("scrollend",e);break;case"dangerouslySetInnerHTML":if(c!=null){if(typeof c!="object"||!("__html"in c))throw Error(s(61));if(i=c.__html,i!=null){if(p.children!=null)throw Error(s(60));e.innerHTML=i}}break;case"multiple":e.multiple=c&&typeof c!="function"&&typeof c!="symbol";break;case"muted":e.muted=c&&typeof c!="function"&&typeof c!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(c==null||typeof c=="function"||typeof c=="boolean"||typeof c=="symbol"){e.removeAttribute("xlink:href");break}i=Lr(""+c),e.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",i);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":c!=null&&typeof c!="function"&&typeof c!="symbol"?e.setAttribute(i,""+c):e.removeAttribute(i);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":c&&typeof c!="function"&&typeof c!="symbol"?e.setAttribute(i,""):e.removeAttribute(i);break;case"capture":case"download":c===!0?e.setAttribute(i,""):c!==!1&&c!=null&&typeof c!="function"&&typeof c!="symbol"?e.setAttribute(i,c):e.removeAttribute(i);break;case"cols":case"rows":case"size":case"span":c!=null&&typeof c!="function"&&typeof c!="symbol"&&!isNaN(c)&&1<=c?e.setAttribute(i,c):e.removeAttribute(i);break;case"rowSpan":case"start":c==null||typeof c=="function"||typeof c=="symbol"||isNaN(c)?e.removeAttribute(i):e.setAttribute(i,c);break;case"popover":Xt("beforetoggle",e),Xt("toggle",e),si(e,"popover",c);break;case"xlinkActuate":yr(e,"http://www.w3.org/1999/xlink","xlink:actuate",c);break;case"xlinkArcrole":yr(e,"http://www.w3.org/1999/xlink","xlink:arcrole",c);break;case"xlinkRole":yr(e,"http://www.w3.org/1999/xlink","xlink:role",c);break;case"xlinkShow":yr(e,"http://www.w3.org/1999/xlink","xlink:show",c);break;case"xlinkTitle":yr(e,"http://www.w3.org/1999/xlink","xlink:title",c);break;case"xlinkType":yr(e,"http://www.w3.org/1999/xlink","xlink:type",c);break;case"xmlBase":yr(e,"http://www.w3.org/XML/1998/namespace","xml:base",c);break;case"xmlLang":yr(e,"http://www.w3.org/XML/1998/namespace","xml:lang",c);break;case"xmlSpace":yr(e,"http://www.w3.org/XML/1998/namespace","xml:space",c);break;case"is":si(e,"is",c);break;case"innerText":case"textContent":break;default:(!(2<i.length)||i[0]!=="o"&&i[0]!=="O"||i[1]!=="n"&&i[1]!=="N")&&(i=gc.get(i)||i,si(e,i,c))}}function ng(e,a,i,c,p,v){switch(i){case"style":hc(e,c,v);break;case"dangerouslySetInnerHTML":if(c!=null){if(typeof c!="object"||!("__html"in c))throw Error(s(61));if(i=c.__html,i!=null){if(p.children!=null)throw Error(s(60));e.innerHTML=i}}break;case"children":typeof c=="string"?qr(e,c):(typeof c=="number"||typeof c=="bigint")&&qr(e,""+c);break;case"onScroll":c!=null&&Xt("scroll",e);break;case"onScrollEnd":c!=null&&Xt("scrollend",e);break;case"onClick":c!=null&&(e.onclick=ys);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!En.hasOwnProperty(i))e:{if(i[0]==="o"&&i[1]==="n"&&(p=i.endsWith("Capture"),a=i.slice(2,p?i.length-7:void 0),v=e[ze]||null,v=v!=null?v[i]:null,typeof v=="function"&&e.removeEventListener(a,v,p),typeof c=="function")){typeof v!="function"&&v!==null&&(i in e?e[i]=null:e.hasAttribute(i)&&e.removeAttribute(i)),e.addEventListener(a,c,p);break e}i in e?e[i]=c:c===!0?e.setAttribute(i,""):si(e,i,c)}}}function hr(e,a,i){switch(a){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":Xt("error",e),Xt("load",e);var c=!1,p=!1,v;for(v in i)if(i.hasOwnProperty(v)){var M=i[v];if(M!=null)switch(v){case"src":c=!0;break;case"srcSet":p=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(s(137,a));default:Tn(e,a,v,M,i,null)}}p&&Tn(e,a,"srcSet",i.srcSet,i,null),c&&Tn(e,a,"src",i.src,i,null);return;case"input":Xt("invalid",e);var _=v=M=p=null,Z=null,we=null;for(c in i)if(i.hasOwnProperty(c)){var Re=i[c];if(Re!=null)switch(c){case"name":p=Re;break;case"type":M=Re;break;case"checked":Z=Re;break;case"defaultChecked":we=Re;break;case"value":v=Re;break;case"defaultValue":_=Re;break;case"children":case"dangerouslySetInnerHTML":if(Re!=null)throw Error(s(137,a));break;default:Tn(e,a,c,Re,i,null)}}wr(e,v,_,Z,we,M,p,!1);return;case"select":Xt("invalid",e),c=M=v=null;for(p in i)if(i.hasOwnProperty(p)&&(_=i[p],_!=null))switch(p){case"value":v=_;break;case"defaultValue":M=_;break;case"multiple":c=_;default:Tn(e,a,p,_,i,null)}a=v,i=M,e.multiple=!!c,a!=null?xr(e,!!c,a,!1):i!=null&&xr(e,!!c,i,!0);return;case"textarea":Xt("invalid",e),v=p=c=null;for(M in i)if(i.hasOwnProperty(M)&&(_=i[M],_!=null))switch(M){case"value":c=_;break;case"defaultValue":p=_;break;case"children":v=_;break;case"dangerouslySetInnerHTML":if(_!=null)throw Error(s(91));break;default:Tn(e,a,M,_,i,null)}rl(e,c,p,v);return;case"option":for(Z in i)i.hasOwnProperty(Z)&&(c=i[Z],c!=null)&&(Z==="selected"?e.selected=c&&typeof c!="function"&&typeof c!="symbol":Tn(e,a,Z,c,i,null));return;case"dialog":Xt("beforetoggle",e),Xt("toggle",e),Xt("cancel",e),Xt("close",e);break;case"iframe":case"object":Xt("load",e);break;case"video":case"audio":for(c=0;c<If.length;c++)Xt(If[c],e);break;case"image":Xt("error",e),Xt("load",e);break;case"details":Xt("toggle",e);break;case"embed":case"source":case"link":Xt("error",e),Xt("load",e);case"area":case"base":case"br":case"col":case"hr":case"keygen":case"meta":case"param":case"track":case"wbr":case"menuitem":for(we in i)if(i.hasOwnProperty(we)&&(c=i[we],c!=null))switch(we){case"children":case"dangerouslySetInnerHTML":throw Error(s(137,a));default:Tn(e,a,we,c,i,null)}return;default:if(Wr(a)){for(Re in i)i.hasOwnProperty(Re)&&(c=i[Re],c!==void 0&&ng(e,a,Re,c,i,void 0));return}}for(_ in i)i.hasOwnProperty(_)&&(c=i[_],c!=null&&Tn(e,a,_,c,i,null))}function ak(e,a,i,c){switch(a){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var p=null,v=null,M=null,_=null,Z=null,we=null,Re=null;for(ke in i){var _e=i[ke];if(i.hasOwnProperty(ke)&&_e!=null)switch(ke){case"checked":break;case"value":break;case"defaultValue":Z=_e;default:c.hasOwnProperty(ke)||Tn(e,a,ke,null,c,_e)}}for(var xe in c){var ke=c[xe];if(_e=i[xe],c.hasOwnProperty(xe)&&(ke!=null||_e!=null))switch(xe){case"type":v=ke;break;case"name":p=ke;break;case"checked":we=ke;break;case"defaultChecked":Re=ke;break;case"value":M=ke;break;case"defaultValue":_=ke;break;case"children":case"dangerouslySetInnerHTML":if(ke!=null)throw Error(s(137,a));break;default:ke!==_e&&Tn(e,a,xe,ke,c,_e)}}oi(e,M,_,Z,we,Re,v,p);return;case"select":ke=M=_=xe=null;for(v in i)if(Z=i[v],i.hasOwnProperty(v)&&Z!=null)switch(v){case"value":break;case"multiple":ke=Z;default:c.hasOwnProperty(v)||Tn(e,a,v,null,c,Z)}for(p in c)if(v=c[p],Z=i[p],c.hasOwnProperty(p)&&(v!=null||Z!=null))switch(p){case"value":xe=v;break;case"defaultValue":_=v;break;case"multiple":M=v;default:v!==Z&&Tn(e,a,p,v,c,Z)}a=_,i=M,c=ke,xe!=null?xr(e,!!i,xe,!1):!!c!=!!i&&(a!=null?xr(e,!!i,a,!0):xr(e,!!i,i?[]:"",!1));return;case"textarea":ke=xe=null;for(_ in i)if(p=i[_],i.hasOwnProperty(_)&&p!=null&&!c.hasOwnProperty(_))switch(_){case"value":break;case"children":break;default:Tn(e,a,_,null,c,p)}for(M in c)if(p=c[M],v=i[M],c.hasOwnProperty(M)&&(p!=null||v!=null))switch(M){case"value":xe=p;break;case"defaultValue":ke=p;break;case"children":break;case"dangerouslySetInnerHTML":if(p!=null)throw Error(s(91));break;default:p!==v&&Tn(e,a,M,p,c,v)}Fs(e,xe,ke);return;case"option":for(var dt in i)xe=i[dt],i.hasOwnProperty(dt)&&xe!=null&&!c.hasOwnProperty(dt)&&(dt==="selected"?e.selected=!1:Tn(e,a,dt,null,c,xe));for(Z in c)xe=c[Z],ke=i[Z],c.hasOwnProperty(Z)&&xe!==ke&&(xe!=null||ke!=null)&&(Z==="selected"?e.selected=xe&&typeof xe!="function"&&typeof xe!="symbol":Tn(e,a,Z,xe,c,ke));return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var Dt in i)xe=i[Dt],i.hasOwnProperty(Dt)&&xe!=null&&!c.hasOwnProperty(Dt)&&Tn(e,a,Dt,null,c,xe);for(we in c)if(xe=c[we],ke=i[we],c.hasOwnProperty(we)&&xe!==ke&&(xe!=null||ke!=null))switch(we){case"children":case"dangerouslySetInnerHTML":if(xe!=null)throw Error(s(137,a));break;default:Tn(e,a,we,xe,c,ke)}return;default:if(Wr(a)){for(var Nn in i)xe=i[Nn],i.hasOwnProperty(Nn)&&xe!==void 0&&!c.hasOwnProperty(Nn)&&ng(e,a,Nn,void 0,c,xe);for(Re in c)xe=c[Re],ke=i[Re],!c.hasOwnProperty(Re)||xe===ke||xe===void 0&&ke===void 0||ng(e,a,Re,xe,c,ke);return}}for(var ue in i)xe=i[ue],i.hasOwnProperty(ue)&&xe!=null&&!c.hasOwnProperty(ue)&&Tn(e,a,ue,null,c,xe);for(_e in c)xe=c[_e],ke=i[_e],!c.hasOwnProperty(_e)||xe===ke||xe==null&&ke==null||Tn(e,a,_e,xe,c,ke)}function Jy(e){switch(e){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function rk(){if(typeof performance.getEntriesByType=="function"){for(var e=0,a=0,i=performance.getEntriesByType("resource"),c=0;c<i.length;c++){var p=i[c],v=p.transferSize,M=p.initiatorType,_=p.duration;if(v&&_&&Jy(M)){for(M=0,_=p.responseEnd,c+=1;c<i.length;c++){var Z=i[c],we=Z.startTime;if(we>_)break;var Re=Z.transferSize,_e=Z.initiatorType;Re&&Jy(_e)&&(Z=Z.responseEnd,M+=Re*(Z<_?1:(_-we)/(Z-we)))}if(--c,a+=8*(v+M)/(p.duration/1e3),e++,10<e)break}}if(0<e)return a/e/1e6}return navigator.connection&&(e=navigator.connection.downlink,typeof e=="number")?e:5}var ag=null,rg=null;function cp(e){return e.nodeType===9?e:e.ownerDocument}function eb(e){switch(e){case"http://www.w3.org/2000/svg":return 1;case"http://www.w3.org/1998/Math/MathML":return 2;default:return 0}}function tb(e,a){if(e===0)switch(a){case"svg":return 1;case"math":return 2;default:return 0}return e===1&&a==="foreignObject"?0:e}function sg(e,a){return e==="textarea"||e==="noscript"||typeof a.children=="string"||typeof a.children=="number"||typeof a.children=="bigint"||typeof a.dangerouslySetInnerHTML=="object"&&a.dangerouslySetInnerHTML!==null&&a.dangerouslySetInnerHTML.__html!=null}var ig=null;function sk(){var e=window.event;return e&&e.type==="popstate"?e===ig?!1:(ig=e,!0):(ig=null,!1)}var nb=typeof setTimeout=="function"?setTimeout:void 0,ik=typeof clearTimeout=="function"?clearTimeout:void 0,ab=typeof Promise=="function"?Promise:void 0,ok=typeof queueMicrotask=="function"?queueMicrotask:typeof ab<"u"?function(e){return ab.resolve(null).then(e).catch(lk)}:nb;function lk(e){setTimeout(function(){throw e})}function Vl(e){return e==="head"}function rb(e,a){var i=a,c=0;do{var p=i.nextSibling;if(e.removeChild(i),p&&p.nodeType===8)if(i=p.data,i==="/$"||i==="/&"){if(c===0){e.removeChild(p),kd(a);return}c--}else if(i==="$"||i==="$?"||i==="$~"||i==="$!"||i==="&")c++;else if(i==="html")Pf(e.ownerDocument.documentElement);else if(i==="head"){i=e.ownerDocument.head,Pf(i);for(var v=i.firstChild;v;){var M=v.nextSibling,_=v.nodeName;v[Jt]||_==="SCRIPT"||_==="STYLE"||_==="LINK"&&v.rel.toLowerCase()==="stylesheet"||i.removeChild(v),v=M}}else i==="body"&&Pf(e.ownerDocument.body);i=p}while(i);kd(a)}function sb(e,a){var i=e;e=0;do{var c=i.nextSibling;if(i.nodeType===1?a?(i._stashedDisplay=i.style.display,i.style.display="none"):(i.style.display=i._stashedDisplay||"",i.getAttribute("style")===""&&i.removeAttribute("style")):i.nodeType===3&&(a?(i._stashedText=i.nodeValue,i.nodeValue=""):i.nodeValue=i._stashedText||""),c&&c.nodeType===8)if(i=c.data,i==="/$"){if(e===0)break;e--}else i!=="$"&&i!=="$?"&&i!=="$~"&&i!=="$!"||e++;i=c}while(i)}function og(e){var a=e.firstChild;for(a&&a.nodeType===10&&(a=a.nextSibling);a;){var i=a;switch(a=a.nextSibling,i.nodeName){case"HTML":case"HEAD":case"BODY":og(i),In(i);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(i.rel.toLowerCase()==="stylesheet")continue}e.removeChild(i)}}function ck(e,a,i,c){for(;e.nodeType===1;){var p=i;if(e.nodeName.toLowerCase()!==a.toLowerCase()){if(!c&&(e.nodeName!=="INPUT"||e.type!=="hidden"))break}else if(c){if(!e[Jt])switch(a){case"meta":if(!e.hasAttribute("itemprop"))break;return e;case"link":if(v=e.getAttribute("rel"),v==="stylesheet"&&e.hasAttribute("data-precedence"))break;if(v!==p.rel||e.getAttribute("href")!==(p.href==null||p.href===""?null:p.href)||e.getAttribute("crossorigin")!==(p.crossOrigin==null?null:p.crossOrigin)||e.getAttribute("title")!==(p.title==null?null:p.title))break;return e;case"style":if(e.hasAttribute("data-precedence"))break;return e;case"script":if(v=e.getAttribute("src"),(v!==(p.src==null?null:p.src)||e.getAttribute("type")!==(p.type==null?null:p.type)||e.getAttribute("crossorigin")!==(p.crossOrigin==null?null:p.crossOrigin))&&v&&e.hasAttribute("async")&&!e.hasAttribute("itemprop"))break;return e;default:return e}}else if(a==="input"&&e.type==="hidden"){var v=p.name==null?null:""+p.name;if(p.type==="hidden"&&e.getAttribute("name")===v)return e}else return e;if(e=ti(e.nextSibling),e===null)break}return null}function uk(e,a,i){if(a==="")return null;for(;e.nodeType!==3;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!i||(e=ti(e.nextSibling),e===null))return null;return e}function ib(e,a){for(;e.nodeType!==8;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!a||(e=ti(e.nextSibling),e===null))return null;return e}function lg(e){return e.data==="$?"||e.data==="$~"}function cg(e){return e.data==="$!"||e.data==="$?"&&e.ownerDocument.readyState!=="loading"}function dk(e,a){var i=e.ownerDocument;if(e.data==="$~")e._reactRetry=a;else if(e.data!=="$?"||i.readyState!=="loading")a();else{var c=function(){a(),i.removeEventListener("DOMContentLoaded",c)};i.addEventListener("DOMContentLoaded",c),e._reactRetry=c}}function ti(e){for(;e!=null;e=e.nextSibling){var a=e.nodeType;if(a===1||a===3)break;if(a===8){if(a=e.data,a==="$"||a==="$!"||a==="$?"||a==="$~"||a==="&"||a==="F!"||a==="F")break;if(a==="/$"||a==="/&")return null}}return e}var ug=null;function ob(e){e=e.nextSibling;for(var a=0;e;){if(e.nodeType===8){var i=e.data;if(i==="/$"||i==="/&"){if(a===0)return ti(e.nextSibling);a--}else i!=="$"&&i!=="$!"&&i!=="$?"&&i!=="$~"&&i!=="&"||a++}e=e.nextSibling}return null}function lb(e){e=e.previousSibling;for(var a=0;e;){if(e.nodeType===8){var i=e.data;if(i==="$"||i==="$!"||i==="$?"||i==="$~"||i==="&"){if(a===0)return e;a--}else i!=="/$"&&i!=="/&"||a++}e=e.previousSibling}return null}function cb(e,a,i){switch(a=cp(i),e){case"html":if(e=a.documentElement,!e)throw Error(s(452));return e;case"head":if(e=a.head,!e)throw Error(s(453));return e;case"body":if(e=a.body,!e)throw Error(s(454));return e;default:throw Error(s(451))}}function Pf(e){for(var a=e.attributes;a.length;)e.removeAttributeNode(a[0]);In(e)}var ni=new Map,ub=new Set;function up(e){return typeof e.getRootNode=="function"?e.getRootNode():e.nodeType===9?e:e.ownerDocument}var Zo=L.d;L.d={f:fk,r:mk,D:pk,C:hk,L:gk,m:vk,X:bk,S:yk,M:wk};function fk(){var e=Zo.f(),a=tp();return e||a}function mk(e){var a=Cn(e);a!==null&&a.tag===5&&a.type==="form"?Zu(a):Zo.r(e)}var xd=typeof document>"u"?null:document;function db(e,a,i){var c=xd;if(c&&typeof a=="string"&&a){var p=nn(a);p='link[rel="'+e+'"][href="'+p+'"]',typeof i=="string"&&(p+='[crossorigin="'+i+'"]'),ub.has(p)||(ub.add(p),e={rel:e,crossOrigin:i,href:a},c.querySelector(p)===null&&(a=c.createElement("link"),hr(a,"link",e),Ce(a),c.head.appendChild(a)))}}function pk(e){Zo.D(e),db("dns-prefetch",e,null)}function hk(e,a){Zo.C(e,a),db("preconnect",e,a)}function gk(e,a,i){Zo.L(e,a,i);var c=xd;if(c&&e&&a){var p='link[rel="preload"][as="'+nn(a)+'"]';a==="image"&&i&&i.imageSrcSet?(p+='[imagesrcset="'+nn(i.imageSrcSet)+'"]',typeof i.imageSizes=="string"&&(p+='[imagesizes="'+nn(i.imageSizes)+'"]')):p+='[href="'+nn(e)+'"]';var v=p;switch(a){case"style":v=Sd(e);break;case"script":v=Cd(e)}ni.has(v)||(e=b({rel:"preload",href:a==="image"&&i&&i.imageSrcSet?void 0:e,as:a},i),ni.set(v,e),c.querySelector(p)!==null||a==="style"&&c.querySelector(_f(v))||a==="script"&&c.querySelector(Of(v))||(a=c.createElement("link"),hr(a,"link",e),Ce(a),c.head.appendChild(a)))}}function vk(e,a){Zo.m(e,a);var i=xd;if(i&&e){var c=a&&typeof a.as=="string"?a.as:"script",p='link[rel="modulepreload"][as="'+nn(c)+'"][href="'+nn(e)+'"]',v=p;switch(c){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":v=Cd(e)}if(!ni.has(v)&&(e=b({rel:"modulepreload",href:e},a),ni.set(v,e),i.querySelector(p)===null)){switch(c){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(i.querySelector(Of(v)))return}c=i.createElement("link"),hr(c,"link",e),Ce(c),i.head.appendChild(c)}}}function yk(e,a,i){Zo.S(e,a,i);var c=xd;if(c&&e){var p=kn(c).hoistableStyles,v=Sd(e);a=a||"default";var M=p.get(v);if(!M){var _={loading:0,preload:null};if(M=c.querySelector(_f(v)))_.loading=5;else{e=b({rel:"stylesheet",href:e,"data-precedence":a},i),(i=ni.get(v))&&dg(e,i);var Z=M=c.createElement("link");Ce(Z),hr(Z,"link",e),Z._p=new Promise(function(we,Re){Z.onload=we,Z.onerror=Re}),Z.addEventListener("load",function(){_.loading|=1}),Z.addEventListener("error",function(){_.loading|=2}),_.loading|=4,dp(M,a,c)}M={type:"stylesheet",instance:M,count:1,state:_},p.set(v,M)}}}function bk(e,a){Zo.X(e,a);var i=xd;if(i&&e){var c=kn(i).hoistableScripts,p=Cd(e),v=c.get(p);v||(v=i.querySelector(Of(p)),v||(e=b({src:e,async:!0},a),(a=ni.get(p))&&fg(e,a),v=i.createElement("script"),Ce(v),hr(v,"link",e),i.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},c.set(p,v))}}function wk(e,a){Zo.M(e,a);var i=xd;if(i&&e){var c=kn(i).hoistableScripts,p=Cd(e),v=c.get(p);v||(v=i.querySelector(Of(p)),v||(e=b({src:e,async:!0,type:"module"},a),(a=ni.get(p))&&fg(e,a),v=i.createElement("script"),Ce(v),hr(v,"link",e),i.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},c.set(p,v))}}function fb(e,a,i,c){var p=(p=Ze.current)?up(p):null;if(!p)throw Error(s(446));switch(e){case"meta":case"title":return null;case"style":return typeof i.precedence=="string"&&typeof i.href=="string"?(a=Sd(i.href),i=kn(p).hoistableStyles,c=i.get(a),c||(c={type:"style",instance:null,count:0,state:null},i.set(a,c)),c):{type:"void",instance:null,count:0,state:null};case"link":if(i.rel==="stylesheet"&&typeof i.href=="string"&&typeof i.precedence=="string"){e=Sd(i.href);var v=kn(p).hoistableStyles,M=v.get(e);if(M||(p=p.ownerDocument||p,M={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},v.set(e,M),(v=p.querySelector(_f(e)))&&!v._p&&(M.instance=v,M.state.loading=5),ni.has(e)||(i={rel:"preload",as:"style",href:i.href,crossOrigin:i.crossOrigin,integrity:i.integrity,media:i.media,hrefLang:i.hrefLang,referrerPolicy:i.referrerPolicy},ni.set(e,i),v||xk(p,e,i,M.state))),a&&c===null)throw Error(s(528,""));return M}if(a&&c!==null)throw Error(s(529,""));return null;case"script":return a=i.async,i=i.src,typeof i=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=Cd(i),i=kn(p).hoistableScripts,c=i.get(a),c||(c={type:"script",instance:null,count:0,state:null},i.set(a,c)),c):{type:"void",instance:null,count:0,state:null};default:throw Error(s(444,e))}}function Sd(e){return'href="'+nn(e)+'"'}function _f(e){return'link[rel="stylesheet"]['+e+"]"}function mb(e){return b({},e,{"data-precedence":e.precedence,precedence:null})}function xk(e,a,i,c){e.querySelector('link[rel="preload"][as="style"]['+a+"]")?c.loading=1:(a=e.createElement("link"),c.preload=a,a.addEventListener("load",function(){return c.loading|=1}),a.addEventListener("error",function(){return c.loading|=2}),hr(a,"link",i),Ce(a),e.head.appendChild(a))}function Cd(e){return'[src="'+nn(e)+'"]'}function Of(e){return"script[async]"+e}function pb(e,a,i){if(a.count++,a.instance===null)switch(a.type){case"style":var c=e.querySelector('style[data-href~="'+nn(i.href)+'"]');if(c)return a.instance=c,Ce(c),c;var p=b({},i,{"data-href":i.href,"data-precedence":i.precedence,href:null,precedence:null});return c=(e.ownerDocument||e).createElement("style"),Ce(c),hr(c,"style",p),dp(c,i.precedence,e),a.instance=c;case"stylesheet":p=Sd(i.href);var v=e.querySelector(_f(p));if(v)return a.state.loading|=4,a.instance=v,Ce(v),v;c=mb(i),(p=ni.get(p))&&dg(c,p),v=(e.ownerDocument||e).createElement("link"),Ce(v);var M=v;return M._p=new Promise(function(_,Z){M.onload=_,M.onerror=Z}),hr(v,"link",c),a.state.loading|=4,dp(v,i.precedence,e),a.instance=v;case"script":return v=Cd(i.src),(p=e.querySelector(Of(v)))?(a.instance=p,Ce(p),p):(c=i,(p=ni.get(v))&&(c=b({},i),fg(c,p)),e=e.ownerDocument||e,p=e.createElement("script"),Ce(p),hr(p,"link",c),e.head.appendChild(p),a.instance=p);case"void":return null;default:throw Error(s(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(c=a.instance,a.state.loading|=4,dp(c,i.precedence,e));return a.instance}function dp(e,a,i){for(var c=i.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),p=c.length?c[c.length-1]:null,v=p,M=0;M<c.length;M++){var _=c[M];if(_.dataset.precedence===a)v=_;else if(v!==p)break}v?v.parentNode.insertBefore(e,v.nextSibling):(a=i.nodeType===9?i.head:i,a.insertBefore(e,a.firstChild))}function dg(e,a){e.crossOrigin==null&&(e.crossOrigin=a.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=a.referrerPolicy),e.title==null&&(e.title=a.title)}function fg(e,a){e.crossOrigin==null&&(e.crossOrigin=a.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=a.referrerPolicy),e.integrity==null&&(e.integrity=a.integrity)}var fp=null;function hb(e,a,i){if(fp===null){var c=new Map,p=fp=new Map;p.set(i,c)}else p=fp,c=p.get(i),c||(c=new Map,p.set(i,c));if(c.has(e))return c;for(c.set(e,null),i=i.getElementsByTagName(e),p=0;p<i.length;p++){var v=i[p];if(!(v[Jt]||v[se]||e==="link"&&v.getAttribute("rel")==="stylesheet")&&v.namespaceURI!=="http://www.w3.org/2000/svg"){var M=v.getAttribute(a)||"";M=e+M;var _=c.get(M);_?_.push(v):c.set(M,[v])}}return c}function gb(e,a,i){e=e.ownerDocument||e,e.head.insertBefore(i,a==="title"?e.querySelector("head > title"):null)}function Sk(e,a,i){if(i===1||a.itemProp!=null)return!1;switch(e){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;return a.rel==="stylesheet"?(e=a.disabled,typeof a.precedence=="string"&&e==null):!0;case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function vb(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function Ck(e,a,i,c){if(i.type==="stylesheet"&&(typeof c.media!="string"||matchMedia(c.media).matches!==!1)&&(i.state.loading&4)===0){if(i.instance===null){var p=Sd(c.href),v=a.querySelector(_f(p));if(v){a=v._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(e.count++,e=mp.bind(e),a.then(e,e)),i.state.loading|=4,i.instance=v,Ce(v);return}v=a.ownerDocument||a,c=mb(c),(p=ni.get(p))&&dg(c,p),v=v.createElement("link"),Ce(v);var M=v;M._p=new Promise(function(_,Z){M.onload=_,M.onerror=Z}),hr(v,"link",c),i.instance=v}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(i,a),(a=i.state.preload)&&(i.state.loading&3)===0&&(e.count++,i=mp.bind(e),a.addEventListener("load",i),a.addEventListener("error",i))}}var mg=0;function kk(e,a){return e.stylesheets&&e.count===0&&hp(e,e.stylesheets),0<e.count||0<e.imgCount?function(i){var c=setTimeout(function(){if(e.stylesheets&&hp(e,e.stylesheets),e.unsuspend){var v=e.unsuspend;e.unsuspend=null,v()}},6e4+a);0<e.imgBytes&&mg===0&&(mg=62500*rk());var p=setTimeout(function(){if(e.waitingForImages=!1,e.count===0&&(e.stylesheets&&hp(e,e.stylesheets),e.unsuspend)){var v=e.unsuspend;e.unsuspend=null,v()}},(e.imgBytes>mg?50:800)+a);return e.unsuspend=i,function(){e.unsuspend=null,clearTimeout(c),clearTimeout(p)}}:null}function mp(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)hp(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var pp=null;function hp(e,a){e.stylesheets=null,e.unsuspend!==null&&(e.count++,pp=new Map,a.forEach(Mk,e),pp=null,mp.call(e))}function Mk(e,a){if(!(a.state.loading&4)){var i=pp.get(e);if(i)var c=i.get(null);else{i=new Map,pp.set(e,i);for(var p=e.querySelectorAll("link[data-precedence],style[data-precedence]"),v=0;v<p.length;v++){var M=p[v];(M.nodeName==="LINK"||M.getAttribute("media")!=="not all")&&(i.set(M.dataset.precedence,M),c=M)}c&&i.set(null,c)}p=a.instance,M=p.getAttribute("data-precedence"),v=i.get(M)||c,v===c&&i.set(null,p),i.set(M,p),this.count++,c=mp.bind(this),p.addEventListener("load",c),p.addEventListener("error",c),v?v.parentNode.insertBefore(p,v.nextSibling):(e=e.nodeType===9?e.head:e,e.insertBefore(p,e.firstChild)),a.state.loading|=4}}var Ff={$$typeof:P,Provider:null,Consumer:null,_currentValue:le,_currentValue2:le,_threadCount:0};function Ak(e,a,i,c,p,v,M,_,Z){this.tag=1,this.containerInfo=e,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=ha(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=ha(0),this.hiddenUpdates=ha(null),this.identifierPrefix=c,this.onUncaughtError=p,this.onCaughtError=v,this.onRecoverableError=M,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=Z,this.incompleteTransitions=new Map}function yb(e,a,i,c,p,v,M,_,Z,we,Re,_e){return e=new Ak(e,a,i,M,Z,we,Re,_e,_),a=1,v===!0&&(a|=24),v=Jr(3,null,null,a),e.current=v,v.stateNode=e,a=Dc(),a.refCount++,e.pooledCache=a,a.refCount++,v.memoizedState={element:c,isDehydrated:i,cache:a},kl(v),e}function bb(e){return e?(e=vl,e):vl}function wb(e,a,i,c,p,v){p=bb(p),c.context===null?c.context=p:c.pendingContext=p,c=da(a),c.payload={element:i},v=v===void 0?null:v,v!==null&&(c.callback=v),i=La(e,c,a),i!==null&&(ds(i,e,a),Qi(i,e,a))}function xb(e,a){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var i=e.retryLane;e.retryLane=i!==0&&i<a?i:a}}function pg(e,a){xb(e,a),(e=e.alternate)&&xb(e,a)}function Sb(e){if(e.tag===13||e.tag===31){var a=_n(e,67108864);a!==null&&ds(a,e,67108864),pg(e,67108864)}}function Cb(e){if(e.tag===13||e.tag===31){var a=Is();a=Pt(a);var i=_n(e,a);i!==null&&ds(i,e,a),pg(e,a)}}var gp=!0;function Tk(e,a,i,c){var p=U.T;U.T=null;var v=L.p;try{L.p=2,hg(e,a,i,c)}finally{L.p=v,U.T=p}}function Nk(e,a,i,c){var p=U.T;U.T=null;var v=L.p;try{L.p=8,hg(e,a,i,c)}finally{L.p=v,U.T=p}}function hg(e,a,i,c){if(gp){var p=gg(c);if(p===null)tg(e,a,c,vp,i),Mb(e,c);else if(Ek(p,e,a,i,c))c.stopPropagation();else if(Mb(e,c),a&4&&-1<Rk.indexOf(e)){for(;p!==null;){var v=Cn(p);if(v!==null)switch(v.tag){case 3:if(v=v.stateNode,v.current.memoizedState.isDehydrated){var M=wt(v.pendingLanes);if(M!==0){var _=v;for(_.pendingLanes|=2,_.entangledLanes|=2;M;){var Z=1<<31-je(M);_.entanglements[1]|=Z,M&=~Z}io(v),(tt&6)===0&&(Jm=B()+500,Df(0))}}break;case 31:case 13:_=_n(v,2),_!==null&&ds(_,v,2),tp(),pg(v,2)}if(v=gg(c),v===null&&tg(e,a,c,vp,i),v===p)break;p=v}p!==null&&c.stopPropagation()}else tg(e,a,c,null,i)}}function gg(e){return e=bs(e),vg(e)}var vp=null;function vg(e){if(vp=null,e=zn(e),e!==null){var a=u(e);if(a===null)e=null;else{var i=a.tag;if(i===13){if(e=f(a),e!==null)return e;e=null}else if(i===31){if(e=h(a),e!==null)return e;e=null}else if(i===3){if(a.stateNode.current.memoizedState.isDehydrated)return a.tag===3?a.stateNode.containerInfo:null;e=null}else a!==e&&(e=null)}}return vp=e,null}function kb(e){switch(e){case"beforetoggle":case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"toggle":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 2;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 8;case"message":switch(Oe()){case We:return 2;case et:return 8;case it:case ye:return 32;case Ne:return 268435456;default:return 32}default:return 32}}var yg=!1,Kl=null,Ql=null,Yl=null,Bf=new Map,Hf=new Map,Xl=[],Rk="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(" ");function Mb(e,a){switch(e){case"focusin":case"focusout":Kl=null;break;case"dragenter":case"dragleave":Ql=null;break;case"mouseover":case"mouseout":Yl=null;break;case"pointerover":case"pointerout":Bf.delete(a.pointerId);break;case"gotpointercapture":case"lostpointercapture":Hf.delete(a.pointerId)}}function zf(e,a,i,c,p,v){return e===null||e.nativeEvent!==v?(e={blockedOn:a,domEventName:i,eventSystemFlags:c,nativeEvent:v,targetContainers:[p]},a!==null&&(a=Cn(a),a!==null&&Sb(a)),e):(e.eventSystemFlags|=c,a=e.targetContainers,p!==null&&a.indexOf(p)===-1&&a.push(p),e)}function Ek(e,a,i,c,p){switch(a){case"focusin":return Kl=zf(Kl,e,a,i,c,p),!0;case"dragenter":return Ql=zf(Ql,e,a,i,c,p),!0;case"mouseover":return Yl=zf(Yl,e,a,i,c,p),!0;case"pointerover":var v=p.pointerId;return Bf.set(v,zf(Bf.get(v)||null,e,a,i,c,p)),!0;case"gotpointercapture":return v=p.pointerId,Hf.set(v,zf(Hf.get(v)||null,e,a,i,c,p)),!0}return!1}function Ab(e){var a=zn(e.target);if(a!==null){var i=u(a);if(i!==null){if(a=i.tag,a===13){if(a=f(i),a!==null){e.blockedOn=a,_t(e.priority,function(){Cb(i)});return}}else if(a===31){if(a=h(i),a!==null){e.blockedOn=a,_t(e.priority,function(){Cb(i)});return}}else if(a===3&&i.stateNode.current.memoizedState.isDehydrated){e.blockedOn=i.tag===3?i.stateNode.containerInfo:null;return}}}e.blockedOn=null}function yp(e){if(e.blockedOn!==null)return!1;for(var a=e.targetContainers;0<a.length;){var i=gg(e.nativeEvent);if(i===null){i=e.nativeEvent;var c=new i.constructor(i.type,i);Cu=c,i.target.dispatchEvent(c),Cu=null}else return a=Cn(i),a!==null&&Sb(a),e.blockedOn=i,!1;a.shift()}return!0}function Tb(e,a,i){yp(e)&&i.delete(a)}function jk(){yg=!1,Kl!==null&&yp(Kl)&&(Kl=null),Ql!==null&&yp(Ql)&&(Ql=null),Yl!==null&&yp(Yl)&&(Yl=null),Bf.forEach(Tb),Hf.forEach(Tb)}function bp(e,a){e.blockedOn===a&&(e.blockedOn=null,yg||(yg=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,jk)))}var wp=null;function Nb(e){wp!==e&&(wp=e,t.unstable_scheduleCallback(t.unstable_NormalPriority,function(){wp===e&&(wp=null);for(var a=0;a<e.length;a+=3){var i=e[a],c=e[a+1],p=e[a+2];if(typeof c!="function"){if(vg(c||i)===null)continue;break}var v=Cn(i);v!==null&&(e.splice(a,3),a-=3,Gc(v,{pending:!0,data:p,method:i.method,action:c},c,p))}}))}function kd(e){function a(Z){return bp(Z,e)}Kl!==null&&bp(Kl,e),Ql!==null&&bp(Ql,e),Yl!==null&&bp(Yl,e),Bf.forEach(a),Hf.forEach(a);for(var i=0;i<Xl.length;i++){var c=Xl[i];c.blockedOn===e&&(c.blockedOn=null)}for(;0<Xl.length&&(i=Xl[0],i.blockedOn===null);)Ab(i),i.blockedOn===null&&Xl.shift();if(i=(e.ownerDocument||e).$$reactFormReplay,i!=null)for(c=0;c<i.length;c+=3){var p=i[c],v=i[c+1],M=p[ze]||null;if(typeof v=="function")M||Nb(i);else if(M){var _=null;if(v&&v.hasAttribute("formAction")){if(p=v,M=v[ze]||null)_=M.formAction;else if(vg(p)!==null)continue}else _=M.action;typeof _=="function"?i[c+1]=_:(i.splice(c,3),c-=3),Nb(i)}}}function Rb(){function e(v){v.canIntercept&&v.info==="react-transition"&&v.intercept({handler:function(){return new Promise(function(M){return p=M})},focusReset:"manual",scroll:"manual"})}function a(){p!==null&&(p(),p=null),c||setTimeout(i,20)}function i(){if(!c&&!navigation.transition){var v=navigation.currentEntry;v&&v.url!=null&&navigation.navigate(v.url,{state:v.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var c=!1,p=null;return navigation.addEventListener("navigate",e),navigation.addEventListener("navigatesuccess",a),navigation.addEventListener("navigateerror",a),setTimeout(i,100),function(){c=!0,navigation.removeEventListener("navigate",e),navigation.removeEventListener("navigatesuccess",a),navigation.removeEventListener("navigateerror",a),p!==null&&(p(),p=null)}}}function bg(e){this._internalRoot=e}xp.prototype.render=bg.prototype.render=function(e){var a=this._internalRoot;if(a===null)throw Error(s(409));var i=a.current,c=Is();wb(i,c,e,a,null,null)},xp.prototype.unmount=bg.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var a=e.containerInfo;wb(e.current,2,null,e,null,null),tp(),a[st]=null}};function xp(e){this._internalRoot=e}xp.prototype.unstable_scheduleHydration=function(e){if(e){var a=Dr();e={blockedOn:null,target:e,priority:a};for(var i=0;i<Xl.length&&a!==0&&a<Xl[i].priority;i++);Xl.splice(i,0,e),i===0&&Ab(e)}};var Eb=n.version;if(Eb!=="19.2.7")throw Error(s(527,Eb,"19.2.7"));L.findDOMNode=function(e){var a=e._reactInternals;if(a===void 0)throw typeof e.render=="function"?Error(s(188)):(e=Object.keys(e).join(","),Error(s(268,e)));return e=y(a),e=e!==null?w(e):null,e=e===null?null:e.stateNode,e};var Dk={bundleType:0,version:"19.2.7",rendererPackageName:"react-dom",currentDispatcherRef:U,reconcilerVersion:"19.2.7"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Sp=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Sp.isDisabled&&Sp.supportsFiber)try{ae=Sp.inject(Dk),fe=Sp}catch{}}return Uf.createRoot=function(e,a){if(!l(e))throw Error(s(299));var i=!1,c="",p=hf,v=gf,M=Pl;return a!=null&&(a.unstable_strictMode===!0&&(i=!0),a.identifierPrefix!==void 0&&(c=a.identifierPrefix),a.onUncaughtError!==void 0&&(p=a.onUncaughtError),a.onCaughtError!==void 0&&(v=a.onCaughtError),a.onRecoverableError!==void 0&&(M=a.onRecoverableError)),a=yb(e,1,!1,null,null,i,c,null,p,v,M,Rb),e[st]=a.current,eg(e),new bg(a)},Uf.hydrateRoot=function(e,a,i){if(!l(e))throw Error(s(299));var c=!1,p="",v=hf,M=gf,_=Pl,Z=null;return i!=null&&(i.unstable_strictMode===!0&&(c=!0),i.identifierPrefix!==void 0&&(p=i.identifierPrefix),i.onUncaughtError!==void 0&&(v=i.onUncaughtError),i.onCaughtError!==void 0&&(M=i.onCaughtError),i.onRecoverableError!==void 0&&(_=i.onRecoverableError),i.formState!==void 0&&(Z=i.formState)),a=yb(e,1,!0,a,i??null,c,p,Z,v,M,_,Rb),a.context=bb(null),i=a.current,c=Is(),c=Pt(c),p=da(c),p.callback=null,La(i,p,c),i=c,a.current.lanes=i,hn(a,i),io(a),e[st]=a.current,eg(e),new xp(a)},Uf.version="19.2.7",Uf}var Wb;function xM(){if(Wb)return Cg.exports;Wb=1;function t(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(n){console.error(n)}}return t(),Cg.exports=wM(),Cg.exports}var SM=xM();const CM="https://otbyfkjxrkngvjziawki.supabase.co",kM="sb_publishable_NpUs0RDJH2YnllsqTKO6TQ_1jTdSsNQ",MM={getItem:()=>null,setItem:()=>{},removeItem:()=>{}},Ag=typeof window<"u"&&!!window.liveDesk,zt=hM(CM,kM,{auth:{autoRefreshToken:!Ag,persistSession:!Ag,storage:Ag?MM:void 0,detectSessionInUrl:!0,flowType:"pkce",storageKey:"livedesk.mindexec.supabase.auth"}}),AM=new Set(["browserLanguage","platform","online","viewport","timezone","screen"]),TM={id:"browser-safe-v1",collect(){if(typeof navigator>"u")return{};const t={browserLanguage:navigator.language||"",platform:navigator.platform||"",online:navigator.onLine,timezone:typeof Intl>"u"?"":Intl.DateTimeFormat().resolvedOptions().timeZone||"",viewport:typeof window>"u"?void 0:{width:window.innerWidth,height:window.innerHeight},screen:typeof window>"u"?void 0:{width:window.screen.width,height:window.screen.height}};return Object.fromEntries(Object.entries(t).filter(([n,r])=>AM.has(n)&&r!==void 0))}};function NM(t,n="Support request failed."){if(t&&typeof t=="object"&&"message"in t){const r=String(t.message||"").trim();if(r)return r.replace(/^.*Support request failed:\s*/i,"")}return t instanceof Error?t.message:n}function RM(t=TM){return t.collect()}async function EM(t,n="livedesk"){const{data:r,error:s}=await zt.from("app_admins").select("role").eq("user_id",t).limit(1);if(s)throw s;const l=r?.[0]?.role||"user";if(l!=="owner"){const{error:k}=await zt.rpc("register_product_access",{p_product_key:n,p_access_type:"free"});if(k)throw k}const[u,f,h]=await Promise.all([zt.from("products").select("id, product_key, name, description, sort_order").order("sort_order"),zt.from("product_admins").select("product_id, role").eq("user_id",t),zt.from("user_products").select("product_id").eq("user_id",t).eq("is_active",!0)]);if(u.error)throw u.error;if(f.error)throw f.error;if(h.error)throw h.error;const g=u.data||[],y=(f.data||[]).map(k=>String(k.product_id)),w=(h.data||[]).map(k=>String(k.product_id)),b=l==="owner",S=b?g.map(k=>k.id):[...new Set([...y,...w])];return{products:g,access:{userId:t,globalRole:l,accessibleProductIds:S,managedProductIds:b?g.map(k=>k.id):y,canViewAllProducts:b,canViewAllPrivatePosts:b,canManageAllProducts:b,canCreateAnnouncements:b||y.length>0}}}async function jM(t=""){const{data:n,error:r}=await zt.rpc("search_support_posts",{p_query:t.trim()||null,p_limit:250});if(r)throw r;return n||[]}async function DM(t){const{data:n,error:r}=await zt.from("support_attachments").select("*").eq("post_id",t).order("created_at");if(r)throw r;const s=n||[];return Promise.all(s.map(async l=>{const u=await zt.storage.from("support-attachments").createSignedUrl(l.storage_path,3600);return{...l,signed_url:u.data?.signedUrl||void 0}}))}async function IM(){const{data:t,error:n}=await zt.from("support_notifications").select("*").order("created_at",{ascending:!1}).limit(30);if(n)throw n;return t||[]}async function LM(t){const{error:n}=await zt.rpc("mark_support_notification_read",{p_notification_id:t});if(n)throw n}async function Gb(t){const{data:n,error:r}=await zt.from("support_comments").select("*").eq("post_id",t).order("created_at");if(r)throw r;return n||[]}async function PM(t){const{data:n,error:r}=await zt.from("support_votes").select("post_id").eq("user_id",t);if(r)throw r;return new Set((n||[]).map(s=>String(s.post_id)))}async function _M(t){const{data:n,error:r}=await zt.rpc("create_support_post",{p_product_id:t.productId,p_post_type:t.postType,p_title:t.title,p_body:t.body,p_visibility:t.visibility,p_app_version:t.appVersion||null,p_platform:typeof navigator>"u"?null:navigator.platform||null,p_os_version:typeof navigator>"u"?null:navigator.platform||null,p_environment:t.includeEnvironment?RM():{}});if(r)throw r;const s=Array.isArray(n)?n[0]?.post_id:n?.post_id;if(!s)throw new Error("Support post was not created.");return String(s)}const OM=new Set(["image/png","image/jpeg","image/webp","text/plain","text/markdown","application/json","application/pdf"]);async function FM(t,n){if(!OM.has(n.type))throw new Error("This file type is not allowed.");if(n.size<=0||n.size>10*1024*1024)throw new Error("Attachments must be smaller than 10 MB.");const r=n.name.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"attachment",s=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`,l=`${t}/${s}-${r}`,u=await zt.storage.from("support-attachments").upload(l,n,{contentType:n.type,upsert:!1});if(u.error)throw u.error;const{data:f,error:h}=await zt.rpc("add_support_attachment",{p_post_id:t,p_storage_path:l,p_file_name:r,p_mime_type:n.type,p_size_bytes:n.size});if(h)throw await zt.storage.from("support-attachments").remove([l]),h;const g=Array.isArray(f)?f[0]?.attachment_id:f?.attachment_id;if(!g)throw new Error("Attachment metadata was not created.");return String(g)}async function BM(t,n,r,s){const{error:l}=await zt.rpc("update_support_post",{p_post_id:t,p_title:n,p_body:r,p_visibility:s});if(l)throw l}async function HM(t,n){const{error:r}=await zt.rpc("add_support_comment",{p_post_id:t,p_body:n});if(r)throw r}async function zM(t){const{data:n,error:r}=await zt.rpc("toggle_support_vote",{p_post_id:t});if(r)throw r;const s=Array.isArray(n)?n[0]:n;return{voted:!!s?.voted,totalVotes:Number(s?.total_votes||0)}}async function $M(t,n){const{error:r}=await zt.rpc("change_support_post_status",{p_post_id:t,p_target_status:n});if(r)throw r}async function UM(t){const{error:n}=await zt.rpc("set_support_post_hidden",{p_post_id:t,p_hidden:!0});if(n)throw n}async function qM(t,n){const{error:r}=await zt.rpc("set_support_post_locked",{p_post_id:t,p_locked:n});if(r)throw r}async function WM(t,n){const{error:r}=await zt.rpc("set_support_post_pinned",{p_post_id:t,p_pinned:n});if(r)throw r}async function GM(t,n){const{error:r}=await zt.rpc("mark_support_duplicate",{p_post_id:t,p_duplicate_of_post_id:n});if(r)throw r}async function VM(t,n){const{error:r}=await zt.rpc("accept_support_answer",{p_post_id:t,p_comment_id:n});if(r)throw r}async function KM(t,n=!0){const{error:r}=await zt.rpc("hide_support_comment",{p_comment_id:t,p_hidden:n});if(r)throw r}const mv=[{id:"question",label:"Questions",shortLabel:"Question"},{id:"issue",label:"Issues",shortLabel:"Issue"},{id:"feature",label:"Feature Requests",shortLabel:"Feature"},{id:"announcement",label:"Announcements",shortLabel:"Announcement"}],QM=[{id:"all",label:"All statuses"},{id:"needs-response",label:"Needs response"},{id:"open",label:"Open"},{id:"needs-info",label:"Needs more information"},{id:"in-progress",label:"In progress"},{id:"planned",label:"Planned"},{id:"released",label:"Released"},{id:"closed",label:"Closed"}],YM={question:["open","answered","resolved","closed"],issue:["open","needs-info","confirmed","in-progress","fixed","closed"],feature:["under-review","planned","in-progress","released","declined","closed"],announcement:["published","archived"]},XM={type:"all",product:"",status:"all",visibility:"all",sort:"recent",query:""};function Tg(){if(typeof window>"u")return XM;const t=new URLSearchParams(window.location.search),n=window.location.pathname.match(/^\/support\/(questions|issues|features|announcements)$/)?.[1],r=t.get("type")||n||"",s=r==="questions"||r==="question"?"question":r==="issues"||r==="issue"?"issue":r==="features"||r==="feature"?"feature":r==="announcements"||r==="announcement"?"announcement":"all",l=t.get("visibility"),u=t.get("sort");return{type:s,product:t.get("product")||"",status:t.get("status")||"all",visibility:l==="public"||l==="private"?l:"all",sort:u==="votes"||u==="newest"?u:"recent",query:t.get("q")||""}}function ZM(t){return t==="all"?"":t==="question"?"questions":t==="issue"?"issues":t==="feature"?"features":"announcements"}function JM(t,n){const r={...t,...n},s=new URLSearchParams;r.product&&s.set("product",r.product),r.status!=="all"&&s.set("status",r.status),r.visibility!=="all"&&s.set("visibility",r.visibility),r.sort!=="recent"&&s.set("sort",r.sort),r.query&&s.set("q",r.query);const l=ZM(r.type),u=s.toString();return`/support${l?`/${l}`:""}${u?`?${u}`:""}`}function Cp(t){const n=new Date(t);return Number.isFinite(n.getTime())?n.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"}):t}function Ng(t){return t.replaceAll("-"," ").replace(/\b\w/g,n=>n.toUpperCase())}function Vb(t){return t==="question"?Fk:t==="issue"?f0:t==="feature"?Bk:Hk}function Kb(t){return mv.find(n=>n.id===t)?.shortLabel||t}function Rg(t,n){return t.find(r=>r.id===n)?.name||"Product"}function fs(t){const n=NM(t);return/relation .* does not exist|function .* does not exist|schema cache/i.test(n)?"Support Board database is not installed yet. Apply the latest Supabase migration first.":/not-authenticated|jwt/i.test(n)?"Sign in again to use Support.":/product-access-denied|product-not-found/i.test(n)?"You do not have access to this product.":n}function T0({session:t,currentProductKey:n="livedesk",appVersion:r="",onSignIn:s}){const[l,u]=d.useState(()=>Tg()),[f,h]=d.useState(null),[g,y]=d.useState([]),[w,b]=d.useState([]),[S,k]=d.useState(""),[A,T]=d.useState([]),[j,I]=d.useState([]),[N,P]=d.useState([]),[H,F]=d.useState(()=>new Set),[$,D]=d.useState(!0),[K,z]=d.useState(""),[q,W]=d.useState(""),[Y,V]=d.useState(!1),[he,ee]=d.useState(!1),[U,L]=d.useState(""),[le,ve]=d.useState(()=>Tg().query),[J,Ae]=d.useState(!1),[ce,Te]=d.useState(!1),[Fe,$e]=d.useState(""),[Ze,de]=d.useState(""),[Be,Ve]=d.useState("free"),[Je,Qe]=d.useState(""),[yt,ne]=d.useState(""),[me,Ge]=d.useState("admin"),[Se,ge]=d.useState(""),[Ue,Me]=d.useState(""),[rt,At]=d.useState(""),[O,qe]=d.useState(""),[B,Oe]=d.useState(""),[We,et]=d.useState([]),[it,ye]=d.useState({productId:"",postType:"question",title:"",body:"",visibility:"public",includeEnvironment:!0,files:[]}),Ne=d.useCallback(G=>{const ot={...l,...G};u(ot),typeof window<"u"&&window.history.pushState({},"",JM(l,G))},[l]);d.useEffect(()=>{const G=()=>u(Tg());return window.addEventListener("popstate",G),()=>window.removeEventListener("popstate",G)},[]);const He=d.useCallback(async()=>{const G=await jM(l.query);return b(G),t?.user.id&&F(await PM(t.user.id)),G},[l.query,t?.user.id]),pe=d.useCallback(async()=>{if(!t?.user.id){h(null),y([]),b([]),k(""),P([]),D(!1);return}D(!0),W("");try{const G=await EM(t.user.id,n);h(G.access),y(G.products),await He(),P(await IM())}catch(G){W(fs(G))}finally{D(!1)}},[n,He,t?.user.id]);d.useEffect(()=>{pe()},[pe]);const ae=d.useMemo(()=>f?f.canViewAllProducts?g:g.filter(G=>f.accessibleProductIds.includes(G.id)):[],[f,g]),fe=d.useMemo(()=>{const G=ae.find(ot=>ot.product_key===l.product);return f?.canViewAllProducts&&!l.product||l.product==="all"&&f?.canViewAllProducts?"all":G?G.product_key:ae.some(ot=>ot.product_key===n)?n:ae[0]?.product_key||""},[f?.canViewAllProducts,ae,n,l.product]),Ee=fe==="all"?"":ae.find(G=>G.product_key===fe)?.id||"",je=d.useMemo(()=>{const G=new Map(g.map(Pt=>[Pt.id,Pt.product_key]));return[...w.filter(Pt=>l.type!=="all"&&Pt.post_type!==l.type||fe!=="all"&&Ee&&Pt.product_id!==Ee||l.status==="needs-response"&&!["open","needs-info"].includes(Pt.status)||l.status!=="all"&&l.status!=="needs-response"&&Pt.status!==l.status||l.visibility!=="all"&&Pt.visibility!==l.visibility?!1:G.has(Pt.product_id))].sort((Pt,an)=>l.sort==="votes"?an.vote_count-Pt.vote_count||an.updated_at.localeCompare(Pt.updated_at):l.sort==="newest"?an.created_at.localeCompare(Pt.created_at):Number(an.is_pinned)-Number(Pt.is_pinned)||an.updated_at.localeCompare(Pt.updated_at))},[w,g,l.sort,l.status,l.type,l.visibility,Ee,fe]),De=je.find(G=>G.id===S)||je[0]||null,Et=!!(De&&f&&(f.canViewAllProducts||f.managedProductIds.includes(De.product_id))),at=!!(De&&t?.user.id===De.author_id)||Et;d.useEffect(()=>{if(!De){k(""),T([]),ee(!1);return}De.id!==S&&k(De.id)},[De,S]),d.useEffect(()=>{let G=!0;return S?(Gb(S).then(ot=>{G&&T(ot)}).catch(ot=>{G&&W(fs(ot))}),DM(S).then(ot=>{G&&I(ot)}).catch(ot=>{G&&W(fs(ot))}),()=>{G=!1}):(T([]),I([]),()=>{G=!1})},[S]),d.useEffect(()=>{!it.productId&&ae[0]&&ye(G=>({...G,productId:Ee||ae[0].id}))},[ae,it.productId,Ee]),d.useEffect(()=>{ve(l.query)},[l.query]),d.useEffect(()=>{!Ze&&ae[0]&&de(ae[0].id),!yt&&ae[0]&&ne(ae[0].id)},[ae,Ze,yt]);const ft=G=>{De&&b(ot=>ot.map(Pt=>Pt.id===De.id?{...Pt,...G}:Pt))},jt=async G=>{if(G.preventDefault(),!(!t||!it.productId)){z("create"),W("");try{const ot=await _M({productId:it.productId,postType:it.postType,title:it.title,body:it.body,visibility:it.postType==="announcement"?"public":it.visibility,appVersion:r,includeEnvironment:it.postType==="issue"&&it.includeEnvironment});for(const an of We)await FM(ot,an);const Pt=await He();V(!1),et([]),ye(an=>({...an,title:"",body:"",files:[]})),k(ot),Pt.some(an=>an.id===ot)||await pe()}catch(ot){W(fs(ot))}finally{z("")}}},Ut=async G=>{if(G.preventDefault(),!!De){z("edit"),W("");try{await BM(De.id,De.title,De.body,De.visibility),ee(!1),await He()}catch(ot){W(fs(ot))}finally{z("")}}},wt=async G=>{if(G.preventDefault(),!(!De||!U.trim())){z("comment"),W("");try{await HM(De.id,U),L(""),T(await Gb(De.id)),await He()}catch(ot){W(fs(ot))}finally{z("")}}},Wt=async()=>{if(!(!De||De.post_type!=="feature")){z("vote"),W("");try{const G=await zM(De.id);F(ot=>{const Pt=new Set(ot);return G.voted?Pt.add(De.id):Pt.delete(De.id),Pt}),ft({vote_count:G.totalVotes})}catch(G){W(fs(G))}finally{z("")}}},gt=async G=>{if(De){z("status"),W("");try{await $M(De.id,G),ft({status:G}),await He()}catch(ot){W(fs(ot))}finally{z("")}}},yn=async()=>{if(!(!De||!window.confirm("Hide this Support post from the board?"))){z("hide"),W("");try{await UM(De.id),k(""),await He()}catch(G){W(fs(G))}finally{z("")}}},mt=async()=>{if(De){z("lock"),W("");try{await qM(De.id,!De.is_locked),ft({is_locked:!De.is_locked}),await He()}catch(G){W(fs(G))}finally{z("")}}},ha=async()=>{if(De){z("pin"),W("");try{await WM(De.id,!De.is_pinned),ft({is_pinned:!De.is_pinned}),await He()}catch(G){W(fs(G))}finally{z("")}}},hn=async G=>{if(De){z(`accept-${G}`),W("");try{await VM(De.id,G),ft({accepted_comment_id:G,status:De.post_type==="question"?"answered":De.status}),await He()}catch(ot){W(fs(ot))}finally{z("")}}},na=async()=>{if(!(!De||!O||O===De.id)){z("duplicate"),W("");try{await GM(De.id,O),k(""),qe(""),await He()}catch(G){W(fs(G))}finally{z("")}}},za=async G=>{if(!G.read_at)try{await LM(G.id),P(ot=>ot.map(Pt=>Pt.id===G.id?{...Pt,read_at:new Date().toISOString()}:Pt))}catch(ot){W(fs(ot))}G.post_id&&k(G.post_id),Ae(!1)};return t?$&&!f?o.jsxs("section",{className:"support-page support-loading",children:[o.jsx(vu,{className:"support-spin",size:23})," Loading Support Board..."]}):o.jsxs("section",{className:"support-page",children:[o.jsx("header",{className:"support-page-header support-page-actions-only",children:o.jsxs("div",{className:"support-header-actions",children:[o.jsxs("div",{className:"support-notification-wrap",children:[o.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>Ae(G=>!G),title:"Notifications",children:[o.jsx(Pk,{size:16})," ",N.filter(G=>!G.read_at).length>0&&o.jsx("b",{children:N.filter(G=>!G.read_at).length})]}),J&&o.jsxs("div",{className:"support-notification-popover",children:[o.jsx("strong",{children:"Notifications"}),N.length===0?o.jsx("span",{className:"support-muted",children:"No notifications yet."}):N.map(G=>o.jsxs("button",{type:"button",className:G.read_at?"":"unread",onClick:()=>{za(G)},children:[o.jsx("b",{children:G.title}),o.jsx("span",{children:G.body}),o.jsx("small",{children:Cp(G.created_at)})]},G.id))]})]}),f?.canViewAllProducts&&o.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>Te(G=>!G),children:[o.jsx(Ea,{size:16})," Admin"]}),o.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{pe()},disabled:$,children:[o.jsx(vu,{size:16,className:$?"support-spin":""})," Refresh"]}),o.jsxs("button",{className:"support-primary-button",type:"button",onClick:()=>V(!0),disabled:ae.length===0,children:[o.jsx(Vp,{size:17})," New request"]})]})}),q&&o.jsxs("div",{className:"support-error",role:"alert",children:[o.jsx(vr,{size:17})," ",o.jsx("span",{children:q}),o.jsx("button",{type:"button",onClick:()=>W(""),"aria-label":"Dismiss error",children:o.jsx(vr,{size:15})})]}),Y&&o.jsxs("form",{className:"support-composer",onSubmit:G=>{jt(G)},children:[o.jsxs("div",{className:"support-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"New Support request"}),o.jsx("strong",{children:"Describe one actionable problem or idea."})]}),o.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>V(!1),"aria-label":"Close composer",children:o.jsx(vr,{size:18})})]}),o.jsxs("div",{className:"support-form-grid",children:[o.jsxs("label",{children:[o.jsx("span",{children:"Product"}),o.jsx("select",{value:it.productId,onChange:G=>ye(ot=>({...ot,productId:G.target.value})),children:ae.map(G=>o.jsx("option",{value:G.id,children:G.name},G.id))})]}),o.jsxs("label",{children:[o.jsx("span",{children:"Type"}),o.jsx("select",{value:it.postType,onChange:G=>ye(ot=>({...ot,postType:G.target.value})),children:mv.filter(G=>G.id!=="announcement"||f?.canCreateAnnouncements).map(G=>o.jsx("option",{value:G.id,children:G.label},G.id))})]}),o.jsxs("label",{className:"support-form-wide",children:[o.jsx("span",{children:"Title"}),o.jsx("input",{required:!0,minLength:3,maxLength:180,value:it.title,onChange:G=>ye(ot=>({...ot,title:G.target.value})),placeholder:"A short, searchable summary"})]}),o.jsxs("label",{className:"support-form-wide",children:[o.jsx("span",{children:it.postType==="issue"?"What happened?":it.postType==="feature"?"Describe the desired behavior":it.postType==="announcement"?"Announcement":"Question"}),o.jsx("textarea",{required:!0,value:it.body,onChange:G=>ye(ot=>({...ot,body:G.target.value})),placeholder:"Include the context another person needs to respond.",rows:6})]}),o.jsxs("label",{children:[o.jsx("span",{children:"Visibility"}),o.jsxs("select",{value:it.visibility,disabled:it.postType==="announcement",onChange:G=>ye(ot=>({...ot,visibility:G.target.value})),children:[o.jsx("option",{value:"public",children:"Public"}),o.jsx("option",{value:"private",children:"Private"})]})]}),it.postType==="issue"&&o.jsxs("label",{className:"support-checkbox",children:[o.jsx("input",{type:"checkbox",checked:it.includeEnvironment,onChange:G=>ye(ot=>({...ot,includeEnvironment:G.target.checked}))}),o.jsx("span",{children:"Attach safe browser/runtime details"})]}),o.jsxs("label",{className:"support-form-wide",children:[o.jsx("span",{children:"Attachments"}),o.jsx("input",{type:"file",multiple:!0,accept:"image/png,image/jpeg,image/webp,text/plain,text/markdown,application/json,application/pdf",onChange:G=>et(Array.from(G.target.files||[]).slice(0,5))}),o.jsx("small",{className:"support-muted",children:"Up to 5 files, 10 MB each. Images, text, JSON, Markdown, and PDF."})]})]}),o.jsxs("div",{className:"support-composer-footer",children:[o.jsx("span",{children:We.length>0?`${We.length} attachment${We.length===1?"":"s"} selected.`:"Private posts are visible only to you and the product support staff."}),o.jsxs("button",{className:"support-primary-button",type:"submit",disabled:K==="create",children:[o.jsx(fm,{size:16})," ",K==="create"?"Submitting...":"Submit request"]})]})]}),o.jsxs("div",{className:"support-tabs",role:"tablist","aria-label":"Support post type",children:[o.jsx("button",{className:l.type==="all"?"active":"",type:"button",onClick:()=>Ne({type:"all"}),children:"All"}),mv.map(G=>{const ot=Vb(G.id);return o.jsxs("button",{className:l.type===G.id?"active":"",type:"button",onClick:()=>Ne({type:G.id}),children:[o.jsx(ot,{size:15})," ",G.label]},G.id)})]}),ce&&f?.canViewAllProducts&&o.jsxs("section",{className:"support-admin-panel",children:[o.jsxs("div",{className:"support-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Owner controls"}),o.jsx("strong",{children:"Products and access are managed by immutable user IDs behind these email lookup forms."})]}),o.jsx(Ea,{size:19})]}),o.jsxs("div",{className:"support-admin-grid",children:[o.jsxs("form",{onSubmit:G=>{},children:[o.jsx("strong",{children:"Grant product access"}),o.jsx("input",{type:"email",required:!0,placeholder:"User email",value:Fe,onChange:G=>$e(G.target.value)}),o.jsx("select",{value:Ze,onChange:G=>de(G.target.value),children:ae.map(G=>o.jsx("option",{value:G.id,children:G.name},G.id))}),o.jsxs("select",{value:Be,onChange:G=>Ve(G.target.value),children:[o.jsx("option",{value:"free",children:"Free"}),o.jsx("option",{value:"user",children:"User"}),o.jsx("option",{value:"paid",children:"Paid"}),o.jsx("option",{value:"beta",children:"Beta"}),o.jsx("option",{value:"staff",children:"Staff"})]}),o.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:B==="access",children:[o.jsx(tl,{size:15})," Grant access"]})]}),o.jsxs("form",{onSubmit:G=>{},children:[o.jsx("strong",{children:"Assign product admin"}),o.jsx("input",{type:"email",required:!0,placeholder:"Admin email",value:Je,onChange:G=>Qe(G.target.value)}),o.jsx("select",{value:yt,onChange:G=>ne(G.target.value),children:ae.map(G=>o.jsx("option",{value:G.id,children:G.name},G.id))}),o.jsxs("select",{value:me,onChange:G=>Ge(G.target.value),children:[o.jsx("option",{value:"admin",children:"Admin"}),o.jsx("option",{value:"support",children:"Support"}),o.jsx("option",{value:"moderator",children:"Moderator"})]}),o.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:B==="product-admin",children:[o.jsx(Ea,{size:15})," Assign admin"]})]}),o.jsxs("form",{onSubmit:G=>{},children:[o.jsx("strong",{children:"Add a product"}),o.jsx("input",{required:!0,pattern:"[a-z0-9][a-z0-9_-]{1,48}",placeholder:"product-key",value:Se,onChange:G=>ge(G.target.value)}),o.jsx("input",{required:!0,placeholder:"Product name",value:Ue,onChange:G=>Me(G.target.value)}),o.jsx("input",{placeholder:"Description",value:rt,onChange:G=>At(G.target.value)}),o.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:B==="product",children:[o.jsx(Vp,{size:15})," Add product"]})]})]})]}),o.jsxs("form",{className:"support-search-bar",onSubmit:G=>{G.preventDefault(),Ne({query:le.trim()})},children:[o.jsxs("label",{children:[o.jsx("span",{children:"Search Support"}),o.jsx("input",{value:le,onChange:G=>ve(G.target.value),placeholder:"Search titles and request details"})]}),o.jsxs("button",{className:"support-secondary-button",type:"submit",children:[o.jsx(jb,{size:15})," Search"]}),l.query&&o.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{ve(""),Ne({query:""})},"aria-label":"Clear search",children:o.jsx(vr,{size:16})})]}),o.jsxs("div",{className:"support-filter-bar",children:[o.jsxs("div",{className:"support-filter-title",children:[o.jsx(jb,{size:16}),o.jsx("span",{children:"Filter"})]}),o.jsxs("label",{children:[o.jsx("span",{children:"Product"}),o.jsxs("select",{value:fe,onChange:G=>Ne({product:G.target.value}),disabled:!f?.canViewAllProducts&&ae.length<=1,children:[o.jsx("option",{value:"all",children:"All products"}),ae.map(G=>o.jsx("option",{value:G.product_key,children:G.name},G.id))]})]}),o.jsxs("label",{children:[o.jsx("span",{children:"Status"}),o.jsx("select",{value:l.status,onChange:G=>Ne({status:G.target.value}),children:QM.map(G=>o.jsx("option",{value:G.id,children:G.label},G.id))})]}),o.jsxs("label",{children:[o.jsx("span",{children:"Visibility"}),o.jsxs("select",{value:l.visibility,onChange:G=>Ne({visibility:G.target.value}),children:[o.jsx("option",{value:"all",children:"All visibility"}),o.jsx("option",{value:"public",children:"Public"}),o.jsx("option",{value:"private",children:"Private"})]})]}),o.jsxs("label",{children:[o.jsx("span",{children:"Sort"}),o.jsxs("select",{value:l.sort,onChange:G=>Ne({sort:G.target.value}),children:[o.jsx("option",{value:"recent",children:"Recently updated"}),o.jsx("option",{value:"newest",children:"Newest"}),o.jsx("option",{value:"votes",children:"Most votes"})]})]})]}),f?.canViewAllProducts&&o.jsxs("div",{className:"support-admin-shortcuts",children:[o.jsxs("span",{children:[o.jsx(Ea,{size:15})," Owner view"]}),o.jsx("button",{type:"button",onClick:()=>Ne({status:"needs-response"}),children:"Needs response"}),o.jsx("button",{type:"button",onClick:()=>Ne({visibility:"private"}),children:"Private requests"}),o.jsx("button",{type:"button",onClick:()=>Ne({type:"feature",status:"all",sort:"votes"}),children:"High-vote features"})]}),o.jsxs("div",{className:"support-board-layout",children:[o.jsxs("section",{className:"support-post-list","aria-label":"Support posts",children:[o.jsxs("div",{className:"support-list-heading",children:[o.jsxs("span",{children:[je.length," request",je.length===1?"":"s"]}),o.jsx("small",{children:fe==="all"?"All products":Rg(ae,Ee)})]}),je.length===0?o.jsxs("div",{className:"support-list-empty",children:[o.jsx(am,{size:25}),o.jsx("strong",{children:"No posts match these filters."}),o.jsx("span",{children:"Start with a focused question, issue report, or feature request."}),ae.length>0&&o.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>V(!0),children:[o.jsx(Vp,{size:16})," Create the first request"]})]}):je.map(G=>{const ot=Vb(G.post_type);return o.jsxs("button",{type:"button",className:`support-post-row ${G.id===De?.id?"active":""}`,onClick:()=>{k(G.id),ee(!1)},children:[o.jsx("span",{className:"support-post-row-icon",children:o.jsx(ot,{size:17})}),o.jsxs("span",{className:"support-post-row-copy",children:[o.jsxs("span",{className:"support-post-row-meta",children:[o.jsx("b",{children:Rg(g,G.product_id)}),o.jsx("em",{children:Kb(G.post_type)}),G.visibility==="private"&&o.jsx(el,{size:13})]}),o.jsx("strong",{children:G.title}),o.jsxs("small",{children:[Ng(G.status)," · ",Cp(G.updated_at)," · ",G.comment_count," comments"]})]}),G.post_type==="feature"&&o.jsxs("span",{className:"support-vote-count",children:[o.jsx(d0,{size:14})," ",G.vote_count]})]},G.id)})]}),o.jsx("section",{className:"support-post-detail","aria-label":"Support post detail",children:De?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"support-detail-head",children:[o.jsxs("div",{className:"support-detail-badges",children:[o.jsx("span",{className:"support-product-badge",children:Rg(g,De.product_id)}),o.jsx("span",{className:"support-type-badge",children:Kb(De.post_type)}),o.jsx("span",{className:`support-status-badge status-${De.status}`,children:Ng(De.status)}),De.visibility==="private"&&o.jsxs("span",{className:"support-private-badge",children:[o.jsx(el,{size:13})," Private"]})]}),o.jsxs("div",{className:"support-detail-actions",children:[at&&o.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>ee(G=>!G),title:"Edit post",children:o.jsx(_k,{size:16})}),Et&&o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{ha()},disabled:K==="pin",title:De.is_pinned?"Unpin post":"Pin post",children:o.jsx(Db,{size:16})}),o.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{mt()},disabled:K==="lock",title:De.is_locked?"Unlock post":"Lock post",children:o.jsx(el,{size:16})}),o.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{yn()},disabled:K==="hide",title:"Hide post",children:o.jsx(Ib,{size:16})})]})]})]}),he?o.jsxs("form",{className:"support-edit-form",onSubmit:G=>{Ut(G)},children:[o.jsx("input",{value:De.title,onChange:G=>ft({title:G.target.value}),minLength:3,maxLength:180,required:!0}),o.jsx("textarea",{value:De.body,onChange:G=>ft({body:G.target.value}),rows:9,required:!0}),o.jsxs("div",{className:"support-edit-actions",children:[o.jsxs("select",{value:De.visibility,onChange:G=>ft({visibility:G.target.value}),children:[o.jsx("option",{value:"public",children:"Public"}),o.jsx("option",{value:"private",children:"Private"})]}),o.jsxs("button",{className:"support-primary-button",type:"submit",disabled:K==="edit",children:[o.jsx(tl,{size:16})," Save changes"]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("h3",{children:De.title}),o.jsx("div",{className:"support-detail-body",children:De.body.split(`
10
- `).map((G,ot)=>o.jsx("p",{children:G||" "},`${De.id}-body-${ot}`))})]}),o.jsxs("div",{className:"support-detail-meta",children:[o.jsxs("span",{children:["Opened ",Cp(De.created_at)]}),De.app_version&&o.jsxs("span",{children:["Version ",De.app_version]}),De.platform&&o.jsx("span",{children:De.platform}),De.is_locked&&o.jsxs("span",{children:[o.jsx(el,{size:13})," Locked"]}),De.is_pinned&&o.jsxs("span",{children:[o.jsx(Db,{size:13})," Pinned"]})]}),o.jsxs("div",{className:"support-detail-controls",children:[De.post_type==="feature"&&o.jsxs("button",{className:`support-vote-button ${H.has(De.id)?"voted":""}`,type:"button",onClick:()=>{Wt()},disabled:K==="vote",children:[o.jsx(Ok,{size:16})," ",H.has(De.id)?"Voted":"Vote"," ",o.jsx("b",{children:De.vote_count})]}),Et&&o.jsxs("label",{className:"support-status-control",children:[o.jsx("span",{children:"Change status"}),o.jsx("select",{value:De.status,onChange:G=>{gt(G.target.value)},disabled:K==="status",children:(YM[De.post_type]||[]).map(G=>o.jsx("option",{value:G,children:Ng(G)},G))})]}),Et&&o.jsxs(o.Fragment,{children:[o.jsxs("select",{className:"support-status-control",value:O,onChange:G=>qe(G.target.value),children:[o.jsx("option",{value:"",children:"Duplicate of..."}),je.filter(G=>G.id!==De.id&&G.product_id===De.product_id).map(G=>o.jsx("option",{value:G.id,children:G.title.slice(0,55)},G.id))]}),o.jsx("button",{className:"support-secondary-button",type:"button",onClick:()=>{na()},disabled:!O||K==="duplicate",children:"Merge duplicate"})]})]}),j.length>0&&o.jsxs("div",{className:"support-attachments",children:[o.jsx("div",{className:"support-section-heading",children:o.jsxs("div",{children:[o.jsx("span",{children:"Attachments"}),o.jsxs("strong",{children:[j.length," file",j.length===1?"":"s"]})]})}),j.map(G=>o.jsxs("a",{href:G.signed_url,target:"_blank",rel:"noreferrer",children:[o.jsx(mm,{size:14})," ",G.file_name,o.jsxs("small",{children:[Math.ceil(G.size_bytes/1024)," KB"]})]},G.id))]}),o.jsxs("div",{className:"support-comments",children:[o.jsxs("div",{className:"support-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Discussion"}),o.jsxs("strong",{children:[A.length," comment",A.length===1?"":"s"]})]}),De.is_locked&&o.jsxs("span",{className:"support-locked-label",children:[o.jsx(el,{size:14})," Locked"]})]}),A.length===0?o.jsx("p",{className:"support-muted",children:"No response yet. Keep the conversation focused on this request."}):o.jsx("div",{className:"support-comment-list",children:A.map(G=>o.jsxs("article",{className:`support-comment ${G.is_staff_answer?"staff":""} ${De.accepted_comment_id===G.id?"accepted":""}`,children:[o.jsxs("div",{className:"support-comment-head",children:[o.jsx("strong",{children:G.is_staff_answer?"LiveDesk Support":G.author_id===t.user.id?"You":"Support user"}),G.is_staff_answer&&o.jsxs("span",{children:[o.jsx(Ea,{size:13})," Staff answer"]}),De.accepted_comment_id===G.id&&o.jsxs("span",{children:[o.jsx(tr,{size:13})," Accepted"]}),o.jsx("time",{children:Cp(G.created_at)})]}),o.jsx("p",{children:G.body}),o.jsxs("div",{className:"support-comment-actions",children:[(t.user.id===De.author_id||Et)&&De.post_type==="question"&&De.accepted_comment_id!==G.id&&o.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{hn(G.id)},disabled:K===`accept-${G.id}`,children:[o.jsx(tl,{size:14})," Accept answer"]}),Et&&o.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{KM(G.id)},title:"Hide comment",children:o.jsx(Ib,{size:14})})]})]},G.id))}),!De.is_locked&&o.jsxs("form",{className:"support-comment-form",onSubmit:G=>{wt(G)},children:[o.jsx("textarea",{value:U,onChange:G=>L(G.target.value),placeholder:"Add a focused reply...",rows:3}),o.jsxs("button",{className:"support-primary-button",type:"submit",disabled:K==="comment"||!U.trim(),children:[o.jsx(fm,{size:15})," Reply"]})]})]})]}):o.jsxs("div",{className:"support-detail-empty",children:[o.jsx(am,{size:28}),o.jsx("strong",{children:"Select a Support request"}),o.jsx("span",{children:"Its discussion and staff actions will appear here."})]})})]})]}):o.jsx("section",{className:"support-page support-auth-page",children:o.jsxs("div",{className:"support-empty-hero",children:[o.jsx("span",{className:"support-hero-icon",children:o.jsx(am,{size:28})}),o.jsx("p",{className:"support-eyebrow",children:"LiveDesk Support"}),o.jsx("h2",{children:"Get help, report issues, and shape the product."}),o.jsx("p",{children:"Sign in to see the products attached to your account and submit a private or public request."}),o.jsxs("button",{className:"support-primary-button",type:"button",onClick:s,children:[o.jsx(Ea,{size:17})," Sign in with Google"]})]})})}function eA(t){if(!t)return"Reading the installed version...";switch(t.state){case"checking":return"Checking for a newer LiveDesk version...";case"available":return`Version ${t.availableVersion||""} is available.`;case"downloading":return`Downloading version ${t.availableVersion||""} (${Math.round(t.progress||0)}%).`;case"downloaded":return`Version ${t.availableVersion||""} is ready. Restart to install it.`;case"installing":return"Closing LiveDesk safely and starting the update...";case"current":return"This computer has the latest LiveDesk version.";case"error":return"The update server could not be reached. This version will keep running.";case"development":return"Desktop updates are available in an installed LiveDesk build.";case"unavailable":return"Updates are not available for this desktop build.";default:return"LiveDesk checks once when the desktop app starts."}}function N0(){const t=window.liveDesk?.updates,[n,r]=d.useState(null),[s,l]=d.useState(!1);if(d.useEffect(()=>{if(!t)return;let g=!0;t.getStatus?.().then(w=>{g&&r(w)});const y=t.onStatus?.(w=>{g&&r(w)});return()=>{g=!1,y?.()}},[t]),!t)return null;const u=n?.state==="downloaded"||n?.downloaded===!0,f=s||n?.state==="checking"||n?.state==="downloading"||n?.state==="installing",h=async()=>{l(!0);try{const g=u?await t.install?.():await t.check?.();g&&r(g)}finally{l(!1)}};return o.jsxs("section",{className:"settings-section-card desktop-update-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Desktop app"}),o.jsx("h3",{children:"LiveDesk updates"})]}),o.jsx(mm,{size:20})]}),o.jsx("p",{className:"settings-help","aria-live":"polite",children:eA(n)}),o.jsxs("div",{className:"desktop-update-meta",children:[o.jsx("span",{children:"Installed"}),o.jsx("strong",{children:n?.currentVersion||"Unknown"}),n?.availableVersion&&o.jsxs(o.Fragment,{children:[o.jsx("span",{children:"Available"}),o.jsx("strong",{children:n.availableVersion})]})]}),o.jsxs("button",{className:"settings-reset desktop-update-action",onClick:()=>{h()},disabled:f,type:"button",children:[o.jsx(vu,{size:15,className:f?"desktop-update-spin":""}),u?"Restart and update":f?"Updating...":"Check for updates"]})]})}function kp(t){return!!t&&typeof t=="object"}function R0(t){let n=t;return kp(n)&&"data"in n&&(n=n.data),kp(n)&&"session"in n&&(n=n.session),!kp(n)||typeof n.access_token!="string"||!n.access_token||!kp(n.user)||typeof n.user.id!="string"||!n.user.id?null:n}function Qb(t){return t?.access_token?t.refresh_token?"":"refresh-token-required":"access-token-required"}const sh=15e3;function tA(t,n=sh){const r=Number(t),s=Number.isFinite(Number(n))?Number(n):sh;return Math.max(250,Math.min(12e4,Math.trunc(Number.isFinite(r)?r:s)))}class Yb extends Error{constructor(n){super(`LiveDesk Hub request timed out after ${n} ms.`),this.name="HubRequestTimeoutError",this.code="livedesk-hub-request-timeout",this.timeoutMs=n}}async function nA(t,n,r){const s=tA(n),l=new AbortController;let u=!1;const f=()=>{l.signal.aborted||l.abort(t?.reason)};t?.aborted?f():t?.addEventListener("abort",f,{once:!0});const h=setTimeout(()=>{u=!0,l.signal.aborted||l.abort(new Yb(s))},s);try{return await r(l.signal)}catch(g){throw u?new Yb(s):g}finally{clearTimeout(h),t?.removeEventListener("abort",f)}}function yu(t,n){if(t.current)return t.current;const r=Promise.resolve().then(n);return t.current=r,r.finally(()=>{t.current===r&&(t.current=null)}).catch(()=>{}),r}function aA(){let t=!1,n=null,r=()=>{},s=()=>{};const l=new Promise((f,h)=>{r=f,s=h}),u=()=>{n!==null&&(clearTimeout(n),n=null)};return{promise:l,get settled(){return t},bindTimeout(f){if(t){clearTimeout(f);return}u(),n=f},resolve(){return t?!1:(t=!0,u(),r(),!0)},reject(f){return t?!1:(t=!0,u(),s(f instanceof Error?f:new Error(String(f||"console-relay-disconnected"))),!0)}}}const rA="https://livedesk-wake.lovecrdm.workers.dev",E0="livedesk-console-v1",sA="livedesk-auth.",iA=1e4,Eg=73;function oA(){const t=String(rA).trim(),n=new URL(t);return n.protocol=n.protocol==="http:"?"ws:":n.protocol==="https:"?"wss:":n.protocol,n.pathname="/v1/console",n.search="",n.hash="",n.toString()}function lA(t){let n="";for(let s=0;s<t.byteLength;s+=32768)n+=String.fromCharCode(...t.subarray(s,Math.min(t.byteLength,s+32768)));return btoa(n)}function cA(t){const n=atob(t),r=new Uint8Array(n.length);for(let s=0;s<n.length;s+=1)r[s]=n.charCodeAt(s);return r}async function uA(t){if(t==null)return new Uint8Array;if(typeof t=="string")return new TextEncoder().encode(t);if(t instanceof URLSearchParams)return new TextEncoder().encode(t.toString());if(t instanceof Blob)return new Uint8Array(await t.arrayBuffer());if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("This request body cannot be sent through the mobile Console relay.")}function dA(t){const n=new Headers(t?.headers||{}),r={};for(const s of["accept","content-type","if-match","range"]){const l=n.get(s);l&&(r[s]=l)}return r}class fA{session=null;socket=null;connectPromise=null;connectOwner=null;connectGeneration=0;ready=!1;pendingHttp=new Map;channels=new Map;relayPreferred=!1;configure(n){const r=this.session?`${this.session.user.id}
11
- ${this.session.accessToken}`:"",s=n?`${n.user.id}
12
- ${n.accessToken}`:"";this.session=n,r!==s&&this.disconnect("console-session-replaced")}preferRelay(){this.relayPreferred=!0}markDirectReachable(){this.relayPreferred=!1}resume(){this.session&&this.disconnect("console-resume")}shouldUseRelay(){return this.relayPreferred&&!!this.session?.accessToken}disconnect(n){const r=this.connectOwner;this.connectOwner=null,this.connectGeneration+=1,this.ready=!1,this.connectPromise=null;const s=this.socket;this.socket=null,r?.reject(new Error(n));try{s?.close(1e3,n)}catch{}this.failPending(new Error(n)),this.closeChannels(1006,n)}failPending(n){for(const[r,s]of this.pendingHttp)window.clearTimeout(s.timeout),s.detachAbort(),s.reject(n),this.pendingHttp.delete(r)}closeChannels(n,r){for(const s of[...this.channels.values()])s.relayClosed(n,r);this.channels.clear()}handleTextMessage(n){let r;try{r=JSON.parse(n)}catch{return}if(r.type==="relay-ready"&&r.role==="console"){this.ready=!0;return}if(r.type==="hub-offline"){this.closeChannels(1012,"hub-offline");return}const s=String(r.channelId||"");if(!s)return;const l=this.pendingHttp.get(s);if(r.type==="http-response"&&l){this.pendingHttp.delete(s),window.clearTimeout(l.timeout),l.detachAbort();const u=Number(r.status||502),f=r.bodyBase64?cA(r.bodyBase64):new TextEncoder().encode(JSON.stringify({ok:!1,error:r.error||"console-relay-failed"}));l.resolve(new Response(f,{status:u,statusText:String(r.statusText||""),headers:r.headers||{"content-type":"application/json"}}));return}if(r.type==="relay-error"&&l){this.pendingHttp.delete(s),window.clearTimeout(l.timeout),l.detachAbort(),l.reject(new Error(r.error||"console-relay-failed"));return}this.channels.get(s)?.relayMessage(r)}handleBinaryMessage(n){if(n.byteLength<Eg)return;const r=new TextDecoder().decode(new Uint8Array(n,0,Eg));if(r[0]!=="B")return;const s=r.slice(37,73);this.channels.get(s)?.relayBinary(n.slice(Eg))}async connect(){if(this.socket?.readyState===WebSocket.OPEN&&this.ready)return;if(this.connectPromise)return this.connectPromise;const n=String(this.session?.accessToken||"");if(!n)throw new Error("Sign in before using the mobile Console relay.");const r=++this.connectGeneration,s=aA();this.connectOwner=s,this.connectPromise=s.promise.finally(()=>{this.connectOwner===s&&(this.connectOwner=null),r===this.connectGeneration&&(this.connectPromise=null)});try{const l=new WebSocket(oA(),[E0,`${sA}${n}`]);l.binaryType="arraybuffer",this.socket=l;const u=window.setTimeout(()=>{if(!s.settled){try{l.close(1e3,"console-relay-connect-timeout")}catch{}s.reject(new Error("Mobile Console relay connection timed out."))}},iA);s.bindTimeout(u),l.addEventListener("message",f=>{if(!(r!==this.connectGeneration||this.socket!==l))if(typeof f.data=="string"){this.handleTextMessage(f.data);let h=null;try{h=JSON.parse(f.data)}catch{h=null}!s.settled&&h?.type==="relay-ready"&&h.role==="console"&&s.resolve()}else f.data instanceof ArrayBuffer&&this.handleBinaryMessage(f.data)}),l.addEventListener("error",()=>{s.reject(new Error("Mobile Console relay connection failed."))}),l.addEventListener("close",f=>{r!==this.connectGeneration||this.socket!==l||(this.socket=null,this.ready=!1,this.connectPromise=null,this.failPending(new Error(`Mobile Console relay closed (${f.code}).`)),this.closeChannels(f.code||1006,f.reason||"console-relay-closed"),s.reject(new Error(`Mobile Console relay closed (${f.code}).`)))})}catch(l){s.reject(l)}return this.connectPromise}send(n){if(!this.socket||this.socket.readyState!==WebSocket.OPEN||!this.ready)throw new Error("Mobile Console relay is not connected.");this.socket.send(JSON.stringify(n))}async fetch(n,r,s){await this.connect();const l=crypto.randomUUID(),u=await uA(r?.body),f=new Promise((h,g)=>{const y=()=>{const b=this.pendingHttp.get(l);b&&(this.pendingHttp.delete(l),window.clearTimeout(b.timeout),g(r?.signal?.reason instanceof Error?r.signal.reason:new Error("Mobile Console request cancelled.")))};r?.signal?.addEventListener("abort",y,{once:!0});const w=window.setTimeout(()=>{const b=this.pendingHttp.get(l);b&&(this.pendingHttp.delete(l),b.detachAbort(),g(new Error("Mobile Console request timed out.")))},s);this.pendingHttp.set(l,{resolve:h,reject:g,timeout:w,detachAbort:()=>r?.signal?.removeEventListener("abort",y)})});try{this.send({type:"http-request",channelId:l,method:String(r?.method||"GET").toUpperCase(),path:n,headers:dA(r),bodyBase64:u.byteLength>0?lA(u):""})}catch(h){const g=this.pendingHttp.get(l);g&&(this.pendingHttp.delete(l),window.clearTimeout(g.timeout),g.detachAbort(),g.reject(h instanceof Error?h:new Error(String(h))))}return f}openWebSocket(n){const r=new mA(this,n);return this.channels.set(r.channelId,r),this.connect().then(()=>{this.channels.get(r.channelId)===r&&this.send({type:"ws-open",channelId:r.channelId,path:n})}).catch(s=>r.relayError(s instanceof Error?s.message:String(s))),r}removeChannel(n){this.channels.delete(n)}bufferedAmount(){return Number(this.socket?.bufferedAmount||0)}}class mA extends EventTarget{constructor(n,r){super(),this.relay=n,this.url=r}relay;channelId=crypto.randomUUID();url;protocol=E0;extensions="";binaryType="blob";readyState=WebSocket.CONNECTING;onopen=null;onmessage=null;onerror=null;onclose=null;get bufferedAmount(){return this.relay.bufferedAmount()}emit(n,r){(n==="open"?this.onopen:this.onerror)?.call(this,r),this.dispatchEvent(r)}emitMessage(n){const r=new MessageEvent("message",{data:n});this.onmessage?.call(this,r),this.dispatchEvent(r)}emitClose(n,r){if(this.readyState===WebSocket.CLOSED)return;this.readyState=WebSocket.CLOSED,this.relay.removeChannel(this.channelId);const s=new CloseEvent("close",{code:n,reason:r,wasClean:n===1e3});this.onclose?.call(this,s),this.dispatchEvent(s)}send(n){if(this.readyState!==WebSocket.OPEN)throw new DOMException("WebSocket is not open.","InvalidStateError");if(typeof n!="string")throw new DOMException("Mobile Console input messages must be text.","NotSupportedError");this.relay.send({type:"ws-send",channelId:this.channelId,data:n})}close(n=1e3,r=""){if(this.readyState===WebSocket.CLOSED||this.readyState===WebSocket.CLOSING)return;const s=this.readyState===WebSocket.OPEN;if(this.readyState=WebSocket.CLOSING,s)try{this.relay.send({type:"ws-close",channelId:this.channelId,code:n,reason:r})}catch{}this.emitClose(n,r)}relayMessage(n){if(n.type==="ws-opened"){if(this.readyState!==WebSocket.CONNECTING)return;this.readyState=WebSocket.OPEN,this.emit("open",new Event("open"))}else n.type==="ws-message"?this.emitMessage(String(n.data||"")):n.type==="ws-error"||n.type==="relay-error"?this.relayError(n.error||"console-websocket-error"):n.type==="ws-closed"&&this.emitClose(Number(n.code||1e3),String(n.reason||""))}relayBinary(n){this.emitMessage(this.binaryType==="arraybuffer"?n:new Blob([n]))}relayError(n){this.readyState!==WebSocket.CLOSED&&(this.emit("error",new Event("error")),this.emitClose(1011,"console-websocket-error"))}relayClosed(n,r){this.emitClose(n,r)}}const bu=new fA;function pA(t){bu.configure(t)}function hA(){bu.markDirectReachable()}function gA(){bu.resume()}function Xb(t,n,r){return bu.preferRelay(),bu.fetch(t,n,r)}function xh(t,n){return bu.shouldUseRelay()?bu.openWebSocket(n):new WebSocket(t)}const im=5179,Vn=Su(`http://127.0.0.1:${im}`);function vA(t){const n=t.split(".").map(r=>Number(r));return n.length===4&&n.every(r=>Number.isInteger(r)&&r>=0&&r<=255)?n:[]}function j0(t){const n=t.trim().toLowerCase();return n==="localhost"||n==="127.0.0.1"||n==="::1"||n==="[::1]"}function yA(t){const n=t.trim().toLowerCase();return!n||n==="0.0.0.0"||n==="::"||n==="[::]"}function D0(t){const n=vA(t);return n.length===0?!1:n[0]===10||n[0]===172&&n[1]>=16&&n[1]<=31||n[0]===192&&n[1]===168}function bA(t){return t.includes(":")&&!t.startsWith("[")?`[${t}]`:t}function wA(t){const n=String(t||"").trim();if(!n)return null;const r=/^[a-z][a-z\d+.-]*:\/\//i.test(n)?n:`tcp://${n}`;try{const s=new URL(r),l=s.hostname.replace(/^\[|\]$/g,""),u=Number(s.port);return!l||!Number.isInteger(u)||u<1||u>65535||yA(l)?null:{host:l,port:u}}catch{return null}}function Su(t){const n=String(t||"").trim()||`http://127.0.0.1:${im}`,r=/^[a-z][a-z\d+.-]*:\/\//i.test(n)?n:`http://${n}`;try{const s=new URL(r);return s.port||(s.port=String(im)),s.hash="",s.search="",s.toString().replace(/\/+$/,"")}catch{return`http://127.0.0.1:${im}`}}function xA(t){const n=wA(t);return n?Su(`http://${bA(n.host)}:${im}`):""}function Zb(t){const r=[t?.endpoint,...Array.isArray(t?.endpoint_candidates)?t.endpoint_candidates:[]].map(s=>xA(String(s||""))).filter(Boolean);return[...new Set(r)]}function om(t=Vn){if(!(typeof window>"u"||window.location.protocol!=="https:"))try{const n=new URL(t);if(n.protocol!=="http:")return;if(j0(n.hostname))return"loopback";if(D0(n.hostname))return"local"}catch{return}}function Sh(t,n=Vn){const r=new URL(t,Su(n));return r.protocol=r.protocol==="https:"?"wss:":"ws:",r.toString()}let lm=null,Jb="";const Pd=new Map,Qp=new Map;function SA(t){const n=t?.accessToken&&t?.refreshToken&&t?.user?.id?t:null,r=n?`${n.user.id}
13
- ${n.accessToken}
14
- ${n.expiresAt||0}`:"";r!==Jb&&(Pd.clear(),Qp.clear(),Jb=r),lm=n,pA(n?{accessToken:n.accessToken,user:{id:n.user.id}}:null)}function ih(){if(typeof window>"u"||window.location.protocol!=="https:")return!1;const t=window.location.hostname.replace(/^\[|\]$/g,"");return!j0(t)&&!D0(t)}function jg(t){const n=t.split("?")[0];return n==="/api/health"||n==="/api/runtime/status"||n==="/api/auth/status"||n==="/api/auth/session"}async function pv(t,n,r,s,l){const u=om(r);return u&&(n.targetAddressSpace=u),nA(l,s,async f=>{n.signal=f;try{return await fetch(`${r}${t}`,n)}catch(h){throw!f.aborted&&u?new Error("LiveDesk Hub is not reachable at this local network address. If Chrome shows a local network prompt, allow it; otherwise restart the Hub so port 5179 is open on the network."):h}})}async function ew(t,n=!1){const r=Pd.get(t);if(!n&&r&&r.expiresAt>Date.now()+3e4)return;n&&Pd.delete(t);const s=Qp.get(t);if(s)return s;const l=lm;if(!l)return;const u=(async()=>{const f=await pv("/api/auth/session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({accessToken:l.accessToken,refreshToken:l.refreshToken,expiresAt:l.expiresAt,user:l.user}),credentials:"include",cache:"no-store"},t,sh),h=await f.json().catch(()=>null);if(!f.ok)throw new Error(`${f.status} ${h?.error||f.statusText}`);const g=String(h?.uiSession?.csrfToken||"").trim(),y=Number(h?.uiSession?.expiresAt||0);if(!g||!Number.isFinite(y)||y<=Date.now())throw new Error("LiveDesk Hub did not issue a valid UI session.");Pd.set(t,{csrfToken:g,expiresAt:y})})().finally(()=>{Qp.delete(t)});return Qp.set(t,u),u}async function Wv(t,n,r=Vn){const s=Su(r),{timeoutMs:l=sh,signal:u,transport:f="auto",...h}=n||{},g=!jg(t),y=()=>{const w=String(h.method||"GET").toUpperCase(),b=Pd.get(s)?.csrfToken||"";return{...h,headers:{...h.headers||{},...!["GET","HEAD","OPTIONS"].includes(w)&&b?{"X-LiveDesk-CSRF":b}:{}},credentials:"include",cache:"no-store"}};if(f==="relay"){if(u?.aborted)throw u.reason||new Error("LiveDesk Hub request cancelled.");if(!lm||jg(t))throw new Error("Mobile Console relay requires an authenticated management request.");return Xb(t,y(),l)}try{g&&await ew(s);let w=await pv(t,y(),s,l,u);if(hA(),g&&w.status===401&&lm){const b=await w.clone().json().catch(()=>null);/^hub-ui-session-(required|expired)$/.test(String(b?.error||""))&&(await ew(s,!0),w=await pv(t,y(),s,l,u))}return w}catch(w){if(u?.aborted||!lm||jg(t))throw w;return Xb(t,y(),l)}}async function lt(t,n,r=Vn){const s=Su(r),l=await Wv(t,{...n||{},headers:{"Content-Type":"application/json",...n?.headers||{}}},r);let u=null;try{u=await l.json()}catch(f){if(n?.signal?.aborted)throw f;u=null}if(l.ok&&t.split("?")[0]==="/api/auth/session"&&u&&typeof u=="object"){const f=u.uiSession,h=String(f?.csrfToken||"").trim(),g=Number(f?.expiresAt||0);h&&Number.isFinite(g)&&g>Date.now()&&Pd.set(s,{csrfToken:h,expiresAt:g})}if(!l.ok){const f=u&&typeof u=="object"&&"error"in u?String(u.error||""):"";throw new Error(`${l.status} ${f||l.statusText}`)}return u}async function I0({baseUrl:t=Vn,targetRole:n,previousRuntimePid:r=0,allowedStates:s=["running","waiting-auth"],timeoutMs:l=3e4}){const u=Date.now()+l;let f=null;for(;Date.now()<u;){try{const g=await lt("/api/runtime/status",void 0,t),y=String(g.role||"").toLowerCase(),w=String(g.state||"").toLowerCase(),b=Number(g.runtimePid||0),S=r>1?b>1&&b!==r:b>1;if(y===n&&s.map(k=>k.toLowerCase()).includes(w)&&S)return g}catch(g){f=g}await new Promise(g=>setTimeout(g,300))}const h=f instanceof Error?` ${f.message}`:"";throw new Error(`LiveDesk runtime did not become ${n} with a new process.${h}`)}function CA(t,n=120){if(typeof window>"u")return;const r=new URL(window.location.href);r.port=String(t),r.pathname="/",r.search="",r.hash="";const s=r.toString();let l=0;const u=()=>{fetch(s,{cache:"no-store",mode:"no-cors"}).then(()=>window.location.replace(s)).catch(()=>{if(l+=1,l>=n){window.location.replace(s);return}window.setTimeout(u,250)})};u()}function L0(t){if(!t)return"-";const n=Date.now()-Date.parse(t);return Number.isFinite(n)?n<1e3?"now":n<6e4?`${Math.round(n/1e3)}s`:n<36e5?`${Math.round(n/6e4)}m`:`${Math.round(n/36e5)}h`:"-"}async function Yp(t){await navigator.clipboard.writeText(t)}function P0({size:t=22}){return o.jsxs("svg",{width:t,height:t,viewBox:"0 0 28 28",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[o.jsx("rect",{x:"2.5",y:"4",width:"14",height:"9",rx:"1.5",stroke:"currentColor",strokeWidth:"1.7",opacity:"0.42"}),o.jsx("path",{d:"M7 16v1.5h5",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",opacity:"0.42"}),o.jsx("rect",{x:"10.5",y:"2.5",width:"14",height:"9",rx:"1.5",stroke:"currentColor",strokeWidth:"1.7",opacity:"0.62"}),o.jsx("path",{d:"M15 14.5V16h5",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",opacity:"0.62"}),o.jsx("rect",{x:"6.5",y:"8.5",width:"15",height:"10",rx:"1.7",fill:"currentColor",fillOpacity:"0.12",stroke:"currentColor",strokeWidth:"1.9"}),o.jsx("path",{d:"M12 21v1.5H9.5M16 21v1.5h2.5M9.5 22.5h9",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round"})]})}const _0={hub:"Use this computer as Hub. Hub connects to and manages Client computers.","switch-to-hub":"Switch this computer from Client to Hub. It will manage Client computers instead of sharing its own screen.",client:"Keep this computer in Client mode so its screens, files, audio, and remote controls remain available to the active Hub.",wall:"Show live thumbnails from every connected Client. Choose a display, change tile size, or move into Control without opening another connection.",control:"Open the selected Client at full resolution and send mouse and keyboard input through the existing Hub session.","share-files":"Browse files on the Hub, send files to selected Clients, and manage shared folders and transfer progress.",agents:"Run approved commands on connected Clients through the Hub-hosted Codex Agent and LiveDesk permission controls."},hv={en:_0,ko:{hub:"이 컴퓨터를 Hub로 사용합니다. Hub는 Client 컴퓨터를 연결하고 관리합니다.","switch-to-hub":"이 컴퓨터를 Client에서 Hub로 바꿉니다. 자신의 화면 공유를 멈추고 Client 컴퓨터를 관리합니다.",client:"이 컴퓨터를 Client 모드로 유지합니다. 화면, 파일, 오디오와 원격 제어 기능이 활성 Hub에서 계속 사용 가능하도록 연결합니다.",wall:"연결된 모든 Client의 실시간 화면을 한곳에 표시합니다. 모니터와 타일 크기를 선택하고 새 연결 없이 Control로 이동할 수 있습니다.",control:"선택한 Client 화면을 전체 해상도로 열고 기존 Hub 세션을 통해 마우스와 키보드 입력을 전송합니다.","share-files":"Hub의 파일을 탐색하고 선택한 Client로 전송하며 공유 폴더와 전송 진행 상태를 관리합니다.",agents:"Hub의 Codex가 연결된 Client에서 LiveDesk 권한과 승인 범위 안의 명령을 실행합니다."},ja:{hub:"このコンピューターを LiveDesk Hub として運用します。Hub は Client 接続、Wall、Control、ファイル共有、Agents を一か所で管理する統合コントロールセンターで、ネットワーク変更後に押すと安全な接続情報も更新します。","switch-to-hub":"このコンピューターを Client から Hub に切り替えます。新しい役割を保存して同じデスクトップランタイムを再起動し、Wall を開きます。Client としての共有は停止します。",client:"このコンピューターを Client モードで維持し、画面、ファイル、音声、リモート操作をアクティブ Hub から利用できるようにします。",wall:"接続中のすべての Client のライブ画面を一覧表示します。ディスプレイやタイルサイズを選び、新しい接続なしで Control に移動できます。",control:"選択した Client をフル解像度で開き、既存の Hub セッションからマウスとキーボード入力を送信します。","share-files":"Hub のファイルを参照し、選択した Client への送信、共有フォルダー、転送状況を管理します。",agents:"Hub の Codex Agent が、LiveDesk の権限と承認の範囲内で接続中の Client にコマンドを実行します。"},zh:{hub:"将此电脑作为 LiveDesk Hub 运行。Hub 是统一控制中心,可集中管理 Client 连接、Wall、Control、文件共享和 Agents;网络变化后按下此按钮还会刷新安全连接信息。","switch-to-hub":"将此电脑从 Client 切换为 Hub。LiveDesk 保存新角色、重启同一桌面运行时并打开 Wall;此电脑将停止作为 Client 共享。",client:"让此电脑保持 Client 模式,使活动 Hub 可以继续使用它的屏幕、文件、音频和远程控制。",wall:"集中显示所有已连接 Client 的实时缩略图。可以选择显示器、调整磁贴大小,并在不新建连接的情况下进入 Control。",control:"以完整分辨率打开所选 Client,并通过现有 Hub 会话发送鼠标和键盘输入。","share-files":"浏览 Hub 文件、向所选 Client 发送文件,并管理共享文件夹和传输进度。",agents:"Hub 的 Codex Agent 会在 LiveDesk 权限与批准范围内,对已连接的 Client 执行命令。"},"zh-TW":{hub:"將此電腦作為 LiveDesk Hub 運作。Hub 是統一控制中心,可集中管理 Client 連線、Wall、Control、檔案分享與 Agents;網路變更後按下此按鈕也會更新安全連線資訊。","switch-to-hub":"將此電腦從 Client 切換為 Hub。LiveDesk 會儲存新角色、重新啟動同一桌面執行階段並開啟 Wall;此電腦將停止以 Client 身分共享。",client:"讓此電腦維持 Client 模式,使作用中 Hub 可繼續使用它的畫面、檔案、音訊與遠端控制。",wall:"集中顯示所有已連線 Client 的即時縮圖。可選擇顯示器、調整圖塊大小,並在不建立新連線的情況下進入 Control。",control:"以完整解析度開啟所選 Client,並透過現有 Hub 工作階段傳送滑鼠與鍵盤輸入。","share-files":"瀏覽 Hub 檔案、傳送檔案到所選 Client,並管理共享資料夾與傳輸進度。",agents:"Hub 的 Codex Agent 會在 LiveDesk 權限與核准範圍內,對已連線的 Client 執行命令。"},es:{hub:"Usa este equipo como LiveDesk Hub. Hub es el centro de control unificado para conexiones Client, Wall, Control, archivos y Agents; púlsalo tras cambios de red para actualizar el acceso seguro.","switch-to-hub":"Cambia este equipo de Client a Hub. LiveDesk guarda el nuevo rol, reinicia el mismo entorno de escritorio y abre Wall; el equipo deja de compartirse como Client.",client:"Mantiene este equipo en modo Client para que sus pantallas, archivos, audio y control remoto sigan disponibles desde el Hub activo.",wall:"Muestra miniaturas en vivo de todos los Clients conectados. Elige pantalla y tamaño, o entra en Control sin abrir otra conexión.",control:"Abre el Client seleccionado a resolución completa y envía ratón y teclado por la sesión Hub existente.","share-files":"Explora archivos del Hub, envíalos a los Clients seleccionados y administra carpetas compartidas y transferencias.",agents:"El Codex Agent del Hub ejecuta comandos en los Clients conectados dentro de los permisos y aprobaciones de LiveDesk."},fr:{hub:"Utilise cet ordinateur comme LiveDesk Hub. Hub est le centre de contrôle unifié des connexions Client, de Wall, Control, des fichiers et des Agents ; appuyez après un changement réseau pour actualiser l’accès sécurisé.","switch-to-hub":"Bascule cet ordinateur de Client vers Hub. LiveDesk enregistre le nouveau rôle, redémarre le même environnement de bureau et ouvre Wall ; le partage Client s’arrête.",client:"Maintient cet ordinateur en mode Client afin que ses écrans, fichiers, sons et commandes à distance restent disponibles depuis le Hub actif.",wall:"Affiche les miniatures en direct de tous les Clients connectés. Choisissez l’écran et la taille, ou passez à Control sans nouvelle connexion.",control:"Ouvre le Client sélectionné en pleine résolution et transmet souris et clavier via la session Hub existante.","share-files":"Parcourez les fichiers du Hub, envoyez-les aux Clients sélectionnés et gérez dossiers partagés et transferts.",agents:"Le Codex Agent du Hub exécute des commandes sur les Clients connectés selon les permissions et approbations de LiveDesk."},de:{hub:"Verwendet diesen Computer als LiveDesk Hub. Hub ist die gemeinsame Steuerzentrale für Client-Verbindungen, Wall, Control, Dateien und Agents; nach Netzwerkänderungen aktualisiert ein Klick den sicheren Zugriff.","switch-to-hub":"Wechselt diesen Computer von Client zu Hub. LiveDesk speichert die neue Rolle, startet dieselbe Desktop-Laufzeit neu und öffnet Wall; die Client-Freigabe endet.",client:"Hält diesen Computer im Client-Modus, damit Bildschirme, Dateien, Audio und Fernsteuerung am aktiven Hub verfügbar bleiben.",wall:"Zeigt Live-Vorschaubilder aller verbundenen Clients. Display und Kachelgröße wählen oder ohne neue Verbindung zu Control wechseln.",control:"Öffnet den gewählten Client in voller Auflösung und sendet Maus- und Tastatureingaben über die bestehende Hub-Sitzung.","share-files":"Dateien auf dem Hub durchsuchen, an gewählte Clients senden sowie Freigaben und Übertragungen verwalten.",agents:"Der Codex Agent des Hubs führt Befehle auf verbundenen Clients innerhalb der LiveDesk-Berechtigungen und Freigaben aus."},"pt-BR":{hub:"Usa este computador como LiveDesk Hub. Hub é o centro de controle unificado para conexões Client, Wall, Control, arquivos e Agents; após mudanças de rede, pressione para atualizar o acesso seguro.","switch-to-hub":"Muda este computador de Client para Hub. O LiveDesk salva a nova função, reinicia o mesmo runtime de desktop e abre o Wall; o compartilhamento como Client é encerrado.",client:"Mantém este computador no modo Client para que telas, arquivos, áudio e controle remoto continuem disponíveis no Hub ativo.",wall:"Mostra miniaturas ao vivo de todos os Clients conectados. Escolha a tela e o tamanho ou entre em Control sem criar outra conexão.",control:"Abre o Client selecionado em resolução total e envia mouse e teclado pela sessão Hub existente.","share-files":"Navegue pelos arquivos do Hub, envie para Clients selecionados e gerencie pastas compartilhadas e transferências.",agents:"O Codex Agent do Hub executa comandos nos Clients conectados dentro das permissões e aprovações do LiveDesk."},it:{hub:"Usa questo computer come LiveDesk Hub. Hub è il centro di controllo unificato per connessioni Client, Wall, Control, file e Agents; dopo modifiche di rete, premilo per aggiornare l’accesso sicuro.","switch-to-hub":"Passa questo computer da Client a Hub. LiveDesk salva il nuovo ruolo, riavvia lo stesso runtime desktop e apre Wall; la condivisione come Client termina.",client:"Mantiene questo computer in modalità Client, rendendo schermi, file, audio e controllo remoto disponibili all’Hub attivo.",wall:"Mostra le anteprime live di tutti i Client connessi. Scegli display e dimensione oppure passa a Control senza una nuova connessione.",control:"Apre il Client selezionato a piena risoluzione e invia mouse e tastiera tramite la sessione Hub esistente.","share-files":"Esplora i file dell’Hub, inviali ai Client selezionati e gestisci cartelle condivise e trasferimenti.",agents:"Il Codex Agent dell’Hub esegue comandi sui Client connessi entro i permessi e le approvazioni di LiveDesk."},id:{hub:"Gunakan komputer ini sebagai LiveDesk Hub. Hub adalah pusat kendali terpadu untuk koneksi Client, Wall, Control, file, dan Agents; tekan setelah perubahan jaringan untuk memperbarui akses aman.","switch-to-hub":"Alihkan komputer ini dari Client menjadi Hub. LiveDesk menyimpan peran baru, memulai ulang runtime desktop yang sama, lalu membuka Wall; berbagi sebagai Client berhenti.",client:"Pertahankan komputer ini dalam mode Client agar layar, file, audio, dan kendali jarak jauh tetap tersedia bagi Hub aktif.",wall:"Tampilkan thumbnail live semua Client yang terhubung. Pilih layar dan ukuran tile atau masuk ke Control tanpa koneksi baru.",control:"Buka Client terpilih pada resolusi penuh dan kirim input mouse serta keyboard melalui sesi Hub yang ada.","share-files":"Jelajahi file Hub, kirim ke Client terpilih, serta kelola folder bersama dan progres transfer.",agents:"Codex Agent di Hub menjalankan perintah pada Client terhubung sesuai izin dan persetujuan LiveDesk."},vi:{hub:"Dùng máy tính này làm LiveDesk Hub. Hub là trung tâm điều khiển hợp nhất cho kết nối Client, Wall, Control, tệp và Agents; nhấn sau khi đổi mạng để làm mới quyền truy cập an toàn.","switch-to-hub":"Chuyển máy tính này từ Client sang Hub. LiveDesk lưu vai trò mới, khởi động lại cùng môi trường desktop và mở Wall; việc chia sẻ dưới dạng Client sẽ dừng.",client:"Giữ máy tính này ở chế độ Client để màn hình, tệp, âm thanh và điều khiển từ xa luôn sẵn sàng cho Hub đang hoạt động.",wall:"Hiển thị ảnh thu nhỏ trực tiếp của mọi Client đã kết nối. Chọn màn hình, cỡ ô hoặc vào Control mà không tạo kết nối mới.",control:"Mở Client đã chọn ở độ phân giải đầy đủ và gửi chuột, bàn phím qua phiên Hub hiện có.","share-files":"Duyệt tệp trên Hub, gửi tới Client đã chọn và quản lý thư mục chia sẻ cùng tiến trình truyền.",agents:"Codex Agent trên Hub chạy lệnh trên các Client đã kết nối trong phạm vi quyền và phê duyệt của LiveDesk."},th:{hub:"ใช้คอมพิวเตอร์เครื่องนี้เป็น LiveDesk Hub โดย Hub คือศูนย์ควบคุมรวมสำหรับการเชื่อมต่อ Client, Wall, Control, ไฟล์ และ Agents และกดหลังเปลี่ยนเครือข่ายเพื่อรีเฟรชการเข้าถึงที่ปลอดภัย","switch-to-hub":"เปลี่ยนคอมพิวเตอร์นี้จาก Client เป็น Hub โดย LiveDesk จะบันทึกบทบาทใหม่ รีสตาร์ต desktop runtime เดิม และเปิด Wall พร้อมหยุดแชร์ในฐานะ Client",client:"ให้คอมพิวเตอร์นี้อยู่ในโหมด Client เพื่อให้ Hub ที่ใช้งานเข้าถึงหน้าจอ ไฟล์ เสียง และการควบคุมระยะไกลได้ต่อเนื่อง",wall:"แสดงภาพสดแบบย่อของ Client ที่เชื่อมต่อทั้งหมด เลือกจอและขนาด tile หรือเข้า Control ได้โดยไม่เปิดการเชื่อมต่อใหม่",control:"เปิด Client ที่เลือกแบบความละเอียดเต็ม และส่งเมาส์กับคีย์บอร์ดผ่าน session ของ Hub ที่มีอยู่","share-files":"เรียกดูไฟล์บน Hub ส่งไปยัง Client ที่เลือก และจัดการโฟลเดอร์แชร์กับความคืบหน้าการโอน",agents:"Codex Agent บน Hub เรียกใช้คำสั่งบน Client ที่เชื่อมต่อภายใต้สิทธิ์และการอนุมัติของ LiveDesk"},hi:{hub:"इस कंप्यूटर को LiveDesk Hub के रूप में उपयोग करें। Hub, Client कनेक्शन, Wall, Control, फ़ाइल और Agents का एकीकृत नियंत्रण केंद्र है; नेटवर्क बदलने के बाद सुरक्षित पहुँच ताज़ा करने के लिए इसे दबाएँ।","switch-to-hub":"इस कंप्यूटर को Client से Hub में बदलता है। LiveDesk नई भूमिका सहेजता है, उसी desktop runtime को restart करके Wall खोलता है और Client sharing रोक देता है।",client:"इस कंप्यूटर को Client मोड में रखता है ताकि इसकी स्क्रीन, फ़ाइलें, ऑडियो और remote control सक्रिय Hub पर उपलब्ध रहें।",wall:"सभी जुड़े Clients के live thumbnail दिखाता है। स्क्रीन और tile आकार चुनें या नया connection खोले बिना Control में जाएँ।",control:"चुने हुए Client को पूर्ण resolution में खोलता है और मौजूदा Hub session से mouse तथा keyboard input भेजता है।","share-files":"Hub की फ़ाइलें देखें, चुने हुए Clients को भेजें और shared folders तथा transfer progress प्रबंधित करें।",agents:"Hub का Codex Agent LiveDesk permissions और approvals के भीतर जुड़े Clients पर commands चलाता है।"},ar:{hub:"استخدم هذا الكمبيوتر بوصفه LiveDesk Hub. يمثّل Hub مركز التحكم الموحّد لاتصالات Client وWall وControl والملفات وAgents؛ اضغط عليه بعد تغييرات الشبكة لتحديث الوصول الآمن.","switch-to-hub":"يحوّل هذا الكمبيوتر من Client إلى Hub. يحفظ LiveDesk الدور الجديد ويعيد تشغيل بيئة سطح المكتب نفسها ويفتح Wall، ويتوقف الجهاز عن المشاركة كـ Client.",client:"يبقي هذا الكمبيوتر في وضع Client لتظل شاشاته وملفاته وصوته والتحكم عن بعد متاحة من Hub النشط.",wall:"يعرض صورا حية مصغرة لكل Clients المتصلين. اختر الشاشة وحجم البلاطات أو انتقل إلى Control من دون اتصال جديد.",control:"يفتح Client المحدد بالدقة الكاملة ويرسل إدخال الماوس ولوحة المفاتيح عبر جلسة Hub الحالية.","share-files":"استعرض ملفات Hub وأرسلها إلى Clients المحددين وأدر المجلدات المشتركة وتقدم النقل.",agents:"يشغّل Codex Agent على Hub الأوامر في Clients المتصلين ضمن صلاحيات وموافقات LiveDesk."},tr:{hub:"Bu bilgisayarı LiveDesk Hub olarak kullanır. Hub; Client bağlantıları, Wall, Control, dosyalar ve Agents için birleşik kontrol merkezidir; ağ değişikliklerinden sonra güvenli erişimi yenilemek için basın.","switch-to-hub":"Bu bilgisayarı Client rolünden Hub rolüne geçirir. LiveDesk yeni rolü kaydeder, aynı masaüstü runtime’ını yeniden başlatıp Wall’u açar; Client paylaşımı durur.",client:"Bu bilgisayarı Client modunda tutar; ekran, dosya, ses ve uzaktan kontrol özellikleri etkin Hub tarafından kullanılabilir kalır.",wall:"Bağlı tüm Client ekranlarının canlı küçük görüntülerini gösterir. Ekran ve kutu boyutunu seçin veya yeni bağlantı açmadan Control’e geçin.",control:"Seçili Client’ı tam çözünürlükte açar ve mevcut Hub oturumu üzerinden fare ile klavye girdisi gönderir.","share-files":"Hub dosyalarını gezin, seçili Client’lara gönderin ve paylaşılan klasörlerle aktarım ilerlemesini yönetin.",agents:"Hub Codex Agent, bağlı Client’larda LiveDesk izinleri ve onayları kapsamında komut çalıştırır."}};function Ch(t){const n=t?[t]:typeof navigator>"u"?["en"]:navigator.languages?.length?navigator.languages:[navigator.language];for(const r of n){const s=String(r||"").trim(),l=s.toLowerCase();if(!l)continue;if(l.startsWith("zh-tw")||l.startsWith("zh-hk"))return"zh-TW";if(l.startsWith("zh"))return"zh";if(l.startsWith("pt"))return"pt-BR";const u=l.split("-")[0];if(hv[s])return s;if(hv[u])return u}return"en"}function oh(t,n){const r=Ch(n);return hv[r]?.[t]||_0[t]}function gv(t,n,r){return`${t}
15
- ${oh(n,r)}`}const O0={eyebrow:"Change computer role",title:"Switch this computer to Hub?",description:"LiveDesk will stop sharing this computer as a Client, save the Hub role, restart the local runtime, and open Wall in this same window.",restartNotice:"Remote streams from this computer will end while LiveDesk restarts.",cancel:"Cancel",confirm:"Switch to Hub",closeLabel:"Close Hub switch confirmation"},kA={en:O0,ko:{eyebrow:"컴퓨터 역할 변경",title:"이 컴퓨터를 Hub로 전환하시겠습니까?",description:"이 컴퓨터의 Client 공유를 중지하고 Hub 역할을 저장한 뒤 로컬 런타임을 재시작하여 같은 창에서 Wall을 엽니다.",restartNotice:"LiveDesk가 재시작되는 동안 이 컴퓨터의 원격 스트림이 종료됩니다.",cancel:"취소",confirm:"Hub로 전환",closeLabel:"Hub 전환 확인 닫기"},ja:{eyebrow:"コンピューターの役割を変更",title:"このコンピューターを Hub に切り替えますか?",description:"このコンピューターの Client 共有を停止し、Hub の役割を保存してローカルランタイムを再起動し、同じウィンドウで Wall を開きます。",restartNotice:"LiveDesk の再起動中、このコンピューターのリモートストリームは終了します。",cancel:"キャンセル",confirm:"Hub に切り替える",closeLabel:"Hub 切り替え確認を閉じる"},zh:{eyebrow:"更改电脑角色",title:"将此电脑切换为 Hub?",description:"LiveDesk 将停止此电脑的 Client 共享,保存 Hub 角色,重启本地运行时,并在同一窗口中打开 Wall。",restartNotice:"LiveDesk 重启期间,此电脑的远程流将会结束。",cancel:"取消",confirm:"切换为 Hub",closeLabel:"关闭 Hub 切换确认"},"zh-TW":{eyebrow:"變更電腦角色",title:"要將此電腦切換為 Hub 嗎?",description:"LiveDesk 將停止此電腦的 Client 分享、儲存 Hub 角色、重新啟動本機執行階段,並在同一視窗中開啟 Wall。",restartNotice:"LiveDesk 重新啟動期間,此電腦的遠端串流將會結束。",cancel:"取消",confirm:"切換為 Hub",closeLabel:"關閉 Hub 切換確認"},es:{eyebrow:"Cambiar función del equipo",title:"¿Cambiar este equipo a Hub?",description:"LiveDesk dejará de compartir este equipo como Client, guardará la función Hub, reiniciará el entorno local y abrirá Wall en esta misma ventana.",restartNotice:"Los streams remotos de este equipo terminarán mientras LiveDesk se reinicia.",cancel:"Cancelar",confirm:"Cambiar a Hub",closeLabel:"Cerrar confirmación de cambio a Hub"},fr:{eyebrow:"Changer le rôle de l’ordinateur",title:"Basculer cet ordinateur vers Hub ?",description:"LiveDesk arrêtera le partage Client de cet ordinateur, enregistrera le rôle Hub, redémarrera le runtime local et ouvrira Wall dans cette même fenêtre.",restartNotice:"Les flux distants de cet ordinateur prendront fin pendant le redémarrage de LiveDesk.",cancel:"Annuler",confirm:"Basculer vers Hub",closeLabel:"Fermer la confirmation de bascule vers Hub"},de:{eyebrow:"Computerrolle ändern",title:"Diesen Computer auf Hub umstellen?",description:"LiveDesk beendet die Client-Freigabe dieses Computers, speichert die Hub-Rolle, startet die lokale Laufzeit neu und öffnet Wall im selben Fenster.",restartNotice:"Die Remote-Streams dieses Computers enden während des LiveDesk-Neustarts.",cancel:"Abbrechen",confirm:"Auf Hub umstellen",closeLabel:"Bestätigung für Hub-Wechsel schließen"},"pt-BR":{eyebrow:"Alterar função do computador",title:"Mudar este computador para Hub?",description:"O LiveDesk interromperá o compartilhamento deste computador como Client, salvará a função Hub, reiniciará o runtime local e abrirá o Wall nesta mesma janela.",restartNotice:"Os streams remotos deste computador serão encerrados enquanto o LiveDesk reinicia.",cancel:"Cancelar",confirm:"Mudar para Hub",closeLabel:"Fechar confirmação de mudança para Hub"},it:{eyebrow:"Cambia ruolo del computer",title:"Passare questo computer a Hub?",description:"LiveDesk interromperà la condivisione Client di questo computer, salverà il ruolo Hub, riavvierà il runtime locale e aprirà Wall nella stessa finestra.",restartNotice:"Gli stream remoti di questo computer termineranno durante il riavvio di LiveDesk.",cancel:"Annulla",confirm:"Passa a Hub",closeLabel:"Chiudi la conferma del passaggio a Hub"},id:{eyebrow:"Ubah peran komputer",title:"Alihkan komputer ini menjadi Hub?",description:"LiveDesk akan menghentikan berbagi komputer ini sebagai Client, menyimpan peran Hub, memulai ulang runtime lokal, lalu membuka Wall di jendela yang sama.",restartNotice:"Stream jarak jauh dari komputer ini akan berakhir saat LiveDesk dimulai ulang.",cancel:"Batal",confirm:"Alihkan ke Hub",closeLabel:"Tutup konfirmasi peralihan Hub"},vi:{eyebrow:"Đổi vai trò máy tính",title:"Chuyển máy tính này thành Hub?",description:"LiveDesk sẽ dừng chia sẻ máy tính này dưới dạng Client, lưu vai trò Hub, khởi động lại runtime cục bộ và mở Wall trong cùng cửa sổ.",restartNotice:"Các luồng từ xa của máy tính này sẽ kết thúc trong khi LiveDesk khởi động lại.",cancel:"Hủy",confirm:"Chuyển sang Hub",closeLabel:"Đóng xác nhận chuyển sang Hub"},th:{eyebrow:"เปลี่ยนบทบาทคอมพิวเตอร์",title:"เปลี่ยนคอมพิวเตอร์เครื่องนี้เป็น Hub หรือไม่",description:"LiveDesk จะหยุดแชร์คอมพิวเตอร์เครื่องนี้ในฐานะ Client บันทึกบทบาท Hub รีสตาร์ทรันไทม์ภายในเครื่อง และเปิด Wall ในหน้าต่างเดิม",restartNotice:"สตรีมระยะไกลจากคอมพิวเตอร์เครื่องนี้จะสิ้นสุดลงระหว่างที่ LiveDesk รีสตาร์ท",cancel:"ยกเลิก",confirm:"เปลี่ยนเป็น Hub",closeLabel:"ปิดการยืนยันการเปลี่ยนเป็น Hub"},hi:{eyebrow:"कंप्यूटर की भूमिका बदलें",title:"इस कंप्यूटर को Hub में बदलें?",description:"LiveDesk इस कंप्यूटर की Client साझेदारी बंद करेगा, Hub भूमिका सहेजेगा, स्थानीय रनटाइम पुनः आरंभ करेगा और इसी विंडो में Wall खोलेगा।",restartNotice:"LiveDesk के पुनः आरंभ होने के दौरान इस कंप्यूटर की रिमोट स्ट्रीम समाप्त हो जाएँगी।",cancel:"रद्द करें",confirm:"Hub में बदलें",closeLabel:"Hub परिवर्तन की पुष्टि बंद करें"},ar:{eyebrow:"تغيير دور الكمبيوتر",title:"هل تريد تحويل هذا الكمبيوتر إلى Hub؟",description:"سيوقف LiveDesk مشاركة هذا الكمبيوتر كـ Client، ويحفظ دور Hub، ويعيد تشغيل وقت التشغيل المحلي، ثم يفتح Wall في النافذة نفسها.",restartNotice:"ستنتهي التدفقات البعيدة من هذا الكمبيوتر أثناء إعادة تشغيل LiveDesk.",cancel:"إلغاء",confirm:"التحويل إلى Hub",closeLabel:"إغلاق تأكيد التحويل إلى Hub"},tr:{eyebrow:"Bilgisayar rolünü değiştir",title:"Bu bilgisayar Hub rolüne geçirilsin mi?",description:"LiveDesk bu bilgisayarın Client paylaşımını durdurur, Hub rolünü kaydeder, yerel çalışma zamanını yeniden başlatır ve Wall’u aynı pencerede açar.",restartNotice:"LiveDesk yeniden başlatılırken bu bilgisayarın uzak akışları sona erer.",cancel:"İptal",confirm:"Hub’a geçir",closeLabel:"Hub geçişi onayını kapat"}},F0={eyebrow:"Computer role",title:"Use this computer as Hub?",description:"Hub connects to and manages Client computers.",restartNotice:"If another computer is Hub, this computer will become the new Hub.",cancel:"Cancel",confirm:"Use as Hub",closeLabel:"Close Hub confirmation"},MA={en:F0,ko:{eyebrow:"컴퓨터 역할",title:"이 컴퓨터를 Hub로 사용할까요?",description:"Hub는 Client 컴퓨터를 연결하고 관리합니다.",restartNotice:"다른 컴퓨터가 Hub라면 이 컴퓨터가 새 Hub가 됩니다.",cancel:"취소",confirm:"Hub로 설정",closeLabel:"Hub 설정 확인 닫기"}};function AA(t){const n=Ch(t);return kA[n]||O0}function TA(t){const n=Ch(t);return MA[n]||F0}function NA(t=[]){return[...new Set(t.filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean))]}function RA(t=[],n=new Set){return t.find(r=>!n.has(r))||""}const EA=[{id:"docs",label:"Doc",icon:ah},{id:"support",label:"Support",icon:am},{id:"pricing",label:"Pricing",icon:rm},{id:"settings",label:"Settings",icon:rh}],tw=[0,1e3,2e3,5e3,1e4,2e4,3e4],jA=15e3;function DA(t=""){const n=t.trim().replace(/\/+$/,"");return n||(typeof window>"u"?"":window.location.port==="5179"?window.location.origin:"http://127.0.0.1:5179")}async function ru(t,n=!1){const r=n?"":sessionStorage.getItem("livedesk.client.csrf");if(r)return r;const s=await fetch(`${t}/api/runtime/status`,{cache:"no-store"}),l=await s.json().catch(()=>({}));if(!s.ok)throw new Error(l.error||`Client runtime returned HTTP ${s.status}.`);const u=String(l.csrfToken||"");return u&&sessionStorage.setItem("livedesk.client.csrf",u),u}function vv(t){return`${Math.max(0,Math.min(100,Number(t||0))).toFixed(0)}%`}function Dg(t){return Number.isFinite(t)?`${Math.max(0,Math.min(100,Number(t))).toFixed(0)}%`:"—"}function B0(t){return Number.isFinite(t)?vv(Number(t)):"0%"}function mu(t){const n=Number(t);return!Number.isFinite(n)||n<0?"—":n>=1024**4?`${(n/1024**4).toFixed(n>=10*1024**4?0:1)} TB`:n>=1024**3?`${(n/1024**3).toFixed(n>=10*1024**3?0:1)} GB`:`${(n/1024**2).toFixed(0)} MB`}function nw(t){const n=Math.max(0,Number(t||0));return n>=1024**3?`${(n/1024**3).toFixed(1)} GB/s`:n>=1024**2?`${(n/1024**2).toFixed(1)} MB/s`:n>=1024?`${(n/1024).toFixed(1)} KB/s`:`${n.toFixed(0)} B/s`}function IA(t,n){const r=Number(t||0)/1073741824,s=Number(n||0)/1024**3;return s>0?`${r.toFixed(1)} / ${s.toFixed(1)} GB`:"Checking..."}function LA(t,n){return!Number.isFinite(n)||Number(n)<=0?"Dedicated memory unavailable":Number.isFinite(t)?`${mu(t)} / ${mu(n)}`:`${mu(n)} available`}function PA(t){const n=Math.max(0,Math.floor(Number(t||0)/60)),r=Math.floor(n/1440),s=Math.floor(n%1440/60),l=n%60;return r>0?`${r}d ${s}h`:s>0?`${s}h ${l}m`:`${l}m`}function Mp({icon:t,label:n,value:r,detail:s,percent:l}){return o.jsxs("article",{className:"client-resource-metric",children:[o.jsxs("div",{className:"client-resource-metric-head",children:[o.jsx(t,{size:17}),o.jsx("span",{children:n}),o.jsx("strong",{children:r})]}),o.jsx("small",{title:s,children:s}),o.jsx("i",{"aria-hidden":"true",children:o.jsx("b",{style:{width:B0(l)}})})]})}function _A(t,n){const r=t?.user.user_metadata||{},s=r.full_name||r.name||r.preferred_username||t?.user.email||t?.user.id||n?.userName||n?.auth?.name||n?.userEmail||n?.userId||"Account";return String(s).trim()||"Account"}function OA(t,n){const r=t?.user.user_metadata||{};return NA([r.avatar_url,r.picture,n?.userAvatarUrl,n?.auth?.avatarUrl])}function FA({page:t,status:n}){const s={docs:{label:"DOC",title:"Using this computer",body:"This computer connects to its assigned Hub automatically. Keep LiveDesk running and manage screens, files, and remote control from the Hub."},pricing:{label:"PRICING",title:"LiveDesk plans",body:"Plans are based on how many computers the Hub manages. This Client computer does not need a separate subscription or setup."},settings:{label:"SETTINGS",title:"Computer preferences",body:"LiveDesk keeps the verified sign-in on this computer and reconnects to the assigned Hub automatically."}}[t];return o.jsxs("section",{className:"client-service-page",children:[o.jsx("span",{className:"client-unified-section-label",children:s.label}),o.jsx("h2",{children:s.title}),o.jsx("p",{children:s.body}),o.jsxs("div",{className:"client-service-page-card",children:[t==="docs"&&o.jsxs(o.Fragment,{children:[o.jsx("strong",{children:"Automatic connection"}),o.jsx("span",{children:"Start LiveDesk. This computer signs in, finds the Hub, and becomes available without another action."})]}),t==="pricing"&&o.jsxs(o.Fragment,{children:[o.jsx("strong",{children:"One plan, managed at the Hub"}),o.jsx("span",{children:"Computer access follows the account and plan used by the Hub."})]}),t==="settings"&&o.jsxs(o.Fragment,{children:[o.jsx("strong",{children:"Saved sign-in"}),o.jsx("span",{children:n?.auth?.persisted?"Enabled on this computer":"Sign in once to enable automatic reconnection"})]})]}),t==="settings"&&o.jsx(N0,{})]})}function BA({session:t,status:n,pin:r,error:s,roleChangeMessage:l,videoAccelerationBusy:u,slotInput:f,slotBusy:h,onSignIn:g,onPinChange:y,onSubmitPin:w,onSlotInputChange:b,onSaveSlot:S,onEnableVideoAcceleration:k}){const A=n?.connectionState==="connected",T=n?.videoAcceleration,j=u||T?.busy||T?.state==="installing",I=T?.ready?`${T.encoder||"H.264"} · ${T.driver||"VAAPI"}`:j?"Setting up…":T?.message||"Setup available",N=n?.system?.memoryTotalBytes?Number(n.system.memoryUsedBytes||0)/n.system.memoryTotalBytes*100:0,P=n?.system?.gpus||[],H=P.find(V=>Number.isFinite(V.usagePercent)||Number.isFinite(V.memoryTotalBytes))||P[0],F=Number.isFinite(H?.usagePercent)?Number(H?.usagePercent):null,$=Number.isFinite(H?.memoryTotalBytes)&&Number(H?.memoryTotalBytes)>0&&Number.isFinite(H?.memoryUsedBytes)?Number(H?.memoryUsedBytes)/Number(H?.memoryTotalBytes)*100:null,D=n?.system?.disks||[],K=n?.system?.network,z=!!K?.sampledAt,q=K?.interfaces||[],W=[...new Set(q.map(V=>V.name).filter(Boolean))],Y=q.map(V=>V.address).filter(Boolean);return o.jsxs("section",{className:"client-home-page",children:[o.jsxs("header",{className:"client-home-heading",children:[o.jsxs("div",{children:[o.jsx("p",{className:"client-unified-eyebrow",children:"THIS COMPUTER"}),o.jsx("h2",{children:n?.deviceName||"This Computer"})]}),o.jsxs("span",{className:`client-unified-role-chip ${A?"connected":""}`,children:[o.jsx(nr,{size:15})," ",A?"Online":"Connecting"]})]}),o.jsxs("div",{className:"client-home-layout",children:[o.jsxs("section",{className:"client-main-surface","aria-label":"Client computer",children:[o.jsxs("div",{className:"client-main-surface-head",children:[o.jsxs("div",{children:[o.jsx("span",{className:"client-unified-section-label",children:"SYSTEM STATUS"}),o.jsx("strong",{children:"Hardware at a glance"})]}),o.jsxs("small",{children:[o.jsx(h0,{size:14})," Uptime ",PA(n?.system?.uptimeSeconds)]})]}),o.jsxs("div",{className:"client-system-dashboard",children:[o.jsxs("section",{className:"client-performance-panel","aria-label":"Performance",children:[o.jsxs("div",{className:"client-system-subhead",children:[o.jsxs("div",{children:[o.jsx("span",{className:"client-unified-section-label",children:"PERFORMANCE"}),o.jsx("strong",{children:"Live resources"})]}),o.jsx("small",{children:"Live updates"})]}),o.jsxs("div",{className:"client-live-metrics",children:[o.jsx(Mp,{icon:Lb,label:"CPU",value:vv(n?.system?.cpuUsagePercent),detail:n?.system?.cpuLogicalCores?`${n.system.cpuLogicalCores} logical cores · Current processor usage`:"Current processor usage",percent:n?.system?.cpuUsagePercent}),o.jsx(Mp,{icon:zk,label:"Memory",value:vv(N),detail:IA(n?.system?.memoryUsedBytes,n?.system?.memoryTotalBytes),percent:N}),o.jsx(Mp,{icon:$k,label:"GPU",value:Dg(F),detail:H?.name||(n?.system?.hardwareCollecting?"Detecting graphics hardware…":"Graphics usage unavailable"),percent:F}),o.jsx(Mp,{icon:mo,label:"VRAM",value:Dg($),detail:LA(H?.memoryUsedBytes,H?.memoryTotalBytes),percent:$})]})]}),o.jsxs("section",{className:"client-storage-panel","aria-label":"Local storage",children:[o.jsxs("div",{className:"client-system-subhead",children:[o.jsxs("div",{children:[o.jsx("span",{className:"client-unified-section-label",children:"STORAGE"}),o.jsx("strong",{children:"Local drives"})]}),o.jsx("small",{children:D.length>0?`${D.length} ${D.length===1?"drive":"drives"}`:n?.system?.hardwareCollecting?"Detecting…":"Unavailable"})]}),o.jsxs("div",{className:"client-disk-list",children:[D.map(V=>o.jsxs("article",{className:"client-disk-row",children:[o.jsxs("div",{className:"client-disk-row-head",children:[o.jsxs("span",{children:[o.jsx(fu,{size:16}),o.jsx("strong",{children:V.mount||"Disk"}),o.jsx("small",{children:V.name||"Local disk"})]}),o.jsx("strong",{children:Dg(V.usedPercent)})]}),o.jsxs("small",{children:[mu(V.freeBytes)," free · ",mu(V.totalBytes)," total"]}),o.jsx("i",{"aria-hidden":"true",children:o.jsx("b",{style:{width:B0(V.usedPercent)}})})]},`${V.mount}-${V.name||""}`)),D.length===0&&o.jsxs("div",{className:"client-disk-empty",children:[o.jsx(fu,{size:18}),o.jsx("span",{children:n?.system?.hardwareCollecting?"Detecting local drives…":"Storage information is not available."})]})]})]}),o.jsxs("section",{className:"client-network-panel","aria-label":"Network activity",children:[o.jsxs("div",{className:"client-system-subhead",children:[o.jsxs("div",{children:[o.jsx("span",{className:"client-unified-section-label",children:"NETWORK"}),o.jsx("strong",{children:"Live traffic"})]}),o.jsx("small",{children:W.length>0?W.join(", "):"Detecting adapter"})]}),o.jsxs("div",{className:"client-network-live",children:[o.jsxs("div",{className:"client-network-adapter",children:[o.jsx(bh,{size:18}),o.jsxs("span",{children:[o.jsx("strong",{children:W.join(", ")||"Network"}),o.jsx("small",{children:Y.join(" / ")||"Checking active connection"})]})]}),o.jsxs("div",{className:"client-network-rate download",children:[o.jsx(Uk,{size:17}),o.jsxs("span",{children:[o.jsx("small",{children:"Receive"}),o.jsx("strong",{children:nw(z?K?.receiveBytesPerSecond:void 0)})]})]}),o.jsxs("div",{className:"client-network-rate upload",children:[o.jsx(qk,{size:17}),o.jsxs("span",{children:[o.jsx("small",{children:"Send"}),o.jsx("strong",{children:nw(z?K?.sendBytesPerSecond:void 0)})]})]}),o.jsx("small",{className:"client-network-total",children:z?`Total ${mu(K?.receivedBytes)} received / ${mu(K?.sentBytes)} sent`:"Traffic has not been measured yet."})]})]})]})]}),o.jsxs("aside",{className:"client-connection-panel",children:[o.jsx("span",{className:"client-unified-section-label",children:"LIVEDESK SERVICES"}),o.jsx("h3",{children:A?"Connected to the Hub":n?.authenticated?"Finding the Hub":"Connect this computer"}),A?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"client-unified-copy",children:"This computer is available from the LiveDesk Hub."}),o.jsxs("div",{className:"client-service-status-list",children:[o.jsxs("div",{children:[o.jsx(nr,{size:17}),o.jsxs("span",{children:[o.jsx("strong",{children:"Screen sharing"}),o.jsx("small",{children:n?.permissions?.screenCapture?"Active":"Waiting"})]})]}),o.jsxs("div",{children:[o.jsx(Ea,{size:17}),o.jsxs("span",{children:[o.jsx("strong",{children:"Remote control"}),o.jsx("small",{children:n?.permissions?.remoteInput?"Available":"Unavailable"})]})]}),o.jsxs("div",{children:[o.jsx(Id,{size:17}),o.jsxs("span",{children:[o.jsx("strong",{children:"File delivery"}),o.jsx("small",{children:n?.permissions?.files?"Ready to receive":"Unavailable"})]})]}),o.jsxs("div",{children:[o.jsx(Ld,{size:17}),o.jsxs("span",{children:[o.jsx("strong",{children:"Computer audio"}),o.jsx("small",{children:n?.permissions?.audio?"Available":"Unavailable"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"client-unified-copy",children:n?.authenticated?"LiveDesk is checking the registered Hub endpoints. A temporary Hub PIN can be used as a fallback.":"Sign in once on this computer. LiveDesk saves the verified session, finds the Hub, and starts screen sharing automatically."}),!t&&!n?.authenticated?o.jsxs("button",{className:"client-unified-primary",type:"button",onClick:g,children:[o.jsx(rc,{size:16})," Sign in with Google"]}):o.jsxs("p",{className:"client-unified-success",children:[o.jsx(tr,{size:16})," Signed in as ",t?.user.email||t?.user.id||n?.userEmail||n?.userId||"saved account"]}),o.jsxs("div",{className:"client-unified-pin-row",children:[o.jsx(Wk,{size:16}),o.jsx("input",{value:r,onChange:V=>y(V.target.value),placeholder:"6-digit Hub PIN",inputMode:"numeric","aria-label":"6-digit Hub PIN"}),o.jsx("button",{className:"client-unified-secondary",type:"button",onClick:w,disabled:r.length!==6,children:"Connect"})]})]}),T?.supported&&o.jsxs("div",{className:`client-video-acceleration state-${T.ready?"ready":T.state||"setup-required"}`,children:[o.jsx(Lb,{size:17}),o.jsxs("span",{children:[o.jsx("strong",{children:"Hardware video"}),o.jsx("small",{children:I})]}),!T.ready&&T.canInstall&&o.jsx("button",{type:"button",onClick:k,disabled:j,title:"Install and verify Linux FFmpeg hardware video support",children:j?"Setting up":"Enable"})]}),(s||n?.lastError)&&o.jsxs("p",{className:"client-unified-error",role:"alert",children:[o.jsx(p0,{size:15})," ",s||n?.lastError]}),l&&o.jsx("p",{className:"client-unified-success",children:l}),o.jsxs("div",{className:"client-slot-setting",children:[o.jsxs("label",{htmlFor:"client-slot-number",children:[o.jsx("span",{children:"Slot"}),o.jsx("input",{id:"client-slot-number",value:f,onChange:V=>b(V.target.value),inputMode:"numeric",pattern:"[0-9]*",placeholder:"1-999","aria-label":"Wall slot number",disabled:!A||h})]}),o.jsxs("button",{type:"button",onClick:S,disabled:!A||h||!f,"aria-label":"Save slot number",title:"Save slot number",children:[o.jsx(rh,{size:17}),o.jsx("span",{children:h?"Saving":"Set"})]})]})]})]})]})}function HA({runtimeBaseUrl:t=""}){const[n,r]=d.useState(null),[s,l]=d.useState(null),[u,f]=d.useState(!1),[h,g]=d.useState(""),[y,w]=d.useState(""),[b,S]=d.useState(""),[k,A]=d.useState(!1),[T,j]=d.useState(!1),[I,N]=d.useState(""),[P,H]=d.useState(!1),[F,$]=d.useState(null),[D,K]=d.useState(!1),[z,q]=d.useState("computer"),[W,Y]=d.useState(!1),V=d.useRef(null),he=d.useRef(null),ee=d.useRef(!1),U=d.useRef(null),L=d.useRef(null),le=d.useRef(!1),ve=d.useRef(!1),J=d.useRef(0),Ae=d.useRef(!1),ce=d.useMemo(()=>DA(t),[t]),Te=d.useMemo(()=>_A(s,n),[s,n]),Fe=d.useMemo(()=>OA(s,n),[s,n]),$e=JSON.stringify(Fe),[Ze,de]=d.useState(()=>new Set),Be=RA(Fe,Ze),Ve=Te.slice(0,1).toUpperCase()||"L";d.useEffect(()=>{de(new Set)},[$e]);const Je=d.useCallback(ye=>{de(Ne=>{if(!ye||Ne.has(ye))return Ne;const He=new Set(Ne);return He.add(ye),He})},[]),Qe=d.useCallback(async()=>{if(w(""),window.liveDesk?.auth?.signInWithGoogle){const ye=await window.liveDesk.auth.signInWithGoogle();return ye?.ok===!1?(w(ye.error||"LiveDesk could not open the system browser for Google sign-in."),!1):!0}return window.location.assign(`${ce}/auth/google`),!0},[ce]),yt=d.useCallback(async()=>{ve.current||(ve.current=!0,w("Your saved Google sign-in is incomplete. LiveDesk is reopening sign-in once to repair it."),await zt.auth.signOut({scope:"local"}).catch(()=>{}),l(null),await Qe()||(ve.current=!1))},[Qe]),ne=d.useCallback(async ye=>{const Ne=Qb(ye);if(Ne)throw new Error(Ne);if(ee.current)return!1;ee.current=!0;try{const He=await window.liveDesk?.auth?.persistSession?.(ye);if(He?.ok===!1)throw new Error(He.error||"LiveDesk could not validate the desktop session.");for(let pe=0;pe<2;pe+=1){const ae=await ru(ce,pe>0),fe=await fetch(`${ce}/api/auth/session`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":ae},signal:AbortSignal.timeout(1e4),body:JSON.stringify({accessToken:ye.access_token,refreshToken:ye.refresh_token,expiresAt:ye.expires_at,user:{id:ye.user.id,email:ye.user.email}})}),Ee=await fe.json().catch(()=>({}));if(fe.status===403&&pe===0){sessionStorage.removeItem("livedesk.client.csrf");continue}if(!fe.ok)throw new Error(Ee.error||`Client runtime returned HTTP ${fe.status}.`);return w(""),!0}throw new Error("Client runtime rejected the session transfer.")}finally{ee.current=!1}},[ce]),me=d.useCallback(()=>{const ye=U.current;if(ye)return ye;const Ne=(async()=>{try{const He=await fetch(`${ce}/api/client/status`,{cache:"no-store",signal:AbortSignal.timeout(1500)}),pe=await He.json().catch(()=>({}));if(!He.ok)throw new Error(pe.error||`Client runtime returned HTTP ${He.status}.`);if(pe.csrfToken&&sessionStorage.setItem("livedesk.client.csrf",pe.csrfToken),String(pe.role||"").toLowerCase()==="hub")throw new Error("This computer is assigned to the Hub role.");r(pe)}catch(He){w(He instanceof Error?He.message:String(He))}})();return U.current=Ne,Ne.finally(()=>{U.current===Ne&&(U.current=null)}),Ne},[ce]),Ge=d.useCallback(()=>{const ye=L.current;if(ye)return ye;const Ne=(async()=>{const He=await fetch(`${ce}/api/client/diagnostics`,{cache:"no-store",signal:AbortSignal.timeout(8e3)}),pe=await He.json().catch(()=>({}));if(!He.ok)throw new Error(pe.error||`Client diagnostics returned HTTP ${He.status}.`);if(String(pe.role||"").toLowerCase()==="hub")throw new Error("This computer is assigned to the Hub role.");r(pe)})();return L.current=Ne,Ne.finally(()=>{L.current===Ne&&(L.current=null)}),Ne},[ce]);d.useEffect(()=>{let ye=!1,Ne=null;const He=async()=>{await me(),ye||(Ne=window.setTimeout(()=>{He()},2e3))};return He(),()=>{ye=!0,Ne!==null&&window.clearTimeout(Ne)}},[me]),d.useEffect(()=>{if(z!=="computer")return;let ye=!1,Ne=null;const He=()=>{ye||(Ne=window.setTimeout(()=>{pe()},jA))},pe=async()=>{document.visibilityState==="visible"&&await Ge().catch(()=>{}),He()},ae=()=>{document.visibilityState==="visible"&&(Ne!==null&&(window.clearTimeout(Ne),Ne=null),pe())};return document.addEventListener("visibilitychange",ae),pe(),()=>{ye=!0,document.removeEventListener("visibilitychange",ae),Ne!==null&&window.clearTimeout(Ne)}},[z,Ge]),d.useEffect(()=>{if(Ae.current)return;const ye=Number(n?.slotNumber||0);N(ye>0?String(ye):"")},[n?.slotNumber]),d.useEffect(()=>{if(!F)return;const ye=window.setTimeout(()=>$(null),5e3);return()=>window.clearTimeout(ye)},[F]);const Se=d.useCallback(async()=>{const ye=Date.now();if(!(!n?.authenticated||n.connectionState==="connected"||!["waiting","reconnecting"].includes(String(n.agent?.state||""))||ye-J.current<4e3)){J.current=ye;try{const Ne=await fetch(`${ce}/api/client/reconnect`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await ru(ce)},body:JSON.stringify({onlyIfWaiting:!0,reason:"app-active"})});if(!Ne.ok)throw new Error(`Client reconnect returned HTTP ${Ne.status}.`);await me()}catch(Ne){w(Ne instanceof Error?Ne.message:String(Ne))}}},[ce,me,n]);d.useEffect(()=>{const ye=()=>{Se()},Ne=()=>{Se()},He=()=>{document.visibilityState==="visible"&&Se()};return window.addEventListener("online",ye),window.addEventListener("focus",Ne),document.addEventListener("visibilitychange",He),()=>{window.removeEventListener("online",ye),window.removeEventListener("focus",Ne),document.removeEventListener("visibilitychange",He)}},[Se]),d.useEffect(()=>{if(!u||!n||!s?.access_token||n.authenticated)return;if(Qb(s)==="refresh-token-required"){yt().catch(ae=>{ve.current=!1,w(ae instanceof Error?ae.message:String(ae))});return}let ye=!1,Ne,He=0;const pe=async()=>{if(ye)return;try{const fe=await ne(s);if(await me(),fe)return}catch(fe){w(fe instanceof Error?fe.message:String(fe))}if(ye)return;const ae=tw[Math.min(He,tw.length-1)];He+=1,Ne=window.setTimeout(()=>{pe()},ae)};return pe(),()=>{ye=!0,Ne!==void 0&&window.clearTimeout(Ne)}},[u,me,yt,s,n,ne]),d.useEffect(()=>{const ye=new URLSearchParams(window.location.search),Ne=ye.get("auth_error");if(!Ne)return;w(Ne),ye.delete("auth_error");const He=ye.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${He?`?${He}`:""}${window.location.hash}`)},[]),d.useEffect(()=>{let ye=!0;if(!window.liveDesk?.auth)return l(null),f(!0),me(),()=>{ye=!1};const Ne=window.liveDesk?.auth?.onComplete?.(pe=>{pe.ok&&pe.session?zt.auth.setSession(pe.session).catch(ae=>w(ae instanceof Error?ae.message:String(ae))):pe.ok&&pe.signedOut?(l(null),f(!0),zt.auth.signOut({scope:"local"})):pe.error&&w(pe.error)});(async()=>{try{const pe=window.liveDesk?.auth?.getSession?await window.liveDesk.auth.getSession():await zt.auth.getSession();if(!ye)return;const ae=R0(pe);l(ae),me()}catch(pe){ye&&w(pe instanceof Error?pe.message:String(pe))}finally{ye&&f(!0)}})();const{data:He}=zt.auth.onAuthStateChange((pe,ae)=>{if(ye){if(!ae&&window.liveDesk?.auth){f(!0);return}l(ae),f(!0),me()}});return()=>{ye=!1,Ne?.(),He.subscription.unsubscribe()}},[me]),d.useEffect(()=>{if(!u||!n||le.current||ve.current||s||n.authenticated)return;const ye=new URLSearchParams(window.location.search);if(!ye.has("livedesk_launch"))return;le.current=!0,ye.delete("livedesk_launch");const Ne=ye.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${Ne?`?${Ne}`:""}${window.location.hash}`),Qe().catch(He=>w(He instanceof Error?He.message:String(He)))},[u,s,Qe,n]);const ge=async()=>{Y(!1),window.liveDesk?.auth?.signOut?(await zt.auth.signOut(),(await window.liveDesk.auth.signOut())?.runtimeCleared===!1&&w("Signed out locally. The LiveDesk runtime could not be reached to clear its session.")):await fetch(`${ce}/api/auth/session`,{method:"DELETE",headers:{"X-LiveDesk-CSRF":await ru(ce)}}).catch(()=>{}),l(null),await me()};d.useEffect(()=>{if(!W)return;const ye=He=>{He.target instanceof Element&&He.target.closest(".account-popover, .rail-account")||Y(!1)},Ne=He=>{He.key==="Escape"&&Y(!1)};return window.addEventListener("pointerdown",ye),window.addEventListener("keydown",Ne),()=>{window.removeEventListener("pointerdown",ye),window.removeEventListener("keydown",Ne)}},[W]);const Ue=d.useCallback((ye=!0)=>{k||(K(!1),ye&&window.requestAnimationFrame(()=>he.current?.focus()))},[k]),Me=d.useCallback(()=>{k||!n?.authenticated||(he.current=document.activeElement instanceof HTMLElement?document.activeElement:null,S(""),K(!0))},[k,n?.authenticated]);d.useEffect(()=>{if(!D)return;const ye=window.requestAnimationFrame(()=>V.current?.focus()),Ne=pe=>{pe.target instanceof Element&&pe.target.closest(".client-hub-switch-popover, .client-hub-switch-trigger")||Ue(!1)},He=pe=>{pe.key==="Escape"&&Ue()};return window.addEventListener("pointerdown",Ne),window.addEventListener("keydown",He),()=>{window.cancelAnimationFrame(ye),window.removeEventListener("pointerdown",Ne),window.removeEventListener("keydown",He)}},[Ue,D]);const rt=async()=>{w("");try{const ye=await fetch(`${ce}/api/client/pin`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await ru(ce)},body:JSON.stringify({pin:h})}),Ne=await ye.json().catch(()=>({}));if(!ye.ok||Ne?.ok===!1)throw new Error(Ne?.error||"PIN could not be accepted.");g(""),await me()}catch(ye){w(ye instanceof Error?ye.message:String(ye))}},At=async()=>{K(!1),A(!0),S(""),w("");try{const ye=await fetch(`${ce}/api/runtime/switch-role`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await ru(ce)},body:JSON.stringify({role:"hub"})}),Ne=await ye.json().catch(()=>({}));if(!ye.ok||Ne?.ok===!1)throw new Error(Ne?.error||`Role change failed with HTTP ${ye.status}.`);S("Hub role accepted. LiveDesk is restarting this computer with the Hub Wall.");const He=Number(n?.runtimePid||0);await I0({baseUrl:ce,targetRole:"hub",previousRuntimePid:He,allowedStates:["running"]}),window.location.reload()}catch(ye){w(ye instanceof Error?ye.message:String(ye)),A(!1)}},O=async()=>{if(P)return;const ye=Number(I);if(!Number.isInteger(ye)||ye<1||ye>999){$({kind:"error",message:"Enter a slot number from 1 to 999."});return}H(!0),$(null);try{const Ne=await fetch(`${ce}/api/client/slot`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await ru(ce)},body:JSON.stringify({slotNumber:ye})}),He=await Ne.json().catch(()=>({}));if(!Ne.ok||He.ok===!1){if(He.error==="slot-taken"){const pe=He.conflict?.deviceName||He.conflict?.hostname||He.conflict?.deviceId||"another computer";throw new Error(`Slot ${String(ye).padStart(3,"0")} is already used by ${pe}.`)}throw new Error(He.error||`Slot update failed with HTTP ${Ne.status}.`)}Ae.current=!1,N(String(ye)),r(He),$({kind:"success",message:`Slot ${String(ye).padStart(3,"0")} saved. LiveDesk is reconnecting this Client.`})}catch(Ne){$({kind:"error",message:Ne instanceof Error?Ne.message:String(Ne)})}finally{H(!1),await me()}},qe=async()=>{if(!T){j(!0),w("");try{const ye=await fetch(`${ce}/api/client/video-acceleration/install`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await ru(ce)},body:JSON.stringify({confirm:!0})}),Ne=await ye.json().catch(()=>({}));if(r(Ne),!ye.ok||Ne.videoAcceleration?.ready!==!0)throw new Error(Ne.videoAcceleration?.error||Ne.error||"Linux hardware video setup did not complete.")}catch(ye){w(ye instanceof Error?ye.message:String(ye))}finally{j(!1),await me()}}},B=!!(n?.authenticated||s),Oe=d.useMemo(()=>Ch(),[]),We=oh("switch-to-hub",Oe),et=oh("client",Oe),it=AA(Oe);return o.jsxs("main",{className:"app-shell client-unified-shell",children:[o.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk Client tools",children:[o.jsx("div",{className:"rail-brand",title:"LiveDesk",children:o.jsx(P0,{size:25})}),o.jsx("nav",{className:"rail-tools","aria-label":"Client navigation",children:o.jsxs("div",{className:"client-main-tool-slot",children:[o.jsxs("button",{className:"rail-tool client-main-tool client-hub-tool client-hub-switch-trigger accent-blue",type:"button",onClick:Me,disabled:k||!n?.authenticated,"aria-busy":k,"aria-expanded":D,"aria-haspopup":"dialog","aria-controls":D?"client-hub-switch-popover":void 0,"aria-label":`Hub. ${We}`,"data-tooltip":D?void 0:gv("Hub","switch-to-hub",Oe),children:[o.jsx(mo,{size:19}),o.jsx("span",{children:k?"Switching…":"Hub"})]}),o.jsxs("button",{className:`rail-tool client-main-tool accent-blue ${z==="computer"?"active":""}`,type:"button",onClick:()=>q("computer"),"aria-current":z==="computer"?"page":void 0,"aria-label":`Client. ${et}`,"data-tooltip":gv("Client","client",Oe),children:[o.jsx(nr,{size:19}),o.jsx("span",{children:"Client"})]})]})}),o.jsxs("div",{className:"rail-footer",children:[EA.map(ye=>{const Ne=ye.icon;return o.jsxs("button",{className:`rail-tool compact ${z===ye.id?"active":""}`,type:"button",onClick:()=>q(ye.id),title:ye.label,children:[o.jsx(Ne,{size:18}),o.jsx("span",{children:ye.label})]},ye.id)}),o.jsxs("button",{className:`rail-account ${B?"signed-in":""}`,type:"button",onClick:()=>Y(ye=>!ye),"aria-expanded":W,"aria-haspopup":"dialog",title:B?"Account":"Sign in",children:[B&&Be?o.jsx("img",{src:Be,alt:Te,referrerPolicy:"no-referrer",onError:()=>Je(Be)},Be):B?o.jsx("span",{className:"avatar-fallback",children:Ve}):o.jsx(rc,{size:18}),o.jsx("span",{children:B?"Account":"Sign in"})]})]})]}),D&&o.jsxs("section",{id:"client-hub-switch-popover",className:"client-hub-switch-popover",role:"dialog","aria-modal":"false","aria-labelledby":"client-hub-switch-title","aria-describedby":"client-hub-switch-description client-hub-switch-restart",children:[o.jsxs("header",{className:"client-hub-switch-head",children:[o.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:o.jsx(mo,{size:19})}),o.jsx("span",{className:"client-hub-switch-eyebrow",children:it.eyebrow}),o.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>Ue(),"aria-label":it.closeLabel,children:o.jsx(vr,{size:17})})]}),o.jsx("h2",{id:"client-hub-switch-title",children:it.title}),o.jsx("p",{id:"client-hub-switch-description",children:it.description}),o.jsxs("p",{id:"client-hub-switch-restart",className:"client-hub-switch-notice",children:[o.jsx(Ea,{size:16,"aria-hidden":"true"}),o.jsx("span",{children:it.restartNotice})]}),o.jsxs("div",{className:"client-hub-switch-actions",children:[o.jsx("button",{type:"button",onClick:()=>Ue(),children:it.cancel}),o.jsxs("button",{ref:V,className:"primary",type:"button",onClick:()=>{At()},disabled:k||!n?.authenticated,children:[o.jsx(mo,{size:16}),it.confirm]})]})]}),W&&o.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[o.jsxs("div",{className:"account-popover-head",children:[o.jsx("div",{className:"account-popover-avatar",children:B&&Be?o.jsx("img",{src:Be,alt:Te,referrerPolicy:"no-referrer",onError:()=>Je(Be)},Be):B?o.jsx("span",{children:Ve}):o.jsx(rc,{size:18})}),o.jsxs("div",{children:[o.jsx("strong",{children:B?Te:"Account"}),o.jsx("p",{children:s?.user.email||n?.userEmail||n?.userId||"Not signed in"})]})]}),o.jsxs("dl",{className:"account-popover-facts",children:[o.jsx("dt",{children:"User"}),o.jsx("dd",{children:s?.user.email||n?.userEmail||n?.userId||"Not signed in"}),o.jsx("dt",{children:"Runtime"}),o.jsx("dd",{children:n?"Local app ready":"Checking local app"}),o.jsx("dt",{children:"Session"}),o.jsx("dd",{children:n?.auth?.persisted?"Saved on this computer":B?"Active for this run":"Not saved"}),o.jsx("dt",{children:"Role"}),o.jsx("dd",{children:"Client"})]}),B?o.jsxs("button",{className:"account-popover-action",onClick:()=>{ge()},type:"button",children:[o.jsx(m0,{size:16}),"Logout"]}):o.jsxs("button",{className:"account-popover-action primary",onClick:()=>{Y(!1),Qe()},type:"button",children:[o.jsx(rc,{size:16}),"Sign in with Google"]})]}),o.jsx("section",{className:"desk-stage client-unified-stage",children:z==="support"?o.jsx("section",{className:"client-unified-page",children:o.jsx(T0,{session:s,currentProductKey:"livedesk",appVersion:n?.appVersion||"",onSignIn:()=>{Qe()}})}):z!=="computer"?o.jsx("section",{className:"client-unified-page",children:o.jsx(FA,{page:z,status:n})}):o.jsx(BA,{session:s,status:n,pin:h,error:y,roleChangeMessage:b,videoAccelerationBusy:T,slotInput:I,slotBusy:P,onSignIn:()=>{Qe()},onPinChange:ye=>g(ye.replace(/\D/g,"").slice(0,6)),onSubmitPin:()=>{rt()},onSlotInputChange:ye=>{Ae.current=!0,N(ye.replace(/\D/g,"").slice(0,3))},onSaveSlot:()=>{O()},onEnableVideoAcceleration:()=>{qe()}})}),F&&o.jsxs("div",{className:`client-side-toast ${F.kind}`,role:F.kind==="error"?"alert":"status",children:[F.kind==="error"?o.jsx(p0,{size:18}):o.jsx(tr,{size:18}),o.jsx("span",{children:F.message}),o.jsx("button",{type:"button",onClick:()=>$(null),"aria-label":"Dismiss notification",children:o.jsx(vr,{size:16})})]})]})}function ac(t,n,r){if(r<0||n<0||n+r>t.length)throw new Error("Invalid LZO1X block: input overrun.")}function Ig(t,n,r){let s=0;for(;ac(t,n.inputIndex,1),t[n.inputIndex]===0;)s+=1,n.inputIndex+=1;const l=s*255+r+t[n.inputIndex];return n.inputIndex+=1,l}function Ap(t,n,r,s){if(ac(t,n.inputIndex,s),n.outputIndex+s>r.length)throw new Error("Invalid LZO1X block: output overrun.");r.set(t.subarray(n.inputIndex,n.inputIndex+s),n.outputIndex),n.inputIndex+=s,n.outputIndex+=s}function zA(t,n,r,s){const l=n-r;if(l<=0||s<=0)throw new Error("Invalid LZO1X block: invalid match distance.");let u=Math.min(l,s);for(t.set(t.subarray(r,r+u),n);u<s;){const f=Math.min(u,s-u);t.copyWithin(n+u,n,n+f),u+=f}return n+s}function H0(t,n){if(!(t instanceof Uint8Array)||t.length<3||n<0)throw new Error("Invalid LZO1X block.");const r=new Uint8Array(n),s={inputIndex:0,outputIndex:0};let l=0,u=0;if(t[s.inputIndex]>=22){const f=t[s.inputIndex]-17;s.inputIndex+=1,Ap(t,s,r,f),l=4}else t[s.inputIndex]>=18&&(l=t[s.inputIndex]-17,s.inputIndex+=1,Ap(t,s,r,l));for(;;){ac(t,s.inputIndex,1);const f=t[s.inputIndex];s.inputIndex+=1;let h,g;if((f&192)!==0)ac(t,s.inputIndex,1),g=s.outputIndex-((t[s.inputIndex]<<3)+(f>>2&7)+1),s.inputIndex+=1,u=(f>>5)+1,h=f&3;else if((f&32)!==0){u=(f&31)+2,u===2&&(u+=Ig(t,s,31)),ac(t,s.inputIndex,2);const y=t[s.inputIndex]|t[s.inputIndex+1]<<8;s.inputIndex+=2,g=s.outputIndex-((y>>2)+1),h=y&3}else if((f&16)!==0){u=(f&7)+2,u===2&&(u+=Ig(t,s,7)),ac(t,s.inputIndex,2);const y=t[s.inputIndex]|t[s.inputIndex+1]<<8;if(s.inputIndex+=2,g=s.outputIndex-(((f&8)<<11)+(y>>2)),h=y&3,g===s.outputIndex)break;g-=16384}else if(l===0){let y=f+3;y===3&&(y+=Ig(t,s,15)),Ap(t,s,r,y),l=4;continue}else l!==4?(ac(t,s.inputIndex,1),h=f&3,g=s.outputIndex-((f>>2)+(t[s.inputIndex]<<2)+1),s.inputIndex+=1,u=2):(ac(t,s.inputIndex,1),h=f&3,g=s.outputIndex-((f>>2)+(t[s.inputIndex]<<2)+2049),s.inputIndex+=1,u=3);if(g<0||s.outputIndex+u+h>r.length)throw new Error("Invalid LZO1X block: lookbehind overrun.");s.outputIndex=zA(r,s.outputIndex,g,u),l=h,Ap(t,s,r,h)}if(u!==3||s.inputIndex!==t.length||s.outputIndex!==r.length)throw new Error("Invalid LZO1X block: incomplete output.");return r}const aw=16,rw=8,$A=24*1024*1024,z0=new Uint8Array(new Uint32Array([16909060]).buffer)[0]===4,yv=new Uint32Array(65536);for(let t=0;t<yv.length;t+=1){const n=Math.round((t>>11&31)*255/31),r=Math.round((t>>5&63)*255/63),s=Math.round((t&31)*255/31);yv[t]=z0?(n|r<<8|s<<16|4278190080)>>>0:(n<<24|r<<16|s<<8|255)>>>0}function Jl(t,n){return t[n]|t[n+1]<<8}function UA(t,n){const r=Number(n);if(!Number.isSafeInteger(r)||r<aw||r>$A)throw new Error(`Invalid Mode 5 packet length: ${n}.`);const s=t instanceof Uint8Array?t:new Uint8Array(t),l=H0(s,r);if(l[0]!==76||l[1]!==68||l[2]!==53||l[3]!==68)throw new Error("Invalid Mode 5 packet magic.");if(l[4]!==1)throw new Error(`Unsupported Mode 5 packet version: ${l[4]}.`);const u=(l[5]&1)!==0,f=Jl(l,6),h=Jl(l,8),g=Jl(l,10),y=Jl(l,12);if(f<=0||h<=0||f>3840||h>2160)throw new Error(`Invalid Mode 5 frame size: ${f}x${h}.`);if(g<=0||g>256||y>8192)throw new Error(`Invalid Mode 5 tile header: ${g}/${y}.`);const w=[];let b=aw;for(let S=0;S<y;S+=1){if(b+rw>l.length)throw new Error("Mode 5 tile header is truncated.");const k=Jl(l,b),A=Jl(l,b+2),T=Jl(l,b+4),j=Jl(l,b+6);b+=rw;const I=T*j*2;if(T<=0||j<=0||T>g||j>g||k+T>f||A+j>h||b+I>l.length)throw new Error(`Invalid Mode 5 tile ${S}.`);w.push({x:k,y:A,width:T,height:j,pixels:l.subarray(b,b+I)}),b+=I}if(b!==l.length)throw new Error(`Mode 5 packet has ${l.length-b} trailing bytes.`);return{keyFrame:u,width:f,height:h,tileSize:g,tiles:w}}function qA(t,n,r,s){if(!(t instanceof Uint8ClampedArray)||t.length!==n*r*4||s.width!==n||s.height!==r)throw new Error("Mode 5 canvas state does not match the packet dimensions.");let l=n,u=r,f=0,h=0;const g=new Uint32Array(t.buffer,t.byteOffset,t.byteLength>>>2);for(const y of s.tiles){const w=z0&&(y.pixels.byteOffset&1)===0?new Uint16Array(y.pixels.buffer,y.pixels.byteOffset,y.pixels.byteLength>>>1):null;let b=0;for(let S=0;S<y.height;S+=1){let k=(y.y+S)*n+y.x;for(let A=0;A<y.width;A+=1){const T=b<<1,j=w?w[b]:y.pixels[T]|y.pixels[T+1]<<8;g[k]=yv[j],b+=1,k+=1}}l=Math.min(l,y.x),u=Math.min(u,y.y),f=Math.max(f,y.x+y.width),h=Math.max(h,y.y+y.height)}return s.tiles.length>0?{x:l,y:u,width:f-l,height:h-u}:null}const ja=new WeakMap,sw=854,iw=480,WA=3840,GA=2160,VA=500,hm=new WeakMap,bv=new WeakMap,wu=new Set,pu=new Set,uc=new WeakMap,hu=new Set,Bd=new WeakMap,wv=new WeakMap,xv=new WeakMap,lh=new WeakMap,$0=4,KA=2,Dd=4,QA=2,YA=2,XA=18,ZA=0,JA=250,U0=80,e1=5,t1=150,n1=1200,a1=18,r1=.65,q0=80,W0=125,s1=4,i1=2*1024*1024,o1=8,l1=16,c1=180,u1=3,Gv=2e3,G0=64,V0=32*1024*1024,d1=500,f1=25,m1=45,p1=20,K0=new Uint8Array(0),Vv=250,h1=globalThis.LIVEDESK_ENABLE_CANVAS_VISUAL_SAMPLING===!0;let Q0=1,Y0=0,X0=0,Sv=0,Z0=0;const Xf=[];let bm=0,J0=0,eS,tS=0,nS,aS;function wm(t,n){Xf.push({sequence:++Z0,type:t,canvasId:Bd.get(n)||0,observedAt:Date.now(),activeDecoderCount:wu.size,hardwareLeaseCount:pu.size,hardwareReleaseGeneration:bm}),Xf.length>256&&Xf.splice(0,Xf.length-256)}let al={h264DecodeAcceleration:"prefer-hardware"};function g1(t){t.h264DecodeAcceleration&&(al={...al,h264DecodeAcceleration:t.h264DecodeAcceleration})}function v1(t){return t.payload.byteLength===0?t:{...t,payload:K0}}function rS(t,n){const r=String(t.streamPurpose||"").trim().toLowerCase();return r==="wall"?!0:r==="control"?!1:n>=45e3}function sS(t){try{return t.paintIsCancelled()}catch{return!0}}function kh(t,n){const r=t.pendingFrames.get(n);if(r)return t.pendingFrames.delete(n),t.pendingFrameBytes=Math.max(0,t.pendingFrameBytes-r.encodedByteLength),t.pendingFrames.size===0&&t.pendingTrimTimer!==null&&(window.clearTimeout(t.pendingTrimTimer),t.pendingTrimTimer=null),r}function y1(t){const n=t.pendingFrames.entries().next().value;return n?kh(t,n[0]):void 0}function iS(t){t.pendingTrimTimer!==null&&(window.clearTimeout(t.pendingTrimTimer),t.pendingTrimTimer=null),t.pendingFrames.clear(),t.pendingFrameBytes=0,t.pendingFrameEvictedThroughTimestamp=-1}function Mh(t,n=performance.now()){for(;t.pendingFrames.size>0;){const r=t.pendingFrames.entries().next().value;if(!r)break;const s=n-r[1].queuedAt>Gv,l=t.pendingFrames.size>G0,u=t.pendingFrameBytes>V0;if(!s&&!l&&!u)break;t.pendingFrameEvictedThroughTimestamp=Math.max(t.pendingFrameEvictedThroughTimestamp,r[0]),kh(t,r[0]),t.pendingFrameEvictionCount+=1}}function b1(t,n,r,s,l,u=performance.now()){kh(t,n);const f={frame:r,queuedAt:u,queueSize:s,encodedByteLength:Math.max(0,Math.floor(Number(r.payload.byteLength||0))),paintIsCancelled:l};t.pendingFrames.set(n,f),t.pendingFrameBytes+=f.encodedByteLength,Mh(t,u),t.pendingFrameHighWaterMark=Math.max(t.pendingFrameHighWaterMark,t.pendingFrames.size),t.pendingFrameByteHighWaterMark=Math.max(t.pendingFrameByteHighWaterMark,t.pendingFrameBytes)}function oS(t,n){if(n.pendingTrimTimer!==null||n.pendingFrames.size===0)return;const r=n.pendingFrames.values().next().value;if(!r)return;const s=Math.max(1,Gv-(performance.now()-r.queuedAt)+1);n.pendingTrimTimer=window.setTimeout(()=>{n.pendingTrimTimer=null,ja.get(t)===n&&(Mh(n),oS(t,n))},s)}function lS(t){return pu.delete(t)?(bm+=1,wm("hardware-release",t),!0):!1}function w1(t,n,r){if(n!=="prefer-hardware"||!r)return!1;const s=uc.get(t);return!s||s.requested!==n||s.actual!=="prefer-software"||bm<=s.failedHardwareReleaseGeneration?!1:(uc.delete(t),hu.delete(t),J0+=1,eS=Date.now(),!0)}function Cv(t,n=al.h264DecodeAcceleration){const r=uc.get(t);return r?.requested===n?(r.actual!=="prefer-hardware"&&(pu.delete(t),hu.add(t)),r.actual):(r&&(uc.delete(t),hu.delete(t)),n!=="prefer-hardware"?(lS(t),hu.delete(t),n):(pu.has(t)||pu.add(t),"prefer-hardware"))}function Ah(t,n,r){if(n!=="prefer-hardware")return!1;const s=uc.get(t),l=ja.get(t),u=Date.now();return Bd.has(t)||Bd.set(t,Q0++),uc.set(t,{requested:n,actual:"prefer-software",reason:r,failedAt:u,failureCount:(s?.requested===n?s.failureCount:0)+1,codec:l?.codec||s?.codec||"",latencyMode:l?.latencyMode||s?.latencyMode||"smooth",inputCount:l?.inputSerial??s?.inputCount??0,outputCount:l?.outputSerial??s?.outputCount??0,lastInputAt:l?.lastInputAt??s?.lastInputAt??0,lastOutputAt:l?.lastOutputAt??s?.lastOutputAt??0,lastPaintAt:l?.lastPaintAt??s?.lastPaintAt??0,decodeQueueHighWaterMark:Math.max(l?.decodeQueueHighWaterMark??0,s?.decodeQueueHighWaterMark??0),decodeQueueOverflowSamples:Math.max(l?.decodeQueueOverflowSamples??0,s?.decodeQueueOverflowSamples??0),decodeQueueOverflowAgeMs:l?.decodeQueueOverflowStartedAt?Math.max(0,performance.now()-l.decodeQueueOverflowStartedAt):s?.decodeQueueOverflowAgeMs,failedHardwareReleaseGeneration:bm}),pu.delete(t),hu.add(t),tS+=1,nS=r,aS=u,!0}function dc(t){t.interactivePipelineFallbackTimer!==null&&(window.clearTimeout(t.interactivePipelineFallbackTimer),t.interactivePipelineFallbackTimer=null),t.interactivePipelineFallbackFrame!==null&&(window.cancelAnimationFrame(t.interactivePipelineFallbackFrame),t.interactivePipelineFallbackFrame=null),t.interactivePipelineRecoveryFrames=[],t.interactivePipelineRecoveryBytes=0,t.interactivePipelinePaintIsCancelled=void 0,t.interactivePipelineGuardTimestampUs=null}function cS(t,n){const r=n.interactivePipelineRecoveryFrames,s=n.interactivePipelinePaintIsCancelled,l=n.onPaint;if(dc(n),r.length===0||s?.()||ja.get(t)!==n||n.hardwareAcceleration!=="prefer-hardware"||!Ah(t,n.requestedAcceleration,"interactive-pipeline-latency"))return!1;const u=n.requestedAcceleration,f=n.latencyMode;hs(t);try{for(const h of r)Qv(t,h,l,u,f,s,!1)}catch{hs(t)}return!0}function x1(t,n,r){const s=Math.max(0,Number(n.payload.byteLength||0));return t.interactivePipelineRecoveryFrames.length>=s1||t.interactivePipelineRecoveryBytes+s>i1?(dc(t),!1):(t.interactivePipelineRecoveryFrames.push({...n,payload:n.payload.slice()}),t.interactivePipelineRecoveryBytes+=s,t.interactivePipelinePaintIsCancelled=r,!0)}function S1(t,n,r,s,l=performance.now()){const u=()=>{if(!(ja.get(t)!==n||n.interactivePipelineGuardTimestampUs!==r)){if(!n.pendingFrames.has(r)){dc(n);return}cS(t,n)}},f=h=>{if(n.interactivePipelineFallbackFrame=null,!(ja.get(t)!==n||n.interactivePipelineGuardTimestampUs!==r)){if(!n.pendingFrames.has(r)){dc(n);return}if(h-l>=s){u();return}n.interactivePipelineFallbackFrame=window.requestAnimationFrame(f)}};n.interactivePipelineFallbackTimer=window.setTimeout(u,s),n.interactivePipelineFallbackFrame=window.requestAnimationFrame(f)}function C1(t,n,r,s=64){try{let l=wv.get(t);l||(l={canvas:document.createElement("canvas"),lastHash:"",initialized:!1},wv.set(t,l));const u=Math.max(8,Math.min(64,Math.round(s))),f=Math.max(1,Math.round(u*Math.max(1,r)/Math.max(1,n)));(l.canvas.width!==u||l.canvas.height!==f)&&(l.canvas.width=u,l.canvas.height=f);const h=l.canvas.getContext("2d",{willReadFrequently:!0});if(!h)return{visualHash:"",visualChanged:!0};h.drawImage(t,0,0,Math.max(1,n),Math.max(1,r),0,0,u,f);const g=h.getImageData(0,0,u,f).data;let y=2166136261;for(let S=0;S<g.length;S+=4)y^=g[S],y=Math.imul(y,16777619),y^=g[S+1],y=Math.imul(y,16777619),y^=g[S+2],y=Math.imul(y,16777619);const w=(y>>>0).toString(16).padStart(8,"0"),b=!l.initialized||w!==l.lastHash;return l.initialized=!0,l.lastHash=w,{visualHash:w,visualChanged:b}}catch{return{visualHash:"",visualChanged:!0}}}function kv(t,n,r,s=Vv,l=64,u){if(!h1&&u)return uS(t,u);let f=xv.get(t);f||(f={lastHash:"",initialized:!1,lastCanvasSampleAt:0},xv.set(t,f));const h=performance.now();if(f.initialized&&s>0&&h-f.lastCanvasSampleAt<s)return{visualHash:f.lastHash,visualChanged:!1};const g=C1(t,n,r,l);return f.initialized=!0,f.lastHash=g.visualHash,f.lastCanvasSampleAt=h,g}function uS(t,n){let r=lh.get(t);r||(r={lastHash:"",initialized:!1},lh.set(t,r));const s=String(n.contentHash||""),l=!r.initialized||!s||s!==r.lastHash;return r.initialized=!0,r.lastHash=s,{visualHash:s,visualChanged:l}}function dS(t,n,r=!1){const s=bv.get(t);if(s)return s;const l=t.getContext("2d",{alpha:!1,desynchronized:n==="interactive",willReadFrequently:r});if(l){const u=l.getContextAttributes?.(),f={context:l,presentation:u?.desynchronized?"desync":"sync"};return bv.set(t,f),f}return null}function k1(t){const n=String(t.frameMode||t.mode||"").toLowerCase(),r=String(t.compression||"").toLowerCase(),s=String(t.mimeType||"").toLowerCase();return n==="mode2-lzo"||r==="lzo1x"||s==="application/vnd.livedesk.lzo-rgb565"||n==="mode2-lz4"||String(t.compression||"").toLowerCase()==="lz4"||s==="application/vnd.livedesk.lz4-raw"}function M1(t){return String(t.frameMode||t.mode||"").toLowerCase()==="mode3-h264-hw"||String(t.codec||"").toLowerCase()==="h264"||String(t.mimeType||"").toLowerCase()==="video/h264"}function A1(t){const n=String(t.frameMode||t.mode||"").toLowerCase(),r=String(t.mimeType||"").toLowerCase();return n==="mode5-lzo-delta"||r==="application/vnd.livedesk.lzo-rgb565-delta"}function ow(t,n,r){let s=r,l=n;if(s===15){let u=255;for(;u===255;){if(l>=t.length)throw new Error("Invalid LZ4 block: length overrun.");u=t[l],l+=1,s+=u}}return{length:s,cursor:l}}function T1(t,n){const r=new Uint8Array(n);let s=0,l=0;for(;s<t.length;){const u=t[s];s+=1;const f=ow(t,s,u>>4);s=f.cursor;const h=f.length;if(s+h>t.length||l+h>r.length)throw new Error("Invalid LZ4 block: literal overrun.");if(r.set(t.subarray(s,s+h),l),s+=h,l+=h,s>=t.length)break;if(s+2>t.length)throw new Error("Invalid LZ4 block: missing offset.");const g=t[s]|t[s+1]<<8;if(s+=2,g<=0||g>l)throw new Error("Invalid LZ4 block: bad match offset.");const y=ow(t,s,u&15);s=y.cursor;const w=y.length+4;if(l+w>r.length)throw new Error("Invalid LZ4 block: match overrun.");let b=l-g;for(let S=0;S<w;S+=1)r[l]=r[b],l+=1,b+=1}if(l!==r.length)throw new Error("Invalid LZ4 block: incomplete output.");return r}function N1(t){const n=Math.max(1,Math.floor(t.width||0)),r=Math.max(1,Math.floor(t.height||0)),s=String(t.compression||"").toLowerCase(),l=String(t.pixelFormat||t.codec||"").toLowerCase();if(s==="lzo1x"||String(t.frameMode||t.mode||"").toLowerCase()==="mode2-lzo"||String(t.mimeType||"").toLowerCase()==="application/vnd.livedesk.lzo-rgb565"){const w=Math.max(1,Math.floor(t.bytesPerPixel||2)),b=n*r*2,S=Math.floor(t.uncompressedByteLength||b);if(w!==2||S!==b)throw new Error(`Invalid mode2 RGB565 frame size: ${S} for ${n}x${r}.`);if(l&&l!=="rgb565le"&&l!=="rgb565")throw new Error(`Unsupported mode2 pixel format: ${l}`);const k=H0(t.payload,b),A=new Uint8ClampedArray(n*r*4);for(let T=0,j=0;T<k.length;T+=2,j+=4){const I=k[T]|k[T+1]<<8,N=I>>11&31,P=I>>5&63,H=I&31;A[j]=N<<3|N>>2,A[j+1]=P<<2|P>>4,A[j+2]=H<<3|H>>2,A[j+3]=255}return new ImageData(A,n,r)}const f=Math.max(1,Math.floor(t.bytesPerPixel||4)),h=Math.max(n*r*f,Math.floor(t.uncompressedByteLength||0)),g=T1(t.payload,h);if(f!==4)throw new Error(`Unsupported mode2 pixel size: ${f}`);const y=new Uint8ClampedArray(n*r*4);if(l==="rgba32"||l==="rgba")y.set(g.subarray(0,y.length));else for(let w=0,b=0;b<y.length;w+=4,b+=4)y[b]=g[w+2],y[b+1]=g[w+1],y[b+2]=g[w],y[b+3]=g[w+3];return new ImageData(y,n,r)}function lw(t,n="smooth",r=al.h264DecodeAcceleration){const s=window.VideoDecoder;if(!s||!window.EncodedVideoChunk)throw new Error("WebCodecs H.264 decode is not supported in this browser.");const l=ja.get(t);if(l&&l.decoder.state!=="closed"&&l.latencyMode===n)return l;l&&hs(t);let u;const f=new s({output:h=>{if(ja.get(t)!==u){h.close();return}const g=Number(h.timestamp||0),y=performance.now();u.outputSerial+=1,Mh(u,y);let w=kh(u,g);if(!w&&g>u.pendingFrameEvictedThroughTimestamp&&u.pendingFrames.size>0&&(w=y1(u),u.timestampFallbacks+=1),!w){u.pendingFrameUnmatchedOutputCount+=1,u.droppedForLatency+=1,u.lastOutputAt=y,h.close();return}const b=u.interactivePipelineGuardTimestampUs===g;if(sS(w)){b&&dc(u),u.droppedForLatency+=1,u.lastOutputAt=y,h.close();return}const S=h.displayWidth||h.codedWidth||t.width||960,k=h.displayHeight||h.codedHeight||t.height||540,A=Number(w?.frame.durationUs||0),T=Number(h.duration||0),j=Math.max(16,Math.min(250,(A>0?A:T||83333)/1e3));u.targetPaintIntervalMs=j;const I=Math.max(0,y-w.queuedAt),P=rS(w.frame,A>0?A:Math.round(j*1e3))?W0:q0;if(u.latencyMode==="interactive"&&u.hardwareAcceleration==="prefer-hardware"&&b&&u.interactivePipelineRecoveryFrames.length>0&&I>P){h.close(),u.droppedForLatency+=1,cS(t,u);return}b&&dc(u),Math.abs(u.interactiveBurstOutputCadenceMs-j)>1&&(u.interactiveBurstOutputTimeCursor=0,u.interactiveBurstOutputTimeCount=0,u.interactiveBurstOutputCadenceMs=j,u.interactiveBurstOutputWindowMs=0),u.interactiveBurstOutputTimes[u.interactiveBurstOutputTimeCursor]=y,u.interactiveBurstOutputTimeCursor=(u.interactiveBurstOutputTimeCursor+1)%Dd,u.interactiveBurstOutputTimeCount=Math.min(Dd,u.interactiveBurstOutputTimeCount+1);const H=u.interactiveBurstOutputTimeCount>=Dd?y-u.interactiveBurstOutputTimes[u.interactiveBurstOutputTimeCursor]:0;for(u.interactiveBurstOutputWindowMs=Math.max(0,H),u.decodedFrames.push({videoFrame:h,pending:w,decodedAt:y,width:S,height:k,durationMs:j}),u.latencyMode==="interactive"&&u.targetPaintIntervalMs>20&&u.interactiveBurstOutputTimeCount>=Dd&&H<=Math.min(m1,Math.max(f1,u.targetPaintIntervalMs-5))&&(u.interactiveBurstTailHoldArmed=!0),u.lastOutputAt=y;u.decodedFrames.length>Kv(u);)ch(u,u.decodedFrames.shift(),"capacity");u.renderQueueHighWaterMark=Math.max(u.renderQueueHighWaterMark,u.decodedFrames.length),mS(u),u.renderTimer!==null&&u.renderScheduledAt>0&&performance.now()-u.renderScheduledAt>d1&&(typeof document>"u"||document.visibilityState==="visible")&&(window.cancelAnimationFrame(u.renderTimer),u.renderTimer=null,u.renderScheduledAt=0),u.renderTimer!==null&&u.decodedFrames.length>=$0&&(window.cancelAnimationFrame(u.renderTimer),u.renderTimer=null,u.renderScheduledAt=0),uh(t,u)},error:()=>{ja.get(t)===u&&(Ah(t,u.requestedAcceleration,"decoder-error"),hs(t))}});return Y0+=1,Bd.has(t)||Bd.set(t,Q0++),u={decoder:f,configured:!1,configKey:"",codec:"",requestedAcceleration:r,hardwareAcceleration:Cv(t,r),latencyMode:n,keyFrameSeen:!1,droppedForLatency:0,pendingFrames:new Map,pendingFrameBytes:0,pendingFrameHighWaterMark:0,pendingFrameByteHighWaterMark:0,pendingFrameEvictionCount:0,pendingFrameUnmatchedOutputCount:0,pendingFrameEvictedThroughTimestamp:-1,pendingTrimTimer:null,decodedFrames:[],renderQueueHighWaterMark:0,renderQueueCapacityDropCount:0,renderQueueAgeDropCount:0,renderTimer:null,renderScheduledAt:0,flushTimer:null,flushInFlight:!1,flushCount:0,timestampFallbacks:0,inputSerial:0,outputSerial:0,lastFlushInputSerial:0,lastOutputAt:0,lastPaintAt:0,lastInputAt:0,interactiveBufferPrimed:!1,interactiveBufferStartedAt:0,interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,interactiveBurstTailHoldArmed:!1,interactiveBurstTailHoldCount:0,interactiveBurstOutputTimes:new Float64Array(Dd),interactiveBurstOutputTimeCursor:0,interactiveBurstOutputTimeCount:0,interactiveBurstOutputCadenceMs:0,interactiveBurstOutputWindowMs:0,interactivePipelineFallbackTimer:null,interactivePipelineFallbackFrame:null,interactivePipelineGuardTimestampUs:null,interactivePipelineRecoveryFrames:[],interactivePipelineRecoveryBytes:0,interactivePipelinePaintIsCancelled:void 0,interactiveBackingWidth:0,interactiveBackingHeight:0,interactiveBackingSourceWidth:0,interactiveBackingSourceHeight:0,interactiveBackingMeasuredAt:0,lastInputFrameSeq:void 0,targetPaintIntervalMs:1e3/12,nextChunkTimestampUs:0,healthSampleStartedAt:performance.now(),healthInputSerial:0,healthOutputSerial:0,decodeQueueHighWaterMark:0,decodeQueueOverflowStartedAt:0,decodeQueueOverflowSamples:0},ja.set(t,u),wu.add(t),Sv=Math.max(Sv,wu.size),wm("create",t),u}function fS(t){dc(t),t.renderTimer!==null&&(window.cancelAnimationFrame(t.renderTimer),t.renderTimer=null),t.renderScheduledAt=0,t.flushTimer!==null&&(window.clearTimeout(t.flushTimer),t.flushTimer=null),t.flushInFlight=!1;const n=t.decodedFrames;t.decodedFrames=[];for(const r of n)try{r.videoFrame.close()}catch{}t.interactiveBufferPrimed=!1,t.interactiveBufferStartedAt=0,t.interactiveBurstTailHoldArmed=!1,t.interactiveBurstOutputTimeCursor=0,t.interactiveBurstOutputTimeCount=0,t.interactiveBurstOutputCadenceMs=0,t.interactiveBurstOutputWindowMs=0}function ch(t,n,r="other"){n&&(n.videoFrame.close(),t.droppedForLatency+=1,r==="capacity"?t.renderQueueCapacityDropCount+=1:r==="age"&&(t.renderQueueAgeDropCount+=1))}function Kv(t){return t.latencyMode==="interactive"?t.targetPaintIntervalMs<=20?QA:Dd:String(t.decodedFrames[0]?.pending?.frame.frameMode||t.decodedFrames[0]?.pending?.frame.mode||"").toLowerCase()==="mode4-h264-atlas"?KA:$0}function mS(t,n=performance.now()){const r=Kv(t);for(;t.decodedFrames.length>r;)ch(t,t.decodedFrames.shift(),"capacity");const s=t.latencyMode==="interactive"?U0:JA;let l=t.decodedFrames[0];for(;t.decodedFrames.length>0&&l&&n-l.decodedAt>s;)ch(t,t.decodedFrames.shift(),"age"),l=t.decodedFrames[0]}function pS(t,n){if(n.hardwareAcceleration!=="prefer-hardware"||n.latencyMode==="interactive"||n.flushTimer!==null||n.flushInFlight)return;const r=t1;n.flushTimer=window.setTimeout(async()=>{n.flushTimer=null;const s=performance.now();if(Mh(n,s),ja.get(t)!==n||n.decoder.state!=="configured"||n.pendingFrames.size===0||n.inputSerial<=n.lastFlushInputSerial||n.lastOutputAt>0&&s-n.lastOutputAt<r)return;const l=n.inputSerial;n.flushInFlight=!0,n.flushCount+=1,n.keyFrameSeen=!1;try{await n.decoder.flush(),n.lastFlushInputSerial=Math.max(n.lastFlushInputSerial,l)}catch{ja.get(t)===n&&Xp(n)}finally{n.flushInFlight=!1,ja.get(t)===n&&n.inputSerial>l&&n.pendingFrames.size>0&&performance.now()-n.lastOutputAt>=r&&pS(t,n)}},r)}function R1(t,n,r,s){const l=performance.now();if(n.interactiveBackingWidth>0&&n.interactiveBackingHeight>0&&l-n.interactiveBackingMeasuredAt<VA)return{width:Math.min(r,n.interactiveBackingWidth),height:Math.min(s,n.interactiveBackingHeight)};const u=typeof t.getBoundingClientRect=="function"?t.getBoundingClientRect():{width:Number(t.clientWidth||t.width||0),height:Number(t.clientHeight||t.height||0)},f=Math.max(1,Math.min(2,Number(globalThis.devicePixelRatio)||1)),h=Math.max(0,Number(t.width||0)),g=Math.max(0,Number(t.height||0)),y=u.width>0?Math.round(u.width*f):h||sw,w=u.height>0?Math.round(u.height*f):g||iw,b=Math.min(1,y/r,w/s),S=Math.min(1,Math.max(sw/r,iw/s)),k=Math.min(1,WA/r,GA/s),A=Math.max(.01,Math.min(k,Math.max(S,b)));return n.interactiveBackingWidth=Math.max(1,Math.round(r*A)),n.interactiveBackingHeight=Math.max(1,Math.round(s*A)),n.interactiveBackingMeasuredAt=l,{width:n.interactiveBackingWidth,height:n.interactiveBackingHeight}}function cw(t,n,r){const s=performance.now();try{if(!r.pending||sS(r.pending)){n.droppedForLatency+=1;return}const l=n.latencyMode==="interactive"?R1(t,n,r.width,r.height):{width:r.width,height:r.height},u=l.width,f=l.height;(t.width!==u||t.height!==f)&&(t.width=u,t.height=f);const h=dS(t,n.latencyMode,n.hardwareAcceleration==="prefer-software");if(h?.context.drawImage(r.videoFrame,0,0,r.width,r.height,0,0,u,f),r.pending){const g=performance.now(),w=n.latencyMode==="interactive"?uS(t,r.pending.frame):kv(t,r.width,r.height,Vv,64,r.pending.frame),b=v1(r.pending.frame);try{n.onPaint?.(b,{deviceId:b.deviceId,frameSeq:b.frameSeq,mode:b.frameMode||b.mode||b.codec||b.mimeType,width:r.width,height:r.height,byteLength:b.byteLength,queuedForMs:Math.max(0,s-r.pending.queuedAt),decodedForMs:Math.max(0,r.decodedAt-r.pending.queuedAt),scheduledForMs:Math.max(0,s-r.decodedAt),drawMs:Math.max(0,g-s),queueSize:r.pending.queueSize,renderQueueSize:n.decodedFrames.length,droppedForLatency:n.droppedForLatency,h264DecodeAcceleration:n.hardwareAcceleration,decoderLabel:n.hardwareAcceleration,decoderFlushCount:n.flushCount,decoderTimestampFallbacks:n.timestampFallbacks,decoderInputCount:n.inputSerial,decoderOutputCount:n.outputSerial,targetPaintIntervalMs:n.targetPaintIntervalMs,canvasPresentation:h?.presentation||"sync",interactiveBufferWaitCount:n.interactiveBufferWaitCount,interactiveBufferWaitMs:n.interactiveBufferWaitMs,interactiveQueueDrainCount:n.interactiveQueueDrainCount,interactiveBurstOutputWindowMs:n.interactiveBurstOutputWindowMs,interactiveBurstTailHoldCount:n.interactiveBurstTailHoldCount,visualHash:w.visualHash,visualChanged:w.visualChanged,paintedAt:g})}catch{}}n.lastPaintAt=performance.now()}finally{r.videoFrame.close()}}function uh(t,n){if(n.renderTimer!==null||n.decodedFrames.length===0)return;const r=Math.max(16,Math.min(250,n.targetPaintIntervalMs||1e3/12)),s=()=>{if(n.renderTimer=null,n.renderScheduledAt=0,n.decodedFrames.length===0)return;const l=performance.now();if(mS(n,l),n.decodedFrames.length===0){n.interactiveBurstTailHoldArmed=!1;return}if(n.latencyMode==="interactive"){const g=n.targetPaintIntervalMs<=20;if(g&&!n.interactiveBufferPrimed){n.interactiveBufferStartedAt<=0&&(n.interactiveBufferStartedAt=l,n.interactiveBufferWaitCount+=1);const w=n.decodedFrames.length>=YA,b=l-n.interactiveBufferStartedAt>=XA;if(!w&&!b){n.renderScheduledAt=performance.now(),n.renderTimer=window.requestAnimationFrame(s);return}n.interactiveBufferWaitMs+=Math.max(0,l-n.interactiveBufferStartedAt),n.interactiveBufferPrimed=!0}else g||(n.interactiveBufferPrimed=!0);if(!g&&n.interactiveBurstTailHoldArmed&&n.decodedFrames.length===1&&l-n.decodedFrames[0].decodedAt<=U0-p1){n.interactiveBurstTailHoldArmed=!1,n.interactiveBurstTailHoldCount+=1,n.renderScheduledAt=performance.now(),n.renderTimer=window.requestAnimationFrame(s);return}const y=n.decodedFrames.shift();if(y)try{cw(t,n,y)}catch{}n.decodedFrames.length===0&&(n.interactiveQueueDrainCount+=1,n.interactiveBufferPrimed=!1,n.interactiveBufferStartedAt=0,n.interactiveBurstTailHoldArmed=!1),uh(t,n);return}const u=n.lastPaintAt>0?n.lastPaintAt+r:l+ZA;if(!(l+e1>=u||n.decodedFrames.length>=Math.max(1,Kv(n)-1))){n.renderScheduledAt=performance.now(),n.renderTimer=window.requestAnimationFrame(s);return}const h=n.decodedFrames.shift();if(h)try{cw(t,n,h)}catch{}uh(t,n)};n.renderScheduledAt=performance.now(),n.renderTimer=window.requestAnimationFrame(s)}function hS(t,n){if(ja.get(t)!==n||n.decoder.state==="closed")return!1;for(n.renderTimer!==null&&(window.cancelAnimationFrame(n.renderTimer),n.renderTimer=null),n.renderScheduledAt=0;n.decodedFrames.length>1;)ch(n,n.decodedFrames.shift());return n.lastPaintAt=0,n.interactiveBufferPrimed=!1,n.interactiveBufferStartedAt=0,n.interactiveBurstTailHoldArmed=!1,n.interactiveBurstOutputTimeCursor=0,n.interactiveBurstOutputTimeCount=0,n.interactiveBurstOutputCadenceMs=0,n.interactiveBurstOutputWindowMs=0,uh(t,n),!0}function Lg(){if(!(typeof document>"u"||document.visibilityState!=="visible"))for(const t of wu){const n=ja.get(t);if(!n||n.decoder.state==="closed"){wu.delete(t);continue}hS(t,n)}}typeof document<"u"&&typeof window<"u"&&(document.addEventListener("visibilitychange",Lg),window.addEventListener("focus",Lg),window.addEventListener("pageshow",Lg));function hs(t){lS(t),wu.delete(t),lh.delete(t);const n=ja.get(t);if(n){ja.delete(t),X0+=1,iS(n),n.onPaint=void 0,fS(n);try{n.decoder.state!=="closed"&&n.decoder.reset()}catch{}try{n.decoder.state!=="closed"&&n.decoder.close()}catch{}wm("close",t)}}function Md(t){t&&(uc.delete(t),hu.delete(t),bv.delete(t),xv.delete(t),wv.delete(t),lh.delete(t),hm.delete(t),hs(t))}function E1(t,n){const r=ja.get(t),s=uc.get(t);if(!r&&!s)return null;const l=f=>f>0?Math.max(0,n-f):void 0,u=r?.pendingFrames.values().next().value;return{canvasId:Bd.get(t)||0,canvasWidth:Math.max(0,Number(t.width||0)),canvasHeight:Math.max(0,Number(t.height||0)),decoderState:r?.decoder.state||"fallback-pending",configured:r?.configured||!1,keyFrameSeen:r?.keyFrameSeen||!1,codec:r?.codec||s?.codec||"",requestedAcceleration:r?.requestedAcceleration||s?.requested||al.h264DecodeAcceleration,configuredAcceleration:r?.hardwareAcceleration||s?.actual||al.h264DecodeAcceleration,latencyMode:r?.latencyMode||s?.latencyMode||"smooth",decodeQueueSize:Math.max(0,Number(r?.decoder.decodeQueueSize||0)),decodeQueueHighWaterMark:Math.max(0,Number(r?.decodeQueueHighWaterMark??0),Number(s?.decodeQueueHighWaterMark??0)),decodeQueueOverflowSamples:Math.max(0,Number(r?.decodeQueueOverflowSamples??0),Number(s?.decodeQueueOverflowSamples??0)),decodeQueueOverflowAgeMs:r?.decodeQueueOverflowStartedAt?Math.max(0,n-r.decodeQueueOverflowStartedAt):s?.decodeQueueOverflowAgeMs,pendingFrameCount:r?.pendingFrames.size||0,pendingFrameBytes:r?.pendingFrameBytes||0,pendingFrameHighWaterMark:r?.pendingFrameHighWaterMark||0,pendingFrameByteHighWaterMark:r?.pendingFrameByteHighWaterMark||0,pendingFrameEvictionCount:r?.pendingFrameEvictionCount||0,pendingFrameUnmatchedOutputCount:r?.pendingFrameUnmatchedOutputCount||0,pendingFrameOldestAgeMs:u?Math.max(0,n-u.queuedAt):void 0,pendingFrameMaxCount:G0,pendingFrameMaxBytes:V0,pendingFrameMaxAgeMs:Gv,renderQueueSize:r?.decodedFrames.length||0,renderQueueHighWaterMark:r?.renderQueueHighWaterMark||0,renderQueueCapacityDropCount:r?.renderQueueCapacityDropCount||0,renderQueueAgeDropCount:r?.renderQueueAgeDropCount||0,interactiveBurstTailHoldCount:r?.interactiveBurstTailHoldCount||0,interactiveBurstOutputWindowMs:Math.max(0,Number(r?.interactiveBurstOutputWindowMs||0)),interactivePipelineRecoveryBytes:Math.max(0,Number(r?.interactivePipelineRecoveryBytes||0)),targetPaintIntervalMs:Math.max(0,Number(r?.targetPaintIntervalMs||0)),droppedForLatency:Math.max(0,Number(r?.droppedForLatency||0)),inputCount:r?.inputSerial??s?.inputCount??0,outputCount:r?.outputSerial??s?.outputCount??0,lastInputAgeMs:l(r?.lastInputAt??s?.lastInputAt??0),lastOutputAgeMs:l(r?.lastOutputAt??s?.lastOutputAt??0),lastPaintAgeMs:l(r?.lastPaintAt??s?.lastPaintAt??0),softwareFallbackReason:s?.reason,softwareFallbackAt:s?.failedAt,softwareFallbackCount:s?.failureCount||0}}function Tp(t,n={}){const r=performance.now(),l=(t?[t]:[...new Set([...wu,...hu])]).map(h=>E1(h,r)).filter(h=>h!==null),u=l.reduce((h,g)=>h+g.pendingFrameCount,0),f=l.reduce((h,g)=>h+g.pendingFrameBytes,0);return{capturedAt:Date.now(),hardwareRequestPolicy:"all-active",activeDecoderCount:l.filter(h=>h.decoderState!=="fallback-pending").length,hardwareLeaseCount:pu.size,hardwareReleaseGeneration:bm,hardwareRecoveryProbeCount:J0,lastHardwareRecoveryProbeAt:eS,activeSoftwareFallbackCount:l.filter(h=>h.configuredAcceleration==="prefer-software"&&h.requestedAcceleration==="prefer-hardware").length,decoderCreateCount:Y0,decoderCloseCount:X0,activeDecoderHighWaterMark:Sv,decoderLifecycleSequence:Z0,decoderLifecycleEvents:n.includeLifecycleEvents===!1?[]:Xf.map(h=>({...h})),softwareFallbackEventCount:tS,lastSoftwareFallbackReason:nS,lastSoftwareFallbackAt:aS,pendingFrameCount:u,pendingFrameBytes:f,canvases:l}}function Xp(t,n=1){try{t.decoder.state!=="closed"&&t.decoder.reset()}catch{}t.configured=!1,t.configKey="",t.keyFrameSeen=!1,iS(t),fS(t),t.lastPaintAt=0,t.lastOutputAt=0,t.lastInputAt=0,t.interactiveBufferPrimed=!1,t.interactiveBufferStartedAt=0,t.lastInputFrameSeq=void 0,t.nextChunkTimestampUs=0,t.healthSampleStartedAt=performance.now(),t.healthInputSerial=t.inputSerial,t.healthOutputSerial=t.outputSerial,t.decodeQueueOverflowStartedAt=0,t.decodeQueueOverflowSamples=0,t.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(n)))}function j1(t,n,r=performance.now()){const s=Math.max(0,Number.isFinite(n)?n:0);if(t.decodeQueueHighWaterMark=Math.max(t.decodeQueueHighWaterMark,s),s<=o1)return t.decodeQueueOverflowStartedAt=0,t.decodeQueueOverflowSamples=0,!1;t.decodeQueueOverflowStartedAt<=0?(t.decodeQueueOverflowStartedAt=r,t.decodeQueueOverflowSamples=1):t.decodeQueueOverflowSamples+=1;const l=Math.max(0,r-t.decodeQueueOverflowStartedAt);return s>=l1||t.decodeQueueOverflowSamples>=u1&&l>=c1}function D1(t,n,r,s,l,u){n.decoder.configure(r),n.configured=!0,n.configKey=s,n.codec=r.codec,n.requestedAcceleration=u,n.hardwareAcceleration=l,n.keyFrameSeen=!1,n.nextChunkTimestampUs=0,n.lastInputFrameSeq=void 0,wm("configure",t)}function I1(t,n){if(n.latencyMode!=="interactive"||n.hardwareAcceleration!=="prefer-hardware")return!1;const r=performance.now();if(r-n.healthSampleStartedAt<n1)return!1;const s=n.inputSerial-n.healthInputSerial,l=n.outputSerial-n.healthOutputSerial;return n.healthSampleStartedAt=r,n.healthInputSerial=n.inputSerial,n.healthOutputSerial=n.outputSerial,s<a1||l/Math.max(1,s)>=r1?!1:(Ah(t,n.requestedAcceleration,"interactive-health"),hs(t),!0)}function Ad(t,n=1){if(!t)return!1;const r=ja.get(t);return r?(r.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(n))),hs(t),!0):!1}function L1(t){if(!t)return!1;const n=ja.get(t);return n?hS(t,n):!1}function P1(t,n,r,s="interactive"){hs(t);const l=performance.now(),u=UA(n.payload,n.uncompressedByteLength||0),f=String(n.streamId||"mode5");let h=hm.get(t);if(!h||h.streamId!==f||h.width!==u.width||h.height!==u.height){const T=new Uint8ClampedArray(u.width*u.height*4);for(let j=3;j<T.length;j+=4)T[j]=255;h={streamId:f,width:u.width,height:u.height,rgba:T,imageData:new ImageData(T,u.width,u.height),keyFrameSeen:!1,inputSerial:0,outputSerial:0},hm.set(t,h)}if(!h)throw new Error("Mode 5 canvas state could not be initialized.");h.inputSerial+=1;const y=Number(n.streamFrameSeq||0);if(y>0&&(h.lastStreamFrameSeq=y),!u.keyFrame&&!h.keyFrameSeen)return;u.keyFrame&&(h.keyFrameSeen=!0);const w=qA(h.rgba,h.width,h.height,u),b=performance.now();(t.width!==h.width||t.height!==h.height)&&(t.width=h.width,t.height=h.height);const S=dS(t,s),k=performance.now();w&&S?.context.putImageData(h.imageData,0,0,w.x,w.y,w.width,w.height);const A=performance.now();h.outputSerial+=1,r?.(n,{deviceId:n.deviceId,frameSeq:n.frameSeq,mode:n.frameMode||n.mode||n.mimeType,width:h.width,height:h.height,byteLength:n.byteLength,queuedForMs:Math.max(0,A-l),decodedForMs:Math.max(0,b-l),scheduledForMs:0,drawMs:Math.max(0,A-k),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:"prefer-software",decoderLabel:"lzo-rgb565-delta",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:h.inputSerial,decoderOutputCount:h.outputSerial,targetPaintIntervalMs:Math.max(1,Number(n.durationUs||0)/1e3||1e3/30),canvasPresentation:S?.presentation||"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:String(n.contentHash||""),visualChanged:Number(n.deltaVisualTileCount||0)>0,paintedAt:A})}const Pg=[{code:30,maxFrameSize:1620,maxMacroblocksPerSecond:40500},{code:31,maxFrameSize:3600,maxMacroblocksPerSecond:108e3},{code:32,maxFrameSize:5120,maxMacroblocksPerSecond:216e3},{code:40,maxFrameSize:8192,maxMacroblocksPerSecond:245760},{code:41,maxFrameSize:8192,maxMacroblocksPerSecond:245760},{code:42,maxFrameSize:8704,maxMacroblocksPerSecond:522240},{code:50,maxFrameSize:22080,maxMacroblocksPerSecond:589824},{code:51,maxFrameSize:36864,maxMacroblocksPerSecond:983040},{code:52,maxFrameSize:36864,maxMacroblocksPerSecond:2073600}];function uw(t,n){for(let r=Math.max(0,n);r+3<t.length;r+=1)if(!(t[r]!==0||t[r+1]!==0)){if(t[r+2]===1)return{index:r,length:3};if(t[r+2]===0&&t[r+3]===1)return{index:r,length:4}}return null}function _1(t){let n=0;for(;n<t.length;){const r=uw(t,n);if(!r)break;const s=r.index+r.length,l=uw(t,s),u=l?.index??t.length;if(s<u&&(t[s]&31)===7){const f=[];let h=0;for(let g=s+1;g<u;g+=1){const y=t[g];if(h>=2&&y===3){h=0;continue}f.push(y),h=y===0?h+1:0}if(f.length>=3)return`avc1.${f.slice(0,3).map(g=>g.toString(16).toUpperCase().padStart(2,"0")).join("")}`}n=l?l.index:t.length}return""}function O1(t,n,r,s,l=""){const u=Math.ceil(t/16)*Math.ceil(n/16),f=r>0?1e6/r:30,h=u*f,g=Pg.find(y=>u<=y.maxFrameSize&&h<=y.maxMacroblocksPerSecond)||Pg[Pg.length-1];return _1(s)||l||`avc1.42E0${g.code.toString(16).toUpperCase().padStart(2,"0")}`}function Qv(t,n,r,s,l="smooth",u=()=>!1,f=!0){hm.delete(t);const h=String(n.h264Format||"").toLowerCase()==="avc"?"avc":"annexb",g=Math.max(1,Math.floor(n.width||960)),y=Math.max(1,Math.floor(n.height||540)),w=Math.max(1,Math.floor(n.durationUs||1e6/12)),b=s||al.h264DecodeAcceleration,S=n.isKeyFrame===!0||String(n.chunkType||"").toLowerCase()==="key";w1(t,b,S);let k=lw(t,l,b);const A=O1(g,y,w,n.payload,k.codec);let T=Cv(t,b),j="";const I=()=>{j=[n.streamId||"",n.commandId||"",g,y,A,h,b,T,l].join("|")};I(),k.onPaint=r,k.configured&&k.decoder.state!=="configured"&&(k.configured=!1,k.configKey=""),k.configured&&k.configKey!==j&&(hs(t),k=lw(t,l,b),k.onPaint=r,T=Cv(t,b),I());const N=()=>({codec:A,codedWidth:g,codedHeight:y,hardwareAcceleration:T,optimizeForLatency:!0,avc:{format:h}}),P=L=>k.hardwareAcceleration!=="prefer-hardware"||!Ah(t,k.requestedAcceleration,L)?!1:(hs(t),f&&S&&Qv(t,n,r,b,l,u,!1),!0),H=()=>{try{return D1(t,k,N(),j,T,b),!0}catch(L){if(P("configure-error"))return!1;throw hs(t),L}};if(!k.configured&&!H())return;const F=Number(n.streamFrameSeq||0);if(F>0&&k.lastInputFrameSeq!==void 0&&(F<=k.lastInputFrameSeq&&(!S||F===k.lastInputFrameSeq||(Xp(k,k.lastInputFrameSeq-F+1),!H()))||F>k.lastInputFrameSeq+1&&(Xp(k,F-k.lastInputFrameSeq-1),!S||!H()))||(F>0&&(k.lastInputFrameSeq=F),!S&&!k.keyFrameSeen))return;S&&(k.keyFrameSeen=!0);const $=Number(k.decoder.decodeQueueSize||0);if(j1(k,$)){if(k.latencyMode==="interactive"&&k.hardwareAcceleration==="prefer-hardware"){P("decode-queue-overflow");return}if(Xp(k),!S||!H())return;k.keyFrameSeen=!0}const D=k.nextChunkTimestampUs;k.nextChunkTimestampUs+=w,b1(k,D,n,$,u),oS(t,k),k.inputSerial+=1,k.lastInputAt=performance.now(),k.inputSerial===1&&wm("first-input",t);const K=n.payload.buffer,z=K instanceof ArrayBuffer?[K]:[],q=rS(n,w),W=!q&&k.outputSerial>0,Y=S&&k.latencyMode==="interactive"&&k.hardwareAcceleration==="prefer-hardware"&&(q||W),V=q?W0:q0;Y&&(dc(k),k.interactivePipelineGuardTimestampUs=D);const he=k.interactivePipelineGuardTimestampUs!==null&&k.interactivePipelineRecoveryFrames.length>0,ee=Y||he?x1(k,n,u):!1,U=new EncodedVideoChunk({type:S?"key":"delta",timestamp:D,duration:w,data:n.payload,transfer:z});n.payload=K0;try{k.decoder.decode(U)}catch(L){if(P("decode-error"))return;throw hs(t),L}ee&&ja.get(t)===k&&k.interactivePipelineGuardTimestampUs===D&&Y&&S1(t,k,D,V),pS(t,k),I1(t,k)}async function _g(t,n,r,s,l,u="smooth",f=r){if(A1(n)){r()||P1(t,n,s,u);return}if(M1(n)){r()||Qv(t,n,s,l,u,f);return}if(hm.delete(t),k1(n)){hs(t);const S=N1(n);if(r())return;(t.width!==S.width||t.height!==S.height)&&(t.width=S.width,t.height=S.height);const k=t.getContext("2d"),A=performance.now();k?.putImageData(S,0,0);const T=performance.now(),j=kv(t,S.width,S.height,Vv,64,n);s?.(n,{deviceId:n.deviceId,frameSeq:n.frameSeq,mode:n.frameMode||n.mode||n.codec||n.mimeType,width:S.width,height:S.height,byteLength:n.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,T-A),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:al.h264DecodeAcceleration,decoderLabel:"lzo-rgb565",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:j.visualHash,visualChanged:j.visualChanged,paintedAt:T});return}hs(t);const h=new Blob([n.payload],{type:n.mimeType}),g=await createImageBitmap(h);if(r()){g.close();return}const y=n.width||g.width||960,w=n.height||g.height||540;(t.width!==y||t.height!==w)&&(t.width=y,t.height=w);const b=t.getContext("2d");if(b){const S=performance.now();b.clearRect(0,0,y,w),b.drawImage(g,0,0,y,w);const k=performance.now(),A=kv(t,y,w);s?.(n,{deviceId:n.deviceId,frameSeq:n.frameSeq,mode:n.frameMode||n.mode||n.codec||n.mimeType,width:y,height:w,byteLength:n.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,k-S),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:al.h264DecodeAcceleration,decoderLabel:"image",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:A.visualHash,visualChanged:A.visualChanged,paintedAt:k})}g.close()}function F1(t){queueMicrotask(t)}function B1(t){return t?(t.width=0,t.height=0,!0):!1}function Th(t,n){if(!t)return!1;try{n?.(t)}finally{B1(t)}return!0}function Yv(t,n){if(!t||!n)return 0;const r=Math.max(0,Number(t.get(n)||0))+1;return t.set(n,r),r}function H1(t,n){if(!t||!n)return 0;const r=Number(t.get(n)||0);return Number.isSafeInteger(r)&&r>0?r:Yv(t,n)}function dw(t,n){return Yv(t,n)}function fw(t,n,r){return!!t&&!!n&&Number(r)>0&&Number(t.get(n)||0)===Number(r)}function z1(t,n,r){if(!t||!t.has(n))return!1;const s=t.get(n);return t.delete(n),Th(s,r)}function $1(t,n,r){const s=new Set;for(const l of t||[])if(l){for(const u of l.values())u&&s.add(u);l.clear()}for(const l of n||[])l&&s.add(l);for(const l of s)Th(l,r);return s.size}function U1(t,{isCurrent:n,dispose:r,schedule:s=F1}){return!t||typeof n!="function"?!1:(s(()=>{n(t)||Th(t,r)}),!0)}const q1=new Uint8Array(0);function du(t){if(!t||typeof t!="object")return t;const n=t.payload;return n instanceof Uint8Array&&n.byteLength===0?t:{...t,payload:q1}}function W1(t,n){const r=du(n);return t.set(n.deviceId,r),r}function G1(t,n){for(const[r,s]of n.entries())t.set(r,du(s));return n.clear(),new Map(t)}const V1=1500;function K1(t={}){const n=Math.max(10,Math.min(1e4,Number(t.closeDeadlineMs)||V1)),r=typeof t.setTimeout=="function"?t.setTimeout:setTimeout,s=typeof t.clearTimeout=="function"?t.clearTimeout:clearTimeout,l=new Set,u=new WeakMap;let f=0,h=0;const g=(y,w)=>{if(!y||y.settled)return!1;y.settled=!0,y.timer!==null&&(s(y.timer),y.timer=null);try{y.socket.removeEventListener?.("close",y.handleClose)}catch{}return l.delete(y),u.delete(y.entry),w&&(f+=1),!0};return Object.freeze({beginClosing(y,w="livedesk-frame-socket-release"){if(!y?.socket||u.has(y))return!1;const b=y.socket;if(Number(b.readyState)===3)return!1;const S={entry:y,socket:b,timer:null,settled:!1,handleClose:null};S.handleClose=()=>g(S,!1),u.set(y,S),l.add(S),h=Math.max(h,l.size);try{b.addEventListener?.("close",S.handleClose)}catch{}S.timer=r(()=>{if(!S.settled){try{b.close()}catch{}g(S,Number(b.readyState)!==3)}},n);try{Number(b.readyState)===0||Number(b.readyState)===1?b.close(1e3,w):b.close()}catch{try{b.close()}catch{}}return Number(b.readyState)===3&&g(S,!1),!0},snapshot(){return{closingSocketCount:l.size,closingSocketTimerCount:[...l].filter(y=>y.timer!==null).length,closingSocketTimeoutCount:f,maximumClosingSocketCount:h}}})}function Q1(t,n="livedesk-frame-socket-release",r=null){if(!t)return 0;const s=[t],l=new Set;let u=0;for(;s.length>0;){const f=s.pop();if(!f||l.has(f))continue;l.add(f);const h=f.handoffFrom;f.handoffFrom=void 0,h&&!l.has(h)&&s.push(h);const g=f.disposed===!0;f.disposed=!0,f.handoffCompleted=!0;const y=f.detachListeners;f.detachListeners=void 0;try{y?.()}catch{}const w=f.releaseOwnedState;f.releaseOwnedState=void 0;try{w?.()}catch{}if(!g){if(r?.beginClosing)r.beginClosing(f,n);else try{f.socket.readyState===0||f.socket.readyState===1?f.socket.close(1e3,n):f.socket.close()}catch{try{f.socket.close()}catch{}}u+=1}}return u}const mw=Object.freeze(["nativeCaptureTelemetryAvailable","nativeCaptureTelemetryVersion","nativeEncoderHardwareAccelerationKnown","nativeEncoderHardwareAccelerated","nativeEncoderHardwareQueryStatus","nativeCaptureDisplayId","nativeCaptureFps","nativeCompressionFps","nativeEncodedFps","nativeCaptureSampleCount","nativeEncodableFrameCount","nativeSkippedFrameCount","nativeCompressionOutputCount","nativeEncodedFrameCount","nativeEncodeFramesInFlight","nativeEncodePendingFrameCount","nativeEncodeTimestampOwnerCount","nativeEncodeTimestampOwnerHighWatermark","nativeBackpressureCoalescedFrameCount","nativeBackpressureSkippedFrameCount","nativeEncodePendingReplacedFrameCount","nativeIdleSkippedFrameCount","nativeVideoToolboxActiveSessionCount","nativeVideoToolboxSessionHighWatermark","nativeOutputQueueDepth","nativeOutputQueueBytes","nativeOutputQueueOldestAgeMs","nativeOutputQueueHighWatermark","nativeOutputQueueDroppedCount","nativeOutputQueueAwaitingKeyFrame","nativeCopyTelemetryAvailable","nativeAnnexBAccessUnitAllocationCount","nativeAnnexBPayloadCopyCount","nativeAnnexBPayloadCopiedBytes","nativeAndPipeResidenceAgeMs","pipePayloadAllocationCount","pipePayloadCopyCount","pipePayloadCopiedBytes","handoffDroppedFrameCount","handoffRecoveryKeyFrameRequestCount","handoffOldestFrameAgeMs","nativeCaptureResourceTelemetryAvailable","nativeCaptureTelemetryAt"]),Y1=Object.freeze(["nativeEncodeFramesInFlight","nativeEncodePendingFrameCount","nativeEncodeTimestampOwnerCount","nativeEncodeTimestampOwnerHighWatermark","nativeBackpressureCoalescedFrameCount","nativeBackpressureSkippedFrameCount","nativeEncodePendingReplacedFrameCount","nativeIdleSkippedFrameCount","nativeVideoToolboxActiveSessionCount","nativeVideoToolboxSessionHighWatermark","nativeOutputQueueDepth","nativeOutputQueueBytes","nativeOutputQueueOldestAgeMs","nativeOutputQueueHighWatermark","nativeOutputQueueDroppedCount","nativeOutputQueueAwaitingKeyFrame","nativeCopyTelemetryAvailable","nativeAnnexBAccessUnitAllocationCount","nativeAnnexBPayloadCopyCount","nativeAnnexBPayloadCopiedBytes","nativeAndPipeResidenceAgeMs","pipePayloadAllocationCount","pipePayloadCopyCount","pipePayloadCopiedBytes","handoffDroppedFrameCount","handoffRecoveryKeyFrameRequestCount","handoffOldestFrameAgeMs"]);function X1(t){return[String(t?.deviceId||""),String(t?.sessionId||""),String(t?.streamId||""),String(t?.commandId||""),String(Number(t?.captureGeneration||0)||0),String(Number.isFinite(Number(t?.monitorIndex))?Number(t.monitorIndex):-1),String(t?.streamPurpose||"")].join("\0")}function Z1(t,n){return!!n&&String(t?.deviceId||"")===String(n.deviceId||"")&&String(t?.sessionId||"")===String(n.sessionId||"")&&String(t?.streamId||"")===String(n.streamId||"")&&String(t?.commandId||"")===String(n.commandId||"")&&(Number(t?.captureGeneration||0)||0)===(Number(n.captureGeneration||0)||0)&&(Number.isFinite(Number(t?.monitorIndex))?Number(t.monitorIndex):-1)===(Number.isFinite(Number(n.monitorIndex))?Number(n.monitorIndex):-1)&&String(t?.streamPurpose||"")===String(n.streamPurpose||"")}function J1(){return{ownerKey:"",values:Object.create(null)}}function pw(t){t&&(t.ownerKey="",t.values=Object.create(null))}function eT(t,n,r){if(!t||!n||!Z1(t,r))return!1;const s=X1(r);if(n.ownerKey!==s&&(n.ownerKey=s,n.values=Object.create(null)),t.nativeCaptureTelemetryAvailable===!1){for(const l of mw)l!=="nativeCaptureTelemetryAvailable"&&(delete n.values[l],delete t[l]);return n.values.nativeCaptureTelemetryAvailable=!1,!0}if(t.nativeCaptureResourceTelemetryAvailable===!1)for(const l of Y1)delete n.values[l],delete t[l];for(const l of mw)Object.prototype.hasOwnProperty.call(t,l)?n.values[l]=t[l]:Object.prototype.hasOwnProperty.call(n.values,l)&&(t[l]=n.values[l]);return!0}const gS=new ArrayBuffer(0);function tT(t){return`${String(t?.streamId||"")}:${Number(t?.frameSeq||0)}`}function nT(t){return!t||typeof t!="object"||t.payload instanceof ArrayBuffer&&t.payload.byteLength===0?t:{...t,payload:gS}}function aT(){let t=null,n="";return{accept(r){t=nT(r)},publish(){const r=t;if(t=null,!r)return null;const s=tT(r);return s===n?null:(n=s,r)},clear(){t=null,n=""},inspect(){return{pending:t?1:0,pendingPayloadBytes:Number(t?.payload?.byteLength||0),publishedKey:n}}}}const rT=0,sT=1,hw=3;function Nr(t){return Math.max(0,Math.floor(Number(t)||0))}function ki(t,n){return!n||n.active||n.socket!==null||n.audioContext!==null||n.statsTimer!==null||n.scheduledSourceCount!==0||n.pendingDecodeCount!==0||n.workletNodeCount!==0||n.workletPortCount!==0||n.pcmRingCapacityBytes!==0||n.pcmRingBufferedBytes!==0||n.pendingWorkletPacketCount!==0||n.pendingWorkletPacketBytes!==0||n.retainedFrameCount!==0||n.retainedPayloadBytes!==0?!1:t.delete(n)}function iT(){const t=new Set;let n=null;const r={ownerCount:0,socketCount:0,audioContextCount:0,workletNodeCount:0,workletPortCount:0},s=()=>{let l=0,u=0,f=0,h=0;for(const g of t){const y=Number(g.socket?.readyState);l+=g.socket&&y!==hw?1:0,u+=g.audioContext===null?0:1,f+=Nr(g.workletNodeCount),h+=Nr(g.workletPortCount)}r.ownerCount=Math.max(r.ownerCount,t.size),r.socketCount=Math.max(r.socketCount,l),r.audioContextCount=Math.max(r.audioContextCount,u),r.workletNodeCount=Math.max(r.workletNodeCount,f),r.workletPortCount=Math.max(r.workletPortCount,h)};return{createOwner({deviceId:l,socket:u,audioContext:f,statsTimer:h=null}){n=null;const g={deviceId:String(l||""),active:!0,socket:u||null,audioContext:f||null,statsTimer:h,scheduledSourceCount:0,pendingDecodeCount:0,workletNodeCount:0,workletPortCount:0,workletNodeCreateCount:0,pcmRingCapacityBytes:0,pcmRingBufferedBytes:0,pendingWorkletPacketCount:0,pendingWorkletPacketBytes:0,pendingWorkletPacketHighWater:0,pendingWorkletByteHighWater:0,retainedFrameCount:0,retainedPayloadBytes:0};return t.add(g),s(),g},recordTerminalFailure(l,u,f="playback"){return t.has(l)?(n={deviceId:l.deviceId,phase:String(f||"playback").slice(0,64),message:String(u||"Remote audio playback failed.").slice(0,512)},!0):!1},deactivate(l){return t.has(l)?(l.active=!1,ki(t,l)):!1},setSocket(l,u){return t.has(l)?(l.socket=u||null,s(),ki(t,l)):!1},setAudioContext(l,u){return t.has(l)?(l.audioContext=u||null,s(),ki(t,l)):!1},setStatsTimer(l,u){return t.has(l)?(l.statsTimer=u??null,ki(t,l)):!1},setScheduledSourceCount(l,u){return t.has(l)?(l.scheduledSourceCount=Nr(u),ki(t,l)):!1},setPendingDecodeCount(l,u){return t.has(l)?(l.pendingDecodeCount=Nr(u),ki(t,l)):!1},setWorkletNode(l,u,f,h=l?.workletNodeCreateCount){return t.has(l)?(l.workletNodeCount=Nr(u),l.workletPortCount=Nr(f),l.workletNodeCreateCount=Nr(h),s(),ki(t,l)):!1},setPcmRing(l,u,f){return t.has(l)?(l.pcmRingCapacityBytes=Nr(u),l.pcmRingBufferedBytes=Math.min(l.pcmRingCapacityBytes,Nr(f)),ki(t,l)):!1},setPendingWorkletPackets(l,u,f,h=l?.pendingWorkletPacketHighWater,g=l?.pendingWorkletByteHighWater){return t.has(l)?(l.pendingWorkletPacketCount=Nr(u),l.pendingWorkletPacketBytes=Nr(f),l.pendingWorkletPacketHighWater=Math.max(l.pendingWorkletPacketHighWater,Nr(h)),l.pendingWorkletByteHighWater=Math.max(l.pendingWorkletByteHighWater,Nr(g)),ki(t,l)):!1},setRetainedFrame(l,u,f=0){return t.has(l)?(l.retainedFrameCount=Nr(u),l.retainedPayloadBytes=Nr(f),ki(t,l)):!1},releaseIfDrained(l){return ki(t,l)},hasOwner(l){return t.has(l)},snapshot(){const l=[...t].map(f=>{const h=Number(f.socket?.readyState),g=f.socket&&h!==hw?1:0;return{deviceId:f.deviceId,active:f.active,socketCount:g,openSocketCount:h===sT?1:0,connectingSocketCount:h===rT?1:0,audioContextCount:f.audioContext===null?0:1,statsTimerCount:f.statsTimer===null?0:1,scheduledSourceCount:f.scheduledSourceCount,pendingDecodeCount:f.pendingDecodeCount,workletNodeCount:f.workletNodeCount,workletPortCount:f.workletPortCount,workletNodeCreateCount:f.workletNodeCreateCount,pcmRingCapacityBytes:f.pcmRingCapacityBytes,pcmRingBufferedBytes:f.pcmRingBufferedBytes,pendingWorkletPacketCount:f.pendingWorkletPacketCount,pendingWorkletPacketBytes:f.pendingWorkletPacketBytes,pendingWorkletPacketHighWater:f.pendingWorkletPacketHighWater,pendingWorkletByteHighWater:f.pendingWorkletByteHighWater,retainedFrameCount:f.retainedFrameCount,retainedPayloadBytes:f.retainedPayloadBytes}}),u=f=>l.reduce((h,g)=>h+Nr(g[f]),0);return{ownerCount:l.length,activeOwnerCount:l.filter(f=>f.active).length,socketCount:u("socketCount"),openSocketCount:u("openSocketCount"),connectingSocketCount:u("connectingSocketCount"),audioContextCount:u("audioContextCount"),statsTimerCount:u("statsTimerCount"),scheduledSourceCount:u("scheduledSourceCount"),pendingDecodeCount:u("pendingDecodeCount"),workletNodeCount:u("workletNodeCount"),workletPortCount:u("workletPortCount"),workletNodeCreateCount:u("workletNodeCreateCount"),pcmRingCapacityBytes:u("pcmRingCapacityBytes"),pcmRingBufferedBytes:u("pcmRingBufferedBytes"),pendingWorkletPacketCount:u("pendingWorkletPacketCount"),pendingWorkletPacketBytes:u("pendingWorkletPacketBytes"),pendingWorkletPacketHighWater:u("pendingWorkletPacketHighWater"),pendingWorkletByteHighWater:u("pendingWorkletByteHighWater"),retainedFrameCount:u("retainedFrameCount"),retainedPayloadBytes:u("retainedPayloadBytes"),ownerHighWater:r.ownerCount,socketHighWater:r.socketCount,audioContextHighWater:r.audioContextCount,workletNodeHighWater:r.workletNodeCount,workletPortHighWater:r.workletPortCount,lastTerminalFailure:n,owners:l}}}}const Na=iT();function oT(){let t=Promise.resolve(),n=0,r=0,s=0;return{acquire(l){const u=++s;let f=!1,h=!1,g=!1,y;const w=new Promise(A=>{y=A}),b=Promise.resolve(t).catch(()=>{});t=b.then(()=>w);const S=()=>g?!1:(g=!0,f&&(n=Math.max(0,n-1)),y(),!0),k=b.then(async()=>{if(h||g)return S(),null;f=!0,n+=1,r=Math.max(r,n);try{return await l({ownerId:u,release:S})}catch(A){throw S(),A}});return{ownerId:u,ready:k,release:S,cancel(){h=!0,f||S()}}},snapshot(){return{activeOwnerCount:n,ownerHighWater:r,nextOwnerId:s}}}}const lT=oT(),gw=1e3;function cT({enabled:t,now:n,lastPublishedAt:r,intervalMs:s=gw}){if(!t)return!1;const l=Math.max(0,Number(n)||0),u=Math.max(0,Number(r)||0),f=Math.max(1,Number(s)||gw);return u<=0||l-u>=f}const vS="livedesk-remote-audio-v1",uT=250,dT=160,Mv=4;function fT(t){const n=String(t||"").toLowerCase();return n.includes("audio/pcm")||n.includes("f32le")||n.includes("s16le")}function Av(t={},n={}){const r=String(n.deviceId||""),s=String(n.streamId||"");return!!r&&!!s&&String(t.deviceId||"")===r&&String(t.streamId||"")===s}function mT(t={},n={}){if(!Av(t,n))return{accepted:!1,reason:"owner-mismatch",nextFrameSeq:Math.max(0,Math.floor(Number(n.lastFrameSeq)||0))};const r=Math.max(0,Math.floor(Number(t.frameSeq)||0)),s=Math.max(0,Math.floor(Number(n.lastFrameSeq)||0));return r>0&&r<=s?{accepted:!1,reason:"sequence-not-newer",nextFrameSeq:s}:{accepted:!0,reason:"",nextFrameSeq:r}}function pT(t={}){const n=String(t.capturePhase||"").toLowerCase(),r=String(t.backendKind||"").toLowerCase(),s=t.captureAlive===!0?!0:t.captureAlive===!1?!1:null,l=t.helperAlive===!0?!0:t.helperAlive===!1?!1:null,u=Math.max(0,Math.floor(Number(t.helperPid)||0)),f=r==="windows-wasapi-in-process",h=r==="macos-screencapturekit-helper"||r==="linux-system-audio-helper",g=f||h,y=t.helperRequired===!0?!0:t.helperRequired===!1?!1:h?!0:f?!1:null,w=y===!1?!0:y===!0?l===!0&&u>0:!1,b=n==="starting"||n==="capture-active-awaiting-current-pcm",S=n==="active"&&s===!0&&g&&w,k=n==="failed"||n==="stopped"||s===!1||n==="active"&&(!g||!w);let A="";return b?A="awaiting-current-pcm":!f&&!h?A="backend-unknown":n!=="active"?A=n?`phase-${n}`:"phase-unknown":s!==!0?A="capture-not-alive":y===!0&&l!==!0?A="external-helper-not-alive":y===!0&&u<=0&&(A="external-helper-pid-missing"),{capturePhase:n,backendKind:r,captureAlive:s,helperAlive:l,helperPid:u,helperRequired:y,inProcessBackend:f,externalHelperBackend:h,backendKnown:g,helperReady:w,awaitingCurrentPcm:b,healthy:S,failed:k,reason:A}}function fc(t,n){const r=Math.floor(Number(t));return Number.isFinite(r)&&r>0?r:n}function Xv(t={}){const n=Math.max(8e3,Math.min(192e3,fc(t.sampleRate,48e3))),r=Math.max(1,Math.min(8,fc(t.channels,2))),s=String(t.mimeType||"").toLowerCase(),u=String(t.sampleFormat||"").toLowerCase()==="s16le"||s.includes("s16le")||s.includes("audio/l16")?"s16le":"f32le";return{sampleRate:n,channels:r,sampleFormat:u}}function Zv(t={}){const n=Xv(t),r=Math.max(1,Math.min(250,fc(t.maxDurationMs,250))),s=Math.max(1,Math.ceil(n.sampleRate*r/1e3));return{...n,maxDurationMs:r,capacityFrames:s,capacityBytes:s*n.channels*Float32Array.BYTES_PER_ELEMENT}}function hT(t={}){const n=Zv(t),r=Math.max(0,Math.min(n.maxDurationMs,fc(t.targetLeadMs,160))),s=Math.min(n.capacityFrames,Math.max(1,Math.ceil(n.sampleRate*r/1e3)));let l=new Float32Array(n.capacityFrames*n.channels),u=0,f=0,h=0,g=0,y=!1,w=!1,b=0,S=0,k=0;const A={acceptedFrames:0,droppedFrames:0},T=()=>(k+=1,{sampleRate:n.sampleRate,channels:n.channels,sampleFormat:n.sampleFormat,maxDurationMs:n.maxDurationMs,targetLeadMs:r,capacityFrames:w?0:n.capacityFrames,capacityBytes:w?0:n.capacityBytes,bufferedFrames:w?0:h,bufferedBytes:w?0:h*n.channels*Float32Array.BYTES_PER_ELEMENT,bufferedMs:w?0:h*1e3/n.sampleRate,droppedFrames:b,underflowCount:S,started:!w&&y,disposed:w}),j=()=>{u=0,f=0,h=0,g=0,y=!1},I=()=>{w||(j(),l=new Float32Array(0),w=!0)},N=(F,$=0,D,K=n.sampleFormat)=>{if(A.acceptedFrames=0,A.droppedFrames=0,w||!(F instanceof ArrayBuffer))return A;const z=Math.max(0,Math.floor(Number($)||0)),q=Math.max(0,F.byteLength-z),W=Math.min(q,Math.max(0,Math.floor(Number(D??q)||0))),Y=K==="s16le",V=Y?2:4,he=V*n.channels,ee=Math.floor(W/he);if(ee<=0)return A;const U=Math.min(ee,n.capacityFrames),L=ee-U,le=Math.max(0,h+U-n.capacityFrames);le>0&&(u=(u+le)%n.capacityFrames,h-=le);const ve=L+le;b+=ve;const J=new DataView(F,z,W);for(let Ae=L;Ae<ee;Ae+=1){const ce=f*n.channels,Te=Ae*n.channels;for(let Fe=0;Fe<n.channels;Fe+=1){const Ze=(Te+Fe)*V,de=Y?J.getInt16(Ze,!0)/32768:J.getFloat32(Ze,!0);l[ce+Fe]=Number.isFinite(de)?Math.max(-1,Math.min(1,de)):0}f=(f+1)%n.capacityFrames}return h+=U,!y&&h>=s&&(y=!0),A.acceptedFrames=U,A.droppedFrames=ve,A};return{writePcm:(F={})=>N(F.buffer,F.byteOffset,F.byteLength,F.sampleFormat),writePcmBuffer:N,readToChannels:(F,$=n.sampleRate)=>{if(!Array.isArray(F)||F.length===0)return;let D=Number.POSITIVE_INFINITY;for(let q=0;q<F.length;q+=1){const W=F[q];D=Math.min(D,W?.length||0)}if(w||!Number.isFinite(D)||D<=0||!y){for(let q=0;q<F.length;q+=1)F[q]?.fill?.(0);return}const K=Math.max(8e3,Math.min(192e3,fc($,n.sampleRate))),z=n.sampleRate/K;for(let q=0;q<D;q+=1){if(h<=0){y=!1,S+=1,g=0;for(let V=0;V<F.length;V+=1)F[V].fill(0,q);break}const W=u*n.channels;for(let V=0;V<F.length;V+=1){const he=Math.min(V,n.channels-1);F[V][q]=l[W+he]}g+=z;const Y=Math.min(h,Math.floor(g));Y>0&&(u=(u+Y)%n.capacityFrames,h-=Y,g-=Y)}},flush:j,dispose:I,snapshot:T,getSnapshotCount:()=>k}}function gT(t={}){const n=Math.max(1,Math.min(Mv,fc(t.maxPendingPackets,Mv))),r=Math.max(1,fc(t.maxPendingBytes,1)),s=new Map;let l=0,u=0,f=0,h=0,g=0,y=!1;const w=()=>({terminal:y,maxPendingPackets:n,maxPendingBytes:r,pendingPacketCount:s.size,pendingPacketBytes:l,pendingPacketHighWater:u,pendingByteHighWater:f,acceptedCount:h,droppedCount:g});return{claim(b,S){const k=typeof b=="number"&&Number.isFinite(b)?b:String(b||""),A=Math.max(0,Math.floor(Number(S)||0));return y||!k||A<=0||s.has(k)||s.size>=n||l+A>r?(g+=1,!1):(s.set(k,A),l+=A,u=Math.max(u,s.size),f=Math.max(f,l),h+=1,!0)},acknowledge(b){const S=typeof b=="number"&&Number.isFinite(b)?b:String(b||""),k=s.get(S);return k===void 0?!1:(s.delete(S),l=Math.max(0,l-k),!0)},terminate(){return s.clear(),l=0,y=!0,w()},getPendingPacketCount:()=>s.size,getPendingPacketBytes:()=>l,getPendingPacketHighWater:()=>u,getPendingByteHighWater:()=>f,snapshot:w}}function Nh(t,n){const r=String(t?.name||"");if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(r)||!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(n))throw new Error("Remote Audio worklet function binding name is invalid.");const s=`const ${r} = ${Function.prototype.toString.call(t)};`;return r===n?s:`${s}
16
- const ${n} = ${r};`}const vT=Nh(fc,"positiveInteger"),yT=Nh(Xv,"normalizeRemoteAudioPcmFormat"),bT=Nh(Zv,"remoteAudioPcmRingCapacity"),wT=Nh(hT,"createRemoteAudioPcmRing"),xT=`
17
- const REMOTE_AUDIO_PCM_RING_MAX_MS = ${uT};
18
- const REMOTE_AUDIO_PCM_TARGET_LEAD_MS = ${dT};
19
- ${vT}
20
- ${yT}
21
- ${bT}
22
- ${wT}
23
-
24
- class LiveDeskRemoteAudioProcessor extends AudioWorkletProcessor {
25
- constructor() {
26
- super();
27
- this.ring = null;
28
- this.ringSampleRate = 0;
29
- this.ringChannels = 0;
30
- this.ringSampleFormat = '';
31
- this.disposed = false;
32
- this.reportFrames = 0;
33
- this.port.onmessage = event => this.handleMessage(event?.data || {});
34
- }
35
-
36
- postRingState(type, extra = {}) {
37
- const ringState = this.ring?.snapshot?.() || {
38
- capacityBytes: 0,
39
- bufferedBytes: 0,
40
- bufferedMs: 0,
41
- droppedFrames: 0,
42
- underflowCount: 0
43
- };
44
- this.port.postMessage({
45
- type,
46
- ...extra,
47
- ringCapacityBytes: Number(ringState.capacityBytes || 0),
48
- ringBufferedBytes: Number(ringState.bufferedBytes || 0),
49
- ringBufferedMs: Number(ringState.bufferedMs || 0),
50
- ringDroppedFrames: Number(ringState.droppedFrames || 0),
51
- ringUnderflowCount: Number(ringState.underflowCount || 0)
52
- });
53
- }
54
-
55
- handleMessage(message) {
56
- const type = String(message.type || '');
57
- if (type === 'dispose') {
58
- this.disposed = true;
59
- this.ring?.dispose?.();
60
- this.ring = null;
61
- this.ringSampleRate = 0;
62
- this.ringChannels = 0;
63
- this.ringSampleFormat = '';
64
- this.postRingState('disposed');
65
- return;
66
- }
67
- if (this.disposed) {
68
- if (type === 'pcm') {
69
- this.port.postMessage({
70
- type: 'packet-terminal',
71
- packetId: message.packetId ?? 0,
72
- acceptedFrames: 0,
73
- droppedFrames: 0
74
- });
75
- }
76
- return;
77
- }
78
- if (type === 'flush') {
79
- this.ring?.flush?.();
80
- this.postRingState('ring-state');
81
- return;
82
- }
83
- if (type !== 'pcm') {
84
- return;
85
- }
86
-
87
- try {
88
- const sourceSampleRate = Math.max(
89
- 8_000,
90
- Math.min(192_000, positiveInteger(message.sampleRate, 48_000))
91
- );
92
- const sourceChannels = Math.max(
93
- 1,
94
- Math.min(8, positiveInteger(message.channels, 2))
95
- );
96
- const sourceSampleFormat =
97
- message.sampleFormat === 's16le' ? 's16le' : 'f32le';
98
- const ringCreated = !this.ring
99
- || this.ringSampleRate !== sourceSampleRate
100
- || this.ringChannels !== sourceChannels
101
- || this.ringSampleFormat !== sourceSampleFormat;
102
- if (ringCreated) {
103
- this.ring?.dispose?.();
104
- this.ring = createRemoteAudioPcmRing({
105
- sampleRate: sourceSampleRate,
106
- channels: sourceChannels,
107
- sampleFormat: sourceSampleFormat,
108
- maxDurationMs: REMOTE_AUDIO_PCM_RING_MAX_MS,
109
- targetLeadMs: REMOTE_AUDIO_PCM_TARGET_LEAD_MS
110
- });
111
- this.ringSampleRate = sourceSampleRate;
112
- this.ringChannels = sourceChannels;
113
- this.ringSampleFormat = sourceSampleFormat;
114
- this.postRingState('ring-configured');
115
- }
116
- const result = this.ring.writePcmBuffer(
117
- message.buffer,
118
- message.byteOffset,
119
- message.byteLength,
120
- sourceSampleFormat
121
- );
122
- this.port.postMessage({
123
- type: 'packet-terminal',
124
- packetId: message.packetId ?? 0,
125
- acceptedFrames: Number(result.acceptedFrames || 0),
126
- droppedFrames: Number(result.droppedFrames || 0)
127
- });
128
- } catch (error) {
129
- this.port.postMessage({
130
- type: 'processor-error',
131
- packetId: message.packetId ?? 0,
132
- error: error instanceof Error ? error.message : String(error)
133
- });
134
- }
135
- }
136
-
137
- process(_inputs, outputs) {
138
- try {
139
- if (this.disposed) {
140
- return false;
141
- }
142
- const output = outputs && outputs.length > 0 ? outputs[0] : null;
143
- if (!output) {
144
- return true;
145
- }
146
- const outputFrames = output.length > 0 ? output[0].length : 0;
147
- if (this.ring) {
148
- this.ring.readToChannels(output, sampleRate);
149
- } else {
150
- for (let channelIndex = 0; channelIndex < output.length; channelIndex += 1) {
151
- output[channelIndex].fill(0);
152
- }
153
- }
154
- this.reportFrames += outputFrames;
155
- if (this.reportFrames >= Math.max(1, Math.floor(sampleRate / 4))) {
156
- this.reportFrames = 0;
157
- this.postRingState('ring-state');
158
- }
159
- return true;
160
- } catch (error) {
161
- this.disposed = true;
162
- this.port.postMessage({
163
- type: 'processor-error',
164
- packetId: 0,
165
- error: error instanceof Error ? error.message : String(error)
166
- });
167
- return false;
168
- }
169
- }
170
- }
171
-
172
- registerProcessor(
173
- '${vS}',
174
- LiveDeskRemoteAudioProcessor
175
- );
176
- `;function ST({eligibleCandidates:t,fallbackHubBaseUrl:n,publicConsole:r,authenticated:s}){const l=[...new Set((Array.isArray(t)?t:[]).map(f=>String(f||"").trim()).filter(Boolean))];if(l.length>0)return Object.freeze({candidates:Object.freeze(l),transport:"auto",reason:"direct-candidate"});const u=String(n||"").trim();return Object.freeze(r&&s&&u?{candidates:Object.freeze([u]),transport:"relay",reason:"authenticated-public-console-fallback"}:{candidates:Object.freeze([]),transport:"auto",reason:"unavailable"})}const vw="livedesk_remote_host_targets",CT="livedesk_entitlements",yw=4e3,kT=2500,Jv=new TextDecoder,Tv=new Set;function MT(){const t=[...Tv].map(r=>r()),n=r=>t.reduce((s,l)=>s+Number(l[r]||0),0);return{ownerCount:t.length,activeOwnerCount:t.filter(r=>r.active).length,socketCount:n("socketCount"),openSocketCount:n("openSocketCount"),connectingSocketCount:n("connectingSocketCount"),closingSocketCount:n("closingSocketCount"),closingSocketTimerCount:n("closingSocketTimerCount"),closingSocketTimeoutCount:n("closingSocketTimeoutCount"),expectedBindingCount:n("expectedBindingCount"),reconnectTimerCount:n("reconnectTimerCount"),statsTimerCount:n("statsTimerCount"),configurationRefreshTimerCount:n("configurationRefreshTimerCount"),restartTokenCount:n("restartTokenCount"),retainedFrameCount:n("retainedFrameCount"),retainedPayloadBytes:n("retainedPayloadBytes"),owners:t}}function AT(){return Na.snapshot()}function TT(t){const r=(Array.isArray(t)?t:[t||Vn]).map(s=>Su(s||Vn));return[...new Set(r.filter(Boolean))]}function NT(){const[t,n]=d.useState(null),[r,s]=d.useState(!0),l=d.useRef(null);return d.useEffect(()=>{let u=!0,f=0;const h=async(S=!1)=>{try{const k=await(window.liveDesk?.auth?.getSession?.()||zt.auth.getSession());if(!u)return;const A=R0(k);(S||A)&&n(A)}finally{u&&s(!1)}},g=()=>{if(document.visibilityState==="hidden")return;const S=Date.now();S-f<1e3||(f=S,yu(l,()=>h(!1)).catch(()=>{}))},y=window.liveDesk?.auth?.onComplete?.(S=>{S.ok&&S.session?zt.auth.setSession(S.session):S.ok&&S.signedOut&&(n(null),s(!1),zt.auth.signOut({scope:"local"}).catch(()=>{}))});h(!0).catch(()=>{});const{data:{subscription:w}}=zt.auth.onAuthStateChange((S,k)=>{if(!k&&window.liveDesk?.auth){s(!1);return}n(k),s(!1),k&&window.liveDesk?.auth?.persistSession?.(k)}),b=()=>g();return window.addEventListener("pageshow",g),window.addEventListener("online",g),window.addEventListener("focus",g),document.addEventListener("visibilitychange",b),()=>{u=!1,y?.(),w.unsubscribe(),window.removeEventListener("pageshow",g),window.removeEventListener("online",g),window.removeEventListener("focus",g),document.removeEventListener("visibilitychange",b)}},[]),{session:t,loading:r}}function RT(t,n=!0,r=""){const[s,l]=d.useState(null),[u,f]=d.useState([]),[h,g]=d.useState(""),[y,w]=d.useState(""),b=d.useRef(new Map),S=d.useRef(null),k=Array.isArray(t)?t.join(`
177
- `):String(t||""),A=d.useMemo(()=>TT(t),[k]),T=d.useMemo(()=>A.find(N=>om(N)==="loopback")||A[0]||Vn,[A]),j=d.useCallback(async N=>{if(!n){l(null),f([]),w(""),g("");return}let P=null;const H=Date.now(),F=A.filter(D=>(b.current.get(D)||0)<=H),$=ST({eligibleCandidates:F,fallbackHubBaseUrl:T,publicConsole:ih(),authenticated:!!r});if($.candidates.length===0)throw new Error("No LiveDesk Hub endpoint is reachable. Retrying shortly.");for(const D of $.candidates)try{const[K,z]=await Promise.all([lt("/api/remote/status",{signal:N,timeoutMs:yw,transport:$.transport},D),lt("/api/remote/devices",{signal:N,timeoutMs:yw,transport:$.transport},D)]);if(N?.aborted)throw N.reason||new Error("LiveDesk Hub snapshot cancelled.");if(!Array.isArray(z.devices))throw new Error("Invalid Hub devices response.");b.current.delete(D),l(K),f(z.devices),w(D),g("");return}catch(K){if(N?.aborted)throw K;P=K,$.transport==="auto"&&b.current.set(D,Date.now()+1e4)}throw w(""),P||new Error("No LiveDesk Hub endpoint is reachable.")},[r,n,T,A]),I=d.useCallback(()=>{b.current.clear(),yu(S,()=>j()).catch(N=>{g(N instanceof Error?N.message:String(N))})},[j]);return d.useEffect(()=>{if(b.current.clear(),!n){l(null),f([]),w(""),g("");return}let N=!0,P=null;const H=new AbortController,F=()=>{yu(S,()=>j(H.signal)).catch(D=>{N&&!H.signal.aborted&&g(D instanceof Error?D.message:String(D))}).finally(()=>{N&&!H.signal.aborted&&(P=window.setTimeout(F,kT))})};return F(),()=>{N=!1,H.abort(new Error("LiveDesk Hub snapshot polling stopped.")),P!==null&&window.clearTimeout(P)}},[n,j]),d.useEffect(()=>{if(!n)return;let N=0;const P=()=>{if(document.visibilityState==="hidden")return;const F=Date.now();F-N<1e3||(N=F,b.current.clear(),ih()&&gA(),I())},H=()=>P();return window.addEventListener("pageshow",P),window.addEventListener("online",P),window.addEventListener("focus",P),document.addEventListener("visibilitychange",H),()=>{window.removeEventListener("pageshow",P),window.removeEventListener("online",P),window.removeEventListener("focus",P),document.removeEventListener("visibilitychange",H)}},[n,I]),{status:s,devices:u,error:h,refresh:I,hubBaseUrl:y||T,hubCandidates:A}}function ET(t){const[n,r]=d.useState(null),[s,l]=d.useState(""),u=t?.user?.id||"",f=d.useRef(null),h=d.useCallback(async()=>{if(!u){r(null);return}const{data:g,error:y}=await zt.from(vw).select("*").eq("user_id",u).maybeSingle();if(y){l(y.message);return}r(g),l("")},[u]);return d.useEffect(()=>{yu(f,h).catch(()=>{})},[h]),d.useEffect(()=>{if(!u)return;let g=0;const y=()=>{if(document.visibilityState==="hidden")return;const b=Date.now();b-g<1e3||(g=b,yu(f,h).catch(()=>{}))},w=()=>y();return window.addEventListener("pageshow",y),window.addEventListener("online",y),window.addEventListener("focus",y),document.addEventListener("visibilitychange",w),()=>{window.removeEventListener("pageshow",y),window.removeEventListener("online",y),window.removeEventListener("focus",y),document.removeEventListener("visibilitychange",w)}},[h,u]),d.useEffect(()=>{if(!u)return;const g=zt.channel(`livedesk-remote-host-targets-${u.replace(/[^a-zA-Z0-9]/g,"")}`).on("postgres_changes",{event:"*",schema:"public",table:vw,filter:`user_id=eq.${u}`},y=>r(y.new)).subscribe();return()=>{zt.removeChannel(g)}},[u]),{target:n,error:s,refresh:h}}function jT(t){const[n,r]=d.useState(null),[s,l]=d.useState(!1),[u,f]=d.useState(""),h=t?.user?.id||"",g=d.useCallback(async()=>{if(!h){r(null),f(""),l(!1);return}l(!0);const{data:w,error:b}=await zt.from(CT).select("*").eq("user_id",h).eq("product_key","livedesk").maybeSingle();if(b){f(b.message),l(!1);return}r(w),f(""),l(!1)},[h]);d.useEffect(()=>{g()},[g]);const y=d.useMemo(()=>!n||n.status!=="active"?!1:n.expires_at?new Date(n.expires_at).getTime()>Date.now():!0,[n]);return{entitlement:n,licensed:y,loading:s,error:u,refresh:g}}const cm={totalFrames:0,totalBytes:0,framesPerSecond:0,bytesPerSecond:0,sampleMs:0,lastUpdatedAt:0},DT=2500,IT=3e4,LT=64*1024,PT=64*1024,_T=6,OT=_T,yS=new Map;function FT(t){return yS.get(t)}const bw={totalSent:0,totalDropped:0,sentPerSecond:0,droppedPerSecond:0,bufferedAmount:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0,lastUpdatedAt:0};function BT(t,n,r){const s=Number(n);if(!Number.isFinite(s)||s<=0)return 0;const l=r-s,u=t.minimumHubClockOffsetMs;if(!Number.isFinite(u)||l<Number(u))return t.minimumHubClockOffsetMs=l,0;const f=Math.max(0,l-Number(u));return f>IT?(t.minimumHubClockOffsetMs=l,0):f}function bt(t){if(t==null||t==="")return;const n=Number(t);return Number.isFinite(n)?n:void 0}const HT=["nativeEncodeFramesInFlight","nativeEncodePendingFrameCount","nativeEncodeTimestampOwnerCount","nativeEncodeTimestampOwnerHighWatermark","nativeBackpressureCoalescedFrameCount","nativeBackpressureSkippedFrameCount","nativeEncodePendingReplacedFrameCount","nativeIdleSkippedFrameCount","nativeVideoToolboxActiveSessionCount","nativeVideoToolboxSessionHighWatermark","nativeOutputQueueDepth","nativeOutputQueueBytes","nativeOutputQueueOldestAgeMs","nativeOutputQueueHighWatermark","nativeOutputQueueDroppedCount","nativeAnnexBAccessUnitAllocationCount","nativeAnnexBPayloadCopyCount","nativeAnnexBPayloadCopiedBytes","nativeAndPipeResidenceAgeMs","pipePayloadAllocationCount","pipePayloadCopyCount","pipePayloadCopiedBytes","handoffDroppedFrameCount","handoffRecoveryKeyFrameRequestCount","handoffOldestFrameAgeMs"];function zT(t){return Number(t.nativeCaptureTelemetryVersion)>=5&&HT.every(n=>bt(t[n])!==void 0)&&typeof t.nativeOutputQueueAwaitingKeyFrame=="boolean"&&t.nativeCopyTelemetryAvailable===!0}function $T(t,n,r){if(!t||typeof t!="object")return null;const s=t,l=String(s.deviceId||n||"").trim(),u=String(s.sessionId||"").trim(),f=String(s.streamId||"").trim(),h=s.streamPurpose==="control"?"control":s.streamPurpose==="wall"?"wall":null,g=String(s.commandId||"").trim(),y=Number(s.captureGeneration||0),w=Number(s.monitorIndex??-1);return!l||l!==n||!h||h!==r||!u||!f||!g||!Number.isSafeInteger(y)||y<=0||!Number.isSafeInteger(w)||w<0?null:{deviceId:l,sessionId:u,streamId:f,streamPurpose:h,commandId:g,captureGeneration:y,monitorIndex:w}}function ww(t,n,r=Vn,s={}){const[l,u]=d.useState(new Map),[f,h]=d.useState("idle"),[g,y]=d.useState(""),[w,b]=d.useState(cm),S=d.useRef(new Map),k=d.useRef(new Map),A=d.useRef(new Map),T=d.useRef(null);T.current===null&&(T.current=K1());const j=d.useRef(0),I=d.useRef(new Map),N=d.useRef({enabled:!1,token:"",reason:""}),P=d.useRef(new Map),H=d.useRef(null),F=d.useRef(new Map),[$,D]=d.useState(0),K=d.useRef(s.onFrame),z=d.useRef(s.onStreamReady),q=d.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),W=d.useMemo(()=>[...t].sort().join(","),[t]),Y=n&&W.length>0,V=d.useRef(!1);d.useLayoutEffect(()=>(V.current=Y,()=>{V.current=!1}),[Y]);const he=Number.isFinite(s.fps)?Number(s.fps):2,ee=Number.isFinite(s.maxWidth)?Number(s.maxWidth):640,U=Number.isFinite(s.maxHeight)?Number(s.maxHeight):360,L=Number.isFinite(s.quality)?Number(s.quality):45,le=Number.isFinite(s.configurationRefreshMs)?Math.max(0,Math.round(Number(s.configurationRefreshMs))):0,ve=String(s.frameMode||s.mode||"mode3-h264-hw").trim()||"mode3-h264-hw",J=s.streamPurpose==="control"?"control":"wall",Ae=s.forceRestart===!0,ce=String(s.forceRestartToken||"").trim(),Te=String(s.restartReason||"").trim();N.current={enabled:Ae,token:ce,reason:Te};const Fe=d.useMemo(()=>{const Se=Object.entries(s.monitorSelections||{}).filter(([ge])=>!!ge).sort(([ge],[Ue])=>ge.localeCompare(Ue));return JSON.stringify(Object.fromEntries(Se))},[s.monitorSelections]),$e=d.useMemo(()=>{const Se=Object.entries(s.connectionSessionIds||{}).filter(([ge])=>!!ge).map(([ge,Ue])=>[ge,String(Ue||"").trim()]).sort(([ge],[Ue])=>ge.localeCompare(Ue));return JSON.stringify(Object.fromEntries(Se))},[s.connectionSessionIds]);d.useEffect(()=>{K.current=s.onFrame},[s.onFrame]),d.useEffect(()=>{z.current=s.onStreamReady},[s.onStreamReady]);const Ze=d.useCallback((Se,ge="livedesk-frame-socket-release")=>{Q1(Se,ge,T.current)},[]),de=d.useCallback(Se=>{const ge=P.current.get(Se);ge!==void 0&&(window.clearTimeout(ge),P.current.delete(Se))},[]),Be=d.useCallback(Se=>{const ge=F.current.get(Se);ge!==void 0&&(window.clearTimeout(ge),F.current.delete(Se))},[]),Ve=d.useCallback((Se,ge=!0)=>{for(const Ue of P.current.values())window.clearTimeout(Ue);P.current.clear();for(const Ue of F.current.values())window.clearTimeout(Ue);F.current.clear();for(const Ue of A.current.values())Ue.expectedBinding=void 0,Ze(Ue,Se);A.current.clear(),I.current.clear(),S.current=new Map,k.current.clear(),q.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0},ge&&(u(new Map),y(""),b(cm),h("idle"))},[Ze]),Je=d.useCallback(()=>{const Se=[...A.current.values()].map(ge=>ge.socket);if(Se.length===0){h("idle");return}if(Se.some(ge=>ge.readyState===WebSocket.OPEN)){h("open");return}if(Se.some(ge=>ge.readyState===WebSocket.CONNECTING)){h("connecting");return}h("closed")},[]),Qe=d.useCallback((Se,ge,Ue,Me)=>{if(ge.disposed||ge.socket.readyState!==WebSocket.OPEN)return!1;try{return ge.socket.send(JSON.stringify({...ge.payload,type:"restart-live",deviceIds:[Se],forceRestart:!0,restartReason:Ue,restartToken:Me})),ge.expectedBinding=void 0,pw(ge.sparseTelemetry),!0}catch{return!1}},[]),yt=d.useCallback((Se,ge)=>{if(ge.disposed||A.current.get(Se)!==ge||ge.socket.readyState!==WebSocket.OPEN)return!1;try{return ge.socket.send(JSON.stringify({...ge.payload,type:"refresh-live",deviceIds:[Se],forceRestart:!1,reuseExisting:!0,reason:"initial-configuration-settle"})),!0}catch{try{ge.socket.close(4003,"configuration-refresh-failed")}catch{}return!1}},[]),ne=d.useCallback((Se,ge)=>{if(!V.current||ge.disposed||!Se||Se.byteLength<5)return;const Ue=Date.now(),rt=new DataView(Se).getUint32(0,!1);if(rt<=0||rt+4>Se.byteLength)return;const At=new Uint8Array(Se,4,rt),O=JSON.parse(Jv.decode(At));eT(O,ge.sparseTelemetry,ge.expectedBinding);const qe=bt(O.hubPacketEpochMs),B=qe!==void 0&&qe>0?qe:void 0,Oe=BT(ge,B,Ue);if(Oe>DT)return;const We=new Uint8Array(Se,4+rt),et=bt(O.nativeCaptureTelemetryVersion),it=bt(O.nativeCaptureTelemetryAgeMs),ye=bt(O.hubClientDropped),Ne=bt(O.hubClientQueueDepth),He=bt(O.hubClientQueueLimit),pe=bt(O.hubClientBufferedBytes),ae=ye!==void 0&&Ne!==void 0&&He!==void 0&&pe!==void 0,fe={deviceId:String(O.deviceId||""),kind:O.kind==="thumbnail"?"thumbnail":"live",frameSeq:Number(O.frameSeq||0),streamFrameSeq:Number(O.streamFrameSeq||0)||void 0,streamId:String(O.streamId||""),commandId:O.commandId?String(O.commandId):void 0,sessionId:O.sessionId?String(O.sessionId):void 0,captureGeneration:Number(O.captureGeneration||0)||void 0,currentGenerationVerified:!1,streamPurpose:O.streamPurpose?String(O.streamPurpose):void 0,width:Number(O.width||0),height:Number(O.height||0),sourceWidth:Number(O.sourceWidth||0)||void 0,sourceHeight:Number(O.sourceHeight||0)||void 0,mimeType:String(O.mimeType||"image/jpeg"),mode:O.mode?String(O.mode):void 0,frameMode:O.frameMode?String(O.frameMode):void 0,frameProfile:O.frameProfile?String(O.frameProfile):void 0,encoding:O.encoding?String(O.encoding):void 0,codec:O.codec?String(O.codec):void 0,compression:O.compression?String(O.compression):void 0,pixelFormat:O.pixelFormat?String(O.pixelFormat):void 0,bytesPerPixel:Number(O.bytesPerPixel||0)||0,uncompressedByteLength:Number(O.uncompressedByteLength||0)||0,h264Format:O.h264Format?String(O.h264Format):void 0,isKeyFrame:O.isKeyFrame===!0,chunkType:O.chunkType?String(O.chunkType):void 0,timestampUs:Number(O.timestampUs||0)||0,durationUs:Number(O.durationUs||0)||0,sourceGapMs:Number(O.sourceGapMs||0)||0,agentSendGapMs:Number(O.agentSendGapMs||0)||0,agentSendDurationMs:Number(O.agentSendDurationMs||0)||0,agentSendDurationFrameSeq:Number(O.agentSendDurationFrameSeq||0)||0,agentPaceMs:Number(O.agentPaceMs||0)||0,agentQueueBeforePaceMs:Number(O.agentQueueBeforePaceMs||0)||0,agentFrameAgeMs:Number(O.agentFrameAgeMs||0)||0,inputFeedbackEventId:O.inputFeedbackEventId?String(O.inputFeedbackEventId):void 0,inputFeedbackInputSeq:bt(O.inputFeedbackInputSeq),inputFeedbackInputType:O.inputFeedbackInputType?String(O.inputFeedbackInputType):void 0,inputFeedbackIssuedAtEpochMs:bt(O.inputFeedbackIssuedAtEpochMs),inputFeedbackHubReceivedAtEpochMs:bt(O.inputFeedbackHubReceivedAtEpochMs),inputFeedbackHubForwardedAtEpochMs:bt(O.inputFeedbackHubForwardedAtEpochMs),inputFeedbackAgentReceivedAtEpochMs:bt(O.inputFeedbackAgentReceivedAtEpochMs),inputFeedbackAppliedAtEpochMs:bt(O.inputFeedbackAppliedAtEpochMs),inputFeedbackAgentApplyMs:bt(O.inputFeedbackAgentApplyMs),inputFeedbackApplyToCaptureMs:bt(O.inputFeedbackApplyToCaptureMs),inputFeedbackCaptureTimestampAvailable:typeof O.inputFeedbackCaptureTimestampAvailable=="boolean"?O.inputFeedbackCaptureTimestampAvailable:void 0,nativeCaptureTelemetryAvailable:typeof O.nativeCaptureTelemetryAvailable=="boolean"?O.nativeCaptureTelemetryAvailable:void 0,nativeCaptureTelemetryVersion:et===void 0?void 0:Math.max(0,et),nativeCaptureTelemetryAgeMs:it===void 0?void 0:Math.max(0,it),nativeEncoderHardwareAccelerationKnown:typeof O.nativeEncoderHardwareAccelerationKnown=="boolean"?O.nativeEncoderHardwareAccelerationKnown:void 0,nativeEncoderHardwareAccelerated:typeof O.nativeEncoderHardwareAccelerated=="boolean"?O.nativeEncoderHardwareAccelerated:void 0,nativeEncoderHardwareQueryStatus:O.nativeEncoderHardwareQueryStatus?String(O.nativeEncoderHardwareQueryStatus):void 0,nativeCaptureDisplayId:bt(O.nativeCaptureDisplayId),nativeCaptureFps:bt(O.nativeCaptureFps),nativeCompressionFps:bt(O.nativeCompressionFps),nativeEncodedFps:bt(O.nativeEncodedFps),nativeCaptureSampleCount:bt(O.nativeCaptureSampleCount),nativeEncodableFrameCount:bt(O.nativeEncodableFrameCount),nativeSkippedFrameCount:bt(O.nativeSkippedFrameCount),nativeCompressionOutputCount:bt(O.nativeCompressionOutputCount),nativeEncodedFrameCount:bt(O.nativeEncodedFrameCount),nativeEncodeFramesInFlight:bt(O.nativeEncodeFramesInFlight),nativeEncodePendingFrameCount:bt(O.nativeEncodePendingFrameCount),nativeEncodeTimestampOwnerCount:bt(O.nativeEncodeTimestampOwnerCount),nativeEncodeTimestampOwnerHighWatermark:bt(O.nativeEncodeTimestampOwnerHighWatermark),nativeBackpressureCoalescedFrameCount:bt(O.nativeBackpressureCoalescedFrameCount),nativeBackpressureSkippedFrameCount:bt(O.nativeBackpressureSkippedFrameCount),nativeEncodePendingReplacedFrameCount:bt(O.nativeEncodePendingReplacedFrameCount),nativeIdleSkippedFrameCount:bt(O.nativeIdleSkippedFrameCount),nativeVideoToolboxActiveSessionCount:bt(O.nativeVideoToolboxActiveSessionCount),nativeVideoToolboxSessionHighWatermark:bt(O.nativeVideoToolboxSessionHighWatermark),nativeOutputQueueDepth:bt(O.nativeOutputQueueDepth),nativeOutputQueueBytes:bt(O.nativeOutputQueueBytes),nativeOutputQueueOldestAgeMs:bt(O.nativeOutputQueueOldestAgeMs),nativeOutputQueueHighWatermark:bt(O.nativeOutputQueueHighWatermark),nativeOutputQueueDroppedCount:bt(O.nativeOutputQueueDroppedCount),nativeOutputQueueAwaitingKeyFrame:typeof O.nativeOutputQueueAwaitingKeyFrame=="boolean"?O.nativeOutputQueueAwaitingKeyFrame:void 0,nativeCopyTelemetryAvailable:typeof O.nativeCopyTelemetryAvailable=="boolean"?O.nativeCopyTelemetryAvailable:void 0,nativeAnnexBAccessUnitAllocationCount:bt(O.nativeAnnexBAccessUnitAllocationCount),nativeAnnexBPayloadCopyCount:bt(O.nativeAnnexBPayloadCopyCount),nativeAnnexBPayloadCopiedBytes:bt(O.nativeAnnexBPayloadCopiedBytes),nativeAndPipeResidenceAgeMs:bt(O.nativeAndPipeResidenceAgeMs),pipePayloadAllocationCount:bt(O.pipePayloadAllocationCount),pipePayloadCopyCount:bt(O.pipePayloadCopyCount),pipePayloadCopiedBytes:bt(O.pipePayloadCopiedBytes),handoffDroppedFrameCount:bt(O.handoffDroppedFrameCount),handoffRecoveryKeyFrameRequestCount:bt(O.handoffRecoveryKeyFrameRequestCount),handoffOldestFrameAgeMs:bt(O.handoffOldestFrameAgeMs),nativeCaptureResourceTelemetryAvailable:O.nativeCaptureResourceTelemetryAvailable===!0?zT(O):O.nativeCaptureResourceTelemetryAvailable===!1?!1:void 0,nativeCaptureTelemetryAt:O.nativeCaptureTelemetryAt?String(O.nativeCaptureTelemetryAt):void 0,droppedByAgent:Number(O.droppedByAgent||0)||0,hubIngressDropped:Number(O.hubIngressDropped||0)||0,hubClientDropped:ye,transport:O.transport?String(O.transport):void 0,videoTransport:O.videoTransport?String(O.videoTransport):void 0,frameTransportActive:O.frameTransportActive?String(O.frameTransportActive):void 0,frameTransportProtocol:O.frameTransportProtocol?String(O.frameTransportProtocol):void 0,frameTransportState:O.frameTransportState?String(O.frameTransportState):void 0,frameTransportReason:O.frameTransportReason?String(O.frameTransportReason):void 0,frameTransportChangedAt:O.frameTransportChangedAt?String(O.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(O.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(O.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:O.frameTransportP2pReady===!0,hubClientQueueTelemetryAvailable:ae,hubClientQueueDepth:Ne,hubClientQueueLimit:He,hubClientBufferedBytes:pe,udpIncompleteFrames:Number(O.udpIncompleteFrames||0)||0,hardwareEncoder:O.hardwareEncoder?String(O.hardwareEncoder):void 0,platformProfile:O.platformProfile?String(O.platformProfile):void 0,monitorIndex:Number.isFinite(Number(O.monitorIndex))?Number(O.monitorIndex):void 0,monitorCount:Number.isFinite(Number(O.monitorCount))?Number(O.monitorCount):void 0,requestedFps:Number(O.requestedFps||0)||0,effectiveFps:Number(O.effectiveFps||0)||0,captureTimingAvailable:O.captureTimingAvailable===!0,captureAverageMs:bt(O.captureAverageMs),captureP95Ms:bt(O.captureP95Ms),slowFrameCount:Number(O.slowFrameCount||0)||0,captureHelperRestarts:Number(O.captureHelperRestarts||0)||0,capturedAt:String(O.capturedAt||""),receivedAt:String(O.receivedAt||""),hubPacketAt:O.hubPacketAt?String(O.hubPacketAt):void 0,hubPacketEpochMs:B,browserReceivedEpochMs:Ue,hubPacketTransitAgeMs:B!==void 0?Oe:void 0,byteLength:Number(O.byteLength||We.byteLength),contentHash:O.contentHash?String(O.contentHash):void 0,captureMs:bt(O.captureMs),captureStageMs:bt(O.captureStageMs),convertMs:Number(O.convertMs||0)||0,compressMs:Number(O.compressMs||0)||0,captureSourceSerial:Number(O.captureSourceSerial||0)||0,captureSourceSkipped:Number(O.captureSourceSkipped||0)||0,deltaTileSize:Number(O.deltaTileSize||0)||0,deltaTileCount:Number(O.deltaTileCount||0)||0,deltaVisualTileCount:Number(O.deltaVisualTileCount||0)||0,deltaRefreshTileCount:Number(O.deltaRefreshTileCount||0)||0,deltaTotalTiles:Number(O.deltaTotalTiles||0)||0,payload:We};if(!fe.deviceId)return;const Ee=ge.expectedBinding;if(!Ee)return;const je=fe.deviceId===Ee.deviceId&&String(fe.sessionId||"")===Ee.sessionId&&fe.streamId===Ee.streamId&&String(fe.commandId||"")===Ee.commandId&&Number(fe.captureGeneration||0)===Ee.captureGeneration&&Number(fe.monitorIndex??-1)===Ee.monitorIndex&&String(fe.streamPurpose||"")===Ee.streamPurpose;if(!je)return;fe.currentGenerationVerified=je;const De=Number(ge.payload.monitorSelections?.[fe.deviceId]);if(Number.isFinite(De)&&Number.isFinite(Number(fe.monitorIndex))&&Number(fe.monitorIndex)!==De)return;const Et={streamId:ge.lastFrameStreamId,commandId:ge.lastFrameCommandId,order:ge.lastFrameOrder},at=Number(fe.streamFrameSeq||fe.frameSeq||0),ft=!!Et.commandId&&!!fe.commandId,jt=Et.streamId===fe.streamId&&(!ft||Et.commandId===fe.commandId),Ut=Et.order;if(jt&&Ut>=at&&(Ut===at||ft))return;ge.lastFrameStreamId=fe.streamId,ge.lastFrameCommandId=fe.commandId||"",ge.lastFrameOrder=at;const wt=q.current;wt.totalFrames+=1,wt.totalBytes+=We.byteLength,wt.sampleFrames+=1,wt.sampleBytes+=We.byteLength;const Wt=!S.current.has(fe.deviceId)&&!k.current.has(fe.deviceId),gt=W1(k.current,fe);Wt&&(S.current.set(fe.deviceId,gt),k.current.delete(fe.deviceId),u(new Map(S.current))),K.current?.(fe)},[]);d.useEffect(()=>{if(!n||!W)return;q.current.sampleStartedAt=performance.now();const Se=window.setInterval(()=>{if(!V.current)return;const ge=performance.now(),Ue=q.current,Me=Math.max(1,ge-Ue.sampleStartedAt);b({totalFrames:Ue.totalFrames,totalBytes:Ue.totalBytes,framesPerSecond:Ue.sampleFrames*1e3/Me,bytesPerSecond:Ue.sampleBytes*1e3/Me,sampleMs:Me,lastUpdatedAt:Date.now()}),u(G1(S.current,k.current)),Ue.sampleFrames=0,Ue.sampleBytes=0,Ue.sampleStartedAt=ge},2e3);return H.current=Se,()=>{window.clearInterval(Se),H.current===Se&&(H.current=null)}},[n,W]),d.useEffect(()=>{const Se=()=>{const ge=new Set,Ue=[...A.current.values()];for(;Ue.length>0;){const O=Ue.pop();!O||ge.has(O)||(ge.add(O),O.handoffFrom&&Ue.push(O.handoffFrom))}const Me=[...S.current.values(),...k.current.values()],rt=[...ge],At=T.current?.snapshot()||{closingSocketCount:0,closingSocketTimerCount:0,closingSocketTimeoutCount:0};return{deviceKey:W,active:V.current,socketCount:rt.length+At.closingSocketCount,openSocketCount:rt.filter(O=>O.socket.readyState===WebSocket.OPEN).length,connectingSocketCount:rt.filter(O=>O.socket.readyState===WebSocket.CONNECTING).length,closingSocketCount:At.closingSocketCount,closingSocketTimerCount:At.closingSocketTimerCount,closingSocketTimeoutCount:At.closingSocketTimeoutCount,expectedBindingCount:rt.filter(O=>!!O.expectedBinding).length,reconnectTimerCount:P.current.size,statsTimerCount:H.current===null?0:1,configurationRefreshTimerCount:F.current.size,restartTokenCount:I.current.size,retainedFrameCount:Me.length,retainedPayloadBytes:Me.reduce((O,qe)=>O+Math.max(0,Number(qe.payload?.byteLength||0)),0)}};return Tv.add(Se),()=>{Tv.delete(Se)}},[W]),d.useEffect(()=>{const Se=W?W.split(",").filter(Boolean):[];if(!Y){Ve(n?"livedesk-no-devices":"livedesk-stream-inactive");return}const ge=new Set(Se),Ue=performance.now();for(const Me of P.current.keys())ge.has(Me)||de(Me);for(const Me of F.current.keys())ge.has(Me)||Be(Me);for(const[Me,rt]of A.current.entries())ge.has(Me)||(de(Me),Ze(rt,"livedesk-device-unsubscribed"),A.current.delete(Me),I.current.delete(Me),S.current.delete(Me),k.current.delete(Me));q.current.sampleStartedAt<=0&&(q.current.sampleStartedAt=Ue,b({...cm,lastUpdatedAt:Date.now()}));for(const Me of Se){de(Me),Be(Me);const rt=Number(s.monitorSelections?.[Me]),At=Number.isInteger(rt)&&rt>=0?rt:0,O={[Me]:At},qe={type:"subscribe",deviceIds:[Me],autoStartLive:n,fps:he,maxWidth:ee,maxHeight:U,quality:L,mode:ve,frameMode:ve,streamPurpose:J,monitorSelections:O},B=String(s.connectionSessionIds?.[Me]||"").trim(),Oe=JSON.stringify({subscribePayload:qe,connectionSessionId:B}),We=A.current.get(Me),et=Number(We?.payload.monitorSelections?.[Me]),it=Number(O[Me]),ye=!!We&&Number.isFinite(et)&&Number.isFinite(it)&&et!==it,Ne=!!We&&We?.connectionSessionId!==B;if(We){const jt=We.socket.readyState===WebSocket.CONNECTING||We.socket.readyState===WebSocket.OPEN;if(We.payloadKey===Oe&&jt&&!We.disposed)continue}const He=We&&(We.socket.readyState===WebSocket.CONNECTING||We.socket.readyState===WebSocket.OPEN)&&!We.disposed?We.handoffFrom&&!We.handoffCompleted?We.handoffFrom:We:void 0,pe=We&&We!==He?We:void 0,ae=`/api/remote/frames/ws?devices=${encodeURIComponent(Me)}`,fe=xh(Sh(ae,r),ae);fe.binaryType="arraybuffer";const Ee=J1(),je={socket:fe,payload:qe,payloadKey:Oe,connectionSessionId:B,generation:j.current+1,monitorRestartToken:ye?`monitor-${Me}-${it}-${j.current+1}`:"",disposed:!1,handoffFrom:He,handoffCompleted:!1,lastFrameStreamId:"",lastFrameCommandId:"",lastFrameOrder:-1,sparseTelemetry:Ee,releaseOwnedState:()=>pw(Ee)};j.current=je.generation,(ye||Ne)&&(S.current.delete(Me),k.current.delete(Me),u(new Map(S.current))),A.current.set(Me,je),pe&&(pe.handoffFrom=void 0,Ze(pe,"livedesk-subscription-superseded"));const De=()=>{if(!V.current||je.disposed||A.current.get(Me)!==je){Ze(je,"livedesk-stale-frame-socket");return}de(Me),y("");const jt=N.current,Ut=jt.enabled&&(!jt.token||I.current.get(Me)!==jt.token),wt=Ut||je.monitorRestartToken!=="",Wt=Ut?jt.token:je.monitorRestartToken,gt=Ut?jt.reason:je.monitorRestartToken?"monitor-selection-change":"";if(fe.send(JSON.stringify({...je.payload,forceRestart:wt,restartReason:wt?gt:"",restartToken:wt?Wt:""})),le>0){const mt=window.setTimeout(()=>{F.current.get(Me)===mt&&F.current.delete(Me),V.current&&yt(Me,je)},Math.max(1e3,le));F.current.set(Me,mt)}Ut&&jt.token&&I.current.set(Me,jt.token);const yn=je.handoffFrom;je.handoffFrom=void 0,je.handoffCompleted=!0,yn&&!yn.disposed&&Ze(yn,"livedesk-subscription-replaced"),Je()},Et=jt=>{if(!V.current||je.disposed||A.current.get(Me)!==je)return;if(typeof jt.data=="string"){try{const wt=JSON.parse(jt.data),Wt=(gt,yn=!0)=>{const mt=$T(gt,Me,J);return mt?(je.expectedBinding=mt,yn&&z.current?.(mt),!0):!1};if(wt?.type==="RemoteFrameSubscriptionError")y(String(wt.error||"control-stream-start-failed"));else if(wt?.type==="RemoteFrameLiveAutoStart"){const yn=(Array.isArray(wt.skipped)?wt.skipped:[]).find(mt=>mt?.deviceId===Me);if(yn)yn.reason==="CAPTURE_TRANSITION_IN_PROGRESS"&&yn.retryScheduled===!0?y(""):y(String(yn.reason||"control-stream-start-failed"));else if(Array.isArray(wt.started)){const mt=wt.started.find(ha=>ha?.deviceId===Me);mt&&(y(""),Wt(mt,mt.ready===!0))}}else wt?.type==="RemoteFrameStreamReady"&&wt.deviceId===Me&&Wt(wt)&&y("")}catch{}return}const Ut=jt.data instanceof ArrayBuffer?jt.data:null;Ut&&(y(""),ne(Ut,je))},at=()=>{!V.current||je.disposed||A.current.get(Me)!==je||h("connecting")},ft=()=>{const jt=!je.disposed;je.disposed=!0,je.handoffCompleted=!0;const Ut=je.detachListeners;je.detachListeners=void 0,Ut?.();const wt=A.current.get(Me);wt===je&&Be(Me);let Wt=!1;if(wt===je){const gt=je.handoffFrom;je.handoffFrom=void 0,gt&&!gt.disposed&&(gt.socket.readyState===WebSocket.CONNECTING||gt.socket.readyState===WebSocket.OPEN)?(A.current.set(Me,gt),Wt=!0):A.current.delete(Me)}if(Je(),jt&&V.current&&wt===je&&!Wt){const gt=window.setTimeout(()=>{P.current.get(Me)===gt&&P.current.delete(Me),V.current&&D(yn=>yn+1)},750);de(Me),P.current.set(Me,gt)}};je.detachListeners=()=>{fe.removeEventListener("open",De),fe.removeEventListener("message",Et),fe.removeEventListener("error",at),fe.removeEventListener("close",ft)},fe.addEventListener("open",De),fe.addEventListener("message",Et),fe.addEventListener("error",at),fe.addEventListener("close",ft)}Je()},[n,Be,de,Ze,le,$e,W,he,ve,ne,r,U,ee,Fe,s.monitorSelections,L,$,Ve,yt,J,Y,Je]),d.useEffect(()=>{if(!Y||!Ae||!ce)return;const Se=W?W.split(",").filter(Boolean):[];for(const ge of Se){if(I.current.get(ge)===ce)continue;const Ue=A.current.get(ge);!Ue||!Qe(ge,Ue,Te,ce)||I.current.set(ge,ce)}},[W,Ae,ce,Te,Qe,Y]),d.useEffect(()=>()=>{Ve("livedesk-hook-unmount",!1)},[Ve]);const me=d.useCallback((Se,ge="browser-stale")=>{if(!Y)return!1;const Ue=Array.isArray(Se)&&Se.length>0?Se:W.split(",").filter(Boolean);if(Ue.length===0)return!1;let Me=!1;for(const rt of Ue){const At=A.current.get(rt);!At||At.socket.readyState!==WebSocket.OPEN||(Me=Qe(rt,At,ge,`${Date.now()}-${Math.random().toString(36).slice(2)}`)||Me)}return Me},[W,Qe,Y]),Ge=d.useCallback((Se,ge="browser-reconnect")=>{if(!Y)return!1;const Ue=Array.isArray(Se)&&Se.length>0?Se:W.split(",").filter(Boolean);if(Ue.length===0)return!1;let Me=!1;for(const rt of Ue){const At=A.current.get(rt);At&&(de(rt),Ze(At,`livedesk-${ge}`),A.current.delete(rt),I.current.delete(rt),S.current.delete(rt),k.current.delete(rt),Me=!0)}return Me&&u(new Map(S.current)),D(rt=>rt+1),Je(),!0},[de,Ze,W,Y,Je]);return{frames:l,state:f,error:g,stats:w,restartLive:me,reconnectLive:Ge}}function UT(t,n,r=Vn,s={}){const[l,u]=d.useState(null),[f,h]=d.useState(null),[g,y]=d.useState("idle"),[w,b]=d.useState(cm),S=d.useRef(null),k=d.useRef(s.onFrame),A=d.useRef(null),T=d.useRef(0),j=d.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),I=d.useMemo(()=>[...new Set(t.filter(Boolean))].join(","),[t]),N=d.useMemo(()=>[...new Set((s.captureDeviceIds||t).filter(Boolean))].join(","),[t,s.captureDeviceIds]),P=d.useMemo(()=>JSON.stringify(s.monitorSelections||{}),[s.monitorSelections]),H=d.useMemo(()=>{const W=Object.entries(s.connectionSessionIds||{}).filter(([Y])=>!!Y).map(([Y,V])=>[Y,String(V||"").trim()]).sort(([Y],[V])=>Y.localeCompare(V));return JSON.stringify(Object.fromEntries(W))},[s.connectionSessionIds]),F=d.useMemo(()=>({deviceIds:I.split(",").filter(Boolean),captureDeviceIds:N.split(",").filter(Boolean),fps:Number(s.fps||20),inputFps:Number(s.inputFps||8),width:Number(s.width||1920),height:Number(s.height||1080),tileWidth:Number(s.tileWidth||320),tileHeight:Number(s.tileHeight||180),monitorSelections:s.monitorSelections||{}}),[N,I,P,s.fps,s.height,s.inputFps,s.monitorSelections,s.tileHeight,s.tileWidth,s.width]),$=d.useMemo(()=>JSON.stringify({atlasConfiguration:F,connectionSessionKey:H}),[F,H]),D=d.useRef(F);D.current=F;const K=n&&F.deviceIds.length>0,z=d.useCallback(W=>W.readyState!==WebSocket.OPEN?!1:(W.send(JSON.stringify({type:"configure",...D.current})),!0),[]);d.useEffect(()=>{k.current=s.onFrame},[s.onFrame]),d.useEffect(()=>{if(!K)return;j.current.sampleStartedAt=performance.now();const W=window.setInterval(()=>{const Y=j.current,V=performance.now(),he=Math.max(1,V-Y.sampleStartedAt);b({totalFrames:Y.totalFrames,totalBytes:Y.totalBytes,framesPerSecond:Y.sampleFrames*1e3/he,bytesPerSecond:Y.sampleBytes*1e3/he,sampleMs:he,lastUpdatedAt:Date.now()});const ee=A.current;ee&&ee.frameSeq!==T.current&&(T.current=ee.frameSeq,u(ee)),Y.sampleFrames=0,Y.sampleBytes=0,Y.sampleStartedAt=V},1e3);return()=>window.clearInterval(W)},[K]),d.useEffect(()=>{if(!K){S.current?.close(),S.current=null,u(null),A.current=null,T.current=0,h(null),y("idle"),b(cm);return}let W=!1,Y=0;const V=()=>{if(W)return;const he=xh(Sh("/api/remote/atlas/ws",r),"/api/remote/atlas/ws");he.binaryType="arraybuffer",S.current=he,y("connecting"),he.addEventListener("open",()=>{j.current.sampleStartedAt=performance.now(),y("open"),z(he)}),he.addEventListener("message",ee=>{if(typeof ee.data=="string"){try{const L=JSON.parse(ee.data);L?.type==="Mode4AtlasLayout"&&h({layoutVersion:Number(L.layoutVersion||0),width:Number(L.width||1920),height:Number(L.height||1080),columns:Number(L.columns||1),rows:Number(L.rows||1),tiles:Array.isArray(L.tiles)?L.tiles:[]})}catch{}return}const U=ee.data instanceof ArrayBuffer?ee.data:null;if(!(!U||U.byteLength<5))try{const L=Date.now(),ve=new DataView(U).getUint32(0,!1);if(ve<=0||ve+4>U.byteLength)return;const J=JSON.parse(Jv.decode(new Uint8Array(U,4,ve))),Ae=new Uint8Array(U,4+ve),ce=bt(J.hubClientDropped),Te=bt(J.hubClientQueueDepth),Fe=bt(J.hubClientQueueLimit),$e=bt(J.hubClientBufferedBytes),Ze={deviceId:String(J.deviceId||"__livedesk_mode4_atlas__"),kind:"live",frameSeq:Number(J.frameSeq||0),streamFrameSeq:Number(J.streamFrameSeq||0)||void 0,streamId:String(J.streamId||"mode4-atlas"),commandId:J.commandId?String(J.commandId):void 0,width:Number(J.width||1920),height:Number(J.height||1080),sourceWidth:Number(J.sourceWidth||J.width||1920),sourceHeight:Number(J.sourceHeight||J.height||1080),mimeType:String(J.mimeType||"video/h264"),mode:String(J.mode||"mode4-h264-atlas"),frameMode:String(J.frameMode||"mode4-h264-atlas"),frameProfile:String(J.frameProfile||"mode4-h264-atlas-v1"),encoding:String(J.encoding||"video-atlas"),codec:String(J.codec||"h264"),compression:String(J.compression||"video/h264"),h264Format:String(J.h264Format||"annexb"),isKeyFrame:J.isKeyFrame===!0,chunkType:String(J.chunkType||""),timestampUs:Number(J.timestampUs||0),durationUs:Number(J.durationUs||0),transport:J.transport?String(J.transport):void 0,videoTransport:J.videoTransport?String(J.videoTransport):void 0,frameTransportActive:J.frameTransportActive?String(J.frameTransportActive):void 0,frameTransportProtocol:J.frameTransportProtocol?String(J.frameTransportProtocol):void 0,frameTransportState:J.frameTransportState?String(J.frameTransportState):void 0,frameTransportReason:J.frameTransportReason?String(J.frameTransportReason):void 0,frameTransportChangedAt:J.frameTransportChangedAt?String(J.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(J.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(J.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:J.frameTransportP2pReady===!0,hubClientQueueTelemetryAvailable:ce!==void 0&&Te!==void 0&&Fe!==void 0&&$e!==void 0,hubClientDropped:ce,hubClientQueueDepth:Te,hubClientQueueLimit:Fe,hubClientBufferedBytes:$e,udpIncompleteFrames:Number(J.udpIncompleteFrames||0)||0,hardwareEncoder:J.hardwareEncoder?String(J.hardwareEncoder):void 0,platformProfile:J.platformProfile?String(J.platformProfile):void 0,capturedAt:String(J.capturedAt||""),receivedAt:String(J.receivedAt||""),hubPacketAt:J.hubPacketAt?String(J.hubPacketAt):void 0,hubPacketEpochMs:Number(J.hubPacketEpochMs||0)||void 0,browserReceivedEpochMs:L,byteLength:Ae.byteLength,layoutVersion:Number(J.layoutVersion||0),atlasComposeMs:Number(J.atlasComposeMs||0),atlasPoolStarved:Number(J.atlasPoolStarved||0),atlasReadyTiles:Number(J.atlasReadyTiles||0),atlasTileCount:Number(J.atlasTileCount||0),atlasInputRevision:Number(J.atlasInputRevision||0),atlasSourceNewestAtEpochMs:Number(J.atlasSourceNewestAtEpochMs||0),atlasSourceOldestAtEpochMs:Number(J.atlasSourceOldestAtEpochMs||0),atlasSourceMaxAgeMs:Number(J.atlasSourceMaxAgeMs||0),payload:Ae},de=j.current;de.totalFrames+=1,de.totalBytes+=Ae.byteLength,de.sampleFrames+=1,de.sampleBytes+=Ae.byteLength,A.current=Ze,T.current===0&&(T.current=Ze.frameSeq,u(Ze)),k.current?.(Ze)}catch{}}),he.addEventListener("error",()=>y("error")),he.addEventListener("close",()=>{S.current===he&&(S.current=null),!W&&(y("closed"),Y=window.setTimeout(V,1200))})};return V(),()=>{W=!0,window.clearTimeout(Y),S.current?.close(),S.current=null}},[K,r,z]),d.useEffect(()=>{if(!K)return;const W=S.current;W&&z(W)},[$,K,z]);const q=d.useCallback(()=>{const W=S.current;return W?z(W):!1},[z]);return{frame:l,layout:f,state:g,stats:w,refreshInputs:q}}function qT(t,n=Vn){const r=d.useRef(null),s=d.useRef(0),l=d.useRef(0),u=d.useRef(new Map),f=d.useRef(""),[h,g]=d.useState("idle"),[y,w]=d.useState(""),[b,S]=d.useState(bw),k=d.useRef({totalSent:0,totalDropped:0,sampleSent:0,sampleDropped:0,sampleStartedAt:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0});d.useEffect(()=>{if(!t){r.current?.close(),r.current=null,l.current=0,f.current="",u.current.clear(),g("idle"),w(""),S(bw);return}let T=!1,j=0;const I=()=>{if(T)return;const N=xh(Sh("/api/remote/input/ws",n),"/api/remote/input/ws");r.current=N,k.current.sampleStartedAt=performance.now(),g("connecting"),w(""),N.addEventListener("open",()=>{T||r.current!==N||(w(""),g("open"))}),N.addEventListener("message",P=>{if(!(T||r.current!==N||typeof P.data!="string"))try{const H=JSON.parse(P.data),F=Number(H.inputSeq||H.result?.inputSeq||0),$=String(H.deviceId||H.result?.deviceId||""),D=String(H.inputEventId||H.result?.inputEventId||""),K=u.current.get(F);if($&&(K&&K.deviceId!==$||!K&&f.current&&f.current!==$)||K?.inputEventId&&D&&K.inputEventId!==D)return;if(H?.type==="RemoteInputError"){F>0&&u.current.delete(F),w(String(H.error||H.result?.error||"Remote input failed.")),N.readyState===WebSocket.OPEN&&g("open");return}if(H?.type!=="RemoteInputApplied")return;K&&(k.current.lastRoundTripMs=Math.max(0,performance.now()-K.sentAt),u.current.delete(F)),k.current.lastInputSeq=F,k.current.lastAgentApplyMs=Math.max(0,Number(H.agentApplyMs||0)),w(""),g("open")}catch{}}),N.addEventListener("close",()=>{T||r.current!==N||(r.current=null,g("closed"),j=window.setTimeout(I,1200))}),N.addEventListener("error",()=>{!T&&r.current===N&&g("error")})};return I(),()=>{T=!0,window.clearTimeout(j);const N=r.current;r.current=null,N?.close(),u.current.clear()}},[t,n]),d.useEffect(()=>{if(!t)return;const T=window.setInterval(()=>{const j=performance.now(),I=k.current,N=Math.max(1,j-I.sampleStartedAt);S({totalSent:I.totalSent,totalDropped:I.totalDropped,sentPerSecond:I.sampleSent*1e3/N,droppedPerSecond:I.sampleDropped*1e3/N,bufferedAmount:r.current?.bufferedAmount||0,lastInputType:I.lastInputType,lastInputSeq:I.lastInputSeq,lastRoundTripMs:I.lastRoundTripMs,lastAgentApplyMs:I.lastAgentApplyMs,lastUpdatedAt:Date.now()}),I.sampleSent=0,I.sampleDropped=0,I.sampleStartedAt=j},1e3);return()=>window.clearInterval(T)},[t]);const A=d.useCallback((T,j)=>{const I=r.current;if(!I||I.readyState!==WebSocket.OPEN||!T)return!1;const N=String(j.type||"").toLowerCase(),F=N==="pointermove"||N==="wheel",$=k.current;if(F&&I.bufferedAmount>LT)return $.totalDropped+=1,$.sampleDropped+=1,$.lastInputType=`${N}-coalescible-drop`,!1;if(!F&&I.bufferedAmount>PT){$.lastInputType=`${N||"input"}-fail-closed`,w("Remote input channel was reset because ordered input could not drain.");try{I.close(4001,"ordered-input-backpressure")}catch{}return!1}const D=s.current+1;s.current=D;const K=`${D}-${crypto.randomUUID()}`,z=Date.now(),q=!F||D-l.current>=OT;for(q&&(u.current.set(D,{sentAt:performance.now(),deviceId:T,inputEventId:K}),F&&(l.current=D)),f.current=T,yS.set(T,{inputSeq:D,inputType:N||"input",sentAt:performance.now()});u.current.size>256;){const W=u.current.keys().next().value;if(W===void 0)break;u.current.delete(W)}try{I.send(JSON.stringify({type:"input",requestId:F?"":crypto.randomUUID(),fireAndForget:F,deviceId:T,input:{...j,inputEventId:K,inputSeq:D,requestAck:q,issuedAtEpochMs:z,issuedAt:new Date(z).toISOString()}}))}catch{u.current.delete(D),w("Remote input channel closed before the ordered input was queued.");try{I.close(4002,"input-send-failed")}catch{}return!1}return $.totalSent+=1,$.sampleSent+=1,$.lastInputType=N||"input",!0},[]);return{state:h,sendInput:A,stats:b,error:y}}const Td={queuedMs:0,browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:null,helperAlive:null,helperReady:!1,captureHealthy:!1,captureAwaitingCurrentPcm:!1,capturePhase:"",backendKind:"",helperRequired:!1,helperPid:0,captureRestartCount:0,nativeCallbackDiagnosticsAvailable:!1,nativeRejectedCallbackCount:0,nativeCurrentnessDropCount:0,nativeLastDropReason:"",localProcessingAgeMs:0,lastPacketAgeMs:0,lastAcceptedAgeMs:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:"closed",stalledCount:0,automaticRestarts:0,maximumAcceptedGapMs:0,workletRingCapacityBytes:0,workletRingBufferedBytes:0,workletRingDroppedFrames:0,workletRingUnderflowCount:0,lastUpdatedAt:0},WT=.25,xw=300,Sw=2,Np=1500,Og=5e3,GT=2e3,Cw=1e4,qf=[0,1e3,3e3];function kw(t){const n=Date.parse(String(t||""));return Number.isFinite(n)?Math.max(0,Date.now()-n):0}function VT(t,n,r=Vn,s=0,l=!1,u="",f,h){const g=d.useRef(null),[y,w]=d.useState("idle"),[b,S]=d.useState(null),[k,A]=d.useState(Td),[T,j]=d.useState(""),I=d.useRef(l);return I.current=l,d.useEffect(()=>{l||(S(N=>N===null?N:null),A(N=>N===Td?N:Td))},[l]),d.useEffect(()=>{if(!n||!t){w("idle"),S(null),A(Td),j("");return}w("connecting"),S(null),A(Td),j("");const N=window.AudioContext||window.webkitAudioContext;if(!N){w("unsupported"),A(Td),j("Audio playback is not supported in this browser.");return}let P=!1,H=null;const F=lT.acquire(({release:$})=>{if(P){$();return}const D=new N({latencyHint:"interactive"});g.current=D;let K=String(u||"").trim();const z="/api/remote/audio/ws?devices="+encodeURIComponent(t)+(K?"&streamId="+encodeURIComponent(K):""),q=xh(Sh(z,r),z);q.binaryType="arraybuffer";const W=Na.createOwner({deviceId:t,socket:q,audioContext:D,statsTimer:null});let Y=!1;const V=()=>{const ae=Na.releaseIfDrained(W);return(ae||!Na.hasOwner(W))&&!Y&&(Y=!0,$()),ae},he=Zv({sampleRate:192e3,channels:8}).capacityBytes,ee=gT({maxPendingPackets:Mv,maxPendingBytes:he}),U=aT(),L={browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:null,helperAlive:null,helperReady:!1,captureHealthy:!1,captureStatusFailed:!1,captureAwaitingCurrentPcm:!1,captureAwaitingSinceAt:0,capturePhase:"",backendKind:"",helperRequired:!1,helperPid:0,captureRestartCount:0,nativeCallbackDiagnosticsAvailable:!1,nativeRejectedCallbackCount:0,nativeCurrentnessDropCount:0,nativeLastDropReason:"",localProcessingAgeMs:0,lastPacketAt:0,lastAcceptedAt:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:String(D.state),stalledCount:0,automaticRestarts:0,maximumAcceptedGapMs:0,activeStreamId:K,lastCaptureStatusAt:0,lastPcmAtEpochMs:0,workletRingCapacityBytes:0,workletRingBufferedBytes:0,workletRingBufferedMs:0,workletRingDroppedFrames:0,workletRingUnderflowCount:0};let le=!1,ve=!1,J=null,Ae=0,ce=0,Te="",Fe=!1,$e=()=>{},Ze="connecting",de="";const Be=ae=>{le||ae===Ze||(Ze=ae,w(ae))},Ve=ae=>{le||ae===de||(de=ae,j(ae))};let Je=0,Qe=!1,yt=0,ne=0,me=0,Ge=!1;const Se=()=>{Na.setPendingWorkletPackets(W,ee.getPendingPacketCount(),ee.getPendingPacketBytes(),ee.getPendingPacketHighWater(),ee.getPendingByteHighWater())},ge=ae=>{L.workletRingCapacityBytes=Math.max(0,Math.min(he,Number(ae.ringCapacityBytes||0)||0)),L.workletRingBufferedBytes=Math.max(0,Math.min(L.workletRingCapacityBytes,Number(ae.ringBufferedBytes||0)||0)),L.workletRingBufferedMs=Math.max(0,Math.min(WT*1e3,Number(ae.ringBufferedMs||0)||0)),L.workletRingDroppedFrames=Math.max(L.workletRingDroppedFrames,Number(ae.ringDroppedFrames||0)||0),L.workletRingUnderflowCount=Math.max(L.workletRingUnderflowCount,Number(ae.ringUnderflowCount||0)||0),Na.setPcmRing(W,L.workletRingCapacityBytes,L.workletRingBufferedBytes)},Ue=()=>{const ae=J;if(J=null,Fe=!1,ae){ae.onprocessorerror=null,ae.port.onmessage=null;try{ae.disconnect()}catch{}try{ae.port.close()}catch{}}ee.terminate(),Se(),L.workletRingCapacityBytes=0,L.workletRingBufferedBytes=0,L.workletRingBufferedMs=0,Na.setPcmRing(W,0,0),Na.setWorkletNode(W,0,0,Ae),V()},Me=ae=>{const fe=ae.data||{},Ee=String(fe.type||"");if((Ee==="packet-terminal"||Ee==="processor-error")&&(ee.acknowledge(typeof fe.packetId=="number"?fe.packetId:String(fe.packetId||"")),Se()),Ee==="packet-terminal"){const je=Math.max(0,Number(fe.droppedFrames||0)||0);je>0&&(L.workletRingDroppedFrames+=je,L.resyncs+=1)}if(Ee==="ring-configured"||Ee==="ring-state"||Ee==="disposed"){const je=L.workletRingDroppedFrames;ge(fe),L.workletRingDroppedFrames>je&&(L.resyncs+=1)}Ee==="disposed"?Ue():Ee==="processor-error"&&$e(String(fe.error||"Remote audio worklet processing failed."))},rt=()=>{if(!(!J||!Fe))try{J.port.postMessage({type:"flush"})}catch{$e("Remote audio worklet could not be flushed.")}},At=()=>{q.readyState===WebSocket.OPEN&&q.send(JSON.stringify({type:"subscribe",deviceIds:[t],streamIdsByDeviceId:K?{[t]:K}:{}}))},O=()=>{L.audioContextState=String(D.state),!le&&(L.audioContextState==="suspended"||L.audioContextState==="interrupted"?Be("suspended"):L.audioContextState==="closed"&&(Be("error"),Ve("The browser audio context is closed. Toggle Remote Audio off and on to recover.")))},qe=async()=>{if(le||String(D.state)==="closed")return!1;try{if(String(D.state)!=="running"&&await D.resume(),L.audioContextState=String(D.state),!le&&!Qe&&L.audioContextState==="running"){const ae=L.lastAcceptedAt>0&&performance.now()-L.lastAcceptedAt<=Np,fe=L.lastCaptureStatusAt>0&&performance.now()-L.lastCaptureStatusAt<=Og&&L.captureHealthy;Be(ae?"playing":fe?"silent":"open")}return L.audioContextState==="running"}catch(ae){return le||(Be("suspended"),Ve(ae instanceof Error?"Audio playback is suspended: "+ae.message:"Audio playback is suspended.")),!1}},B=async()=>{if(!D.audioWorklet||typeof AudioWorkletNode>"u")throw new Error("AudioWorklet is unavailable in this browser.");const ae=new Blob([xT],{type:"text/javascript"});Te=URL.createObjectURL(ae);try{await D.audioWorklet.addModule(Te)}finally{URL.revokeObjectURL(Te),Te=""}if(le||String(D.state)==="closed")return;const fe=new AudioWorkletNode(D,vS,{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[Sw],channelCount:Sw,channelCountMode:"explicit"});Ae+=1,J=fe,fe.port.onmessage=Me,fe.onprocessorerror=()=>{$e("Remote audio worklet stopped unexpectedly.")},fe.connect(D.destination),Fe=!0,Na.setWorkletNode(W,1,1,Ae)},Oe=(ae,fe,Ee,je)=>{const De=J;if(le||!Fe||!De||fe.byteLength<=0)return!1;const Et=Xv({sampleRate:ae.sampleRate,channels:ae.channels,mimeType:ae.mimeType}),at=++ce;if(!ee.claim(at,fe.byteLength))return Se(),!1;Se();try{return De.port.postMessage({type:"pcm",packetId:at,buffer:fe,byteOffset:Ee,byteLength:je,sampleRate:Et.sampleRate,channels:Et.channels,mimeType:ae.mimeType,sampleFormat:Et.sampleFormat},[fe]),!0}catch{return ee.acknowledge(at),Se(),!1}},We=async()=>{if(le||Qe||q.readyState!==WebSocket.OPEN)return;if(yt>=qf.length){Be("error"),Ve("Remote audio stopped sending frames. Toggle Audio off and on to retry.");return}const ae=yt;yt+=1,Qe=!0,L.stalledCount+=1,L.automaticRestarts+=1,Be("reconnecting");try{if(!f)throw new Error("Remote audio restart owner is unavailable.");const fe=await f(t);if(le||!fe)return;K=fe,At();const Ee=performance.now();Je=Ee,L.lastPacketAt=Ee,L.lastAcceptedAt=0,L.lastCaptureStatusAt=0,L.lastPcmAtEpochMs=0,L.captureAlive=null,L.helperAlive=null,L.helperReady=!1,L.captureHealthy=!1,L.captureStatusFailed=!1,L.captureAwaitingCurrentPcm=!1,L.captureAwaitingSinceAt=0,L.capturePhase="",L.backendKind="",L.helperRequired=!1,L.helperPid=0,L.nativeCallbackDiagnosticsAvailable=!1,L.nativeRejectedCallbackCount=0,L.nativeCurrentnessDropCount=0,L.nativeLastDropReason="",L.silentForMs=0,L.activeStreamId=K,L.lastFrameSeq=0,L.maximumAcceptedGapMs=0,rt(),ne=Ee+(qf[ae+1]??3e3),Ve(""),le||Be("open")}catch(fe){le||(ne=performance.now()+(qf[ae+1]??3e3),Be("error"),Ve(fe instanceof Error?"Remote audio restart failed: "+fe.message:"Remote audio restart failed."))}finally{Qe=!1}},et=()=>{L.drops+=1},it=window.setInterval(()=>{if(le)return;const ae=performance.now(),fe=L.lastPacketAt>0?Math.max(0,ae-L.lastPacketAt):Je>0?Math.max(0,ae-Je):0,Ee=L.lastAcceptedAt>0?Math.max(0,ae-L.lastAcceptedAt):0,je=L.lastCaptureStatusAt>0?Math.max(0,ae-L.lastCaptureStatusAt):0,De=q.readyState===WebSocket.OPEN,Et=L.lastCaptureStatusAt>0,at=Et&&je<=Og&&L.captureHealthy,ft=Et&&L.captureStatusFailed&&je>GT,jt=Et&&je>Og,Ut=!Et&&Je>0&&ae-Je>Cw,wt=L.captureAwaitingCurrentPcm&&L.captureAwaitingSinceAt>0&&ae-L.captureAwaitingSinceAt>Cw,Wt=Je>0&&(L.lastAcceptedAt<=0?ae-Je>Np:Ee>Np);if(De&&Je>0&&(ft||jt||Ut||wt)?yt>=qf.length&&!Qe?(Be("error"),Ve("Remote audio capture heartbeat stopped. Toggle Audio off and on to retry.")):!Qe&&ae>=ne?We():Qe||Be("stalled"):De&&Wt&&!Qe&&L.audioContextState!=="suspended"&&L.audioContextState!=="interrupted"&&Be(at?"silent":"open"),cT({enabled:I.current,now:ae,lastPublishedAt:me})){me=ae,A({queuedMs:L.workletRingBufferedMs,browserAgeMs:L.browserAgeMs,captureAgeMs:L.captureAgeMs,captureStatusAgeMs:je,silentForMs:L.silentForMs,captureAlive:L.captureAlive,helperAlive:L.helperAlive,helperReady:L.helperReady,captureHealthy:L.captureHealthy,captureAwaitingCurrentPcm:L.captureAwaitingCurrentPcm,capturePhase:L.capturePhase,backendKind:L.backendKind,helperRequired:L.helperRequired,helperPid:L.helperPid,captureRestartCount:L.captureRestartCount,nativeCallbackDiagnosticsAvailable:L.nativeCallbackDiagnosticsAvailable,nativeRejectedCallbackCount:L.nativeRejectedCallbackCount,nativeCurrentnessDropCount:L.nativeCurrentnessDropCount,nativeLastDropReason:L.nativeLastDropReason,localProcessingAgeMs:L.localProcessingAgeMs,lastPacketAgeMs:fe,lastAcceptedAgeMs:Ee,framesReceived:L.framesReceived,drops:L.drops,resyncs:L.resyncs,pendingDecodes:L.pendingDecodes,lastFrameSeq:L.lastFrameSeq,audioContextState:L.audioContextState,stalledCount:L.stalledCount,automaticRestarts:L.automaticRestarts,maximumAcceptedGapMs:L.maximumAcceptedGapMs,workletRingCapacityBytes:L.workletRingCapacityBytes,workletRingBufferedBytes:L.workletRingBufferedBytes,workletRingDroppedFrames:L.workletRingDroppedFrames,workletRingUnderflowCount:L.workletRingUnderflowCount,lastUpdatedAt:Date.now()});const gt=U.publish();gt&&(Ge=!0,Na.setRetainedFrame(W,1,gt.payload.byteLength),S(gt))}else!I.current&&Ge&&(Ge=!1,U.clear(),Na.setRetainedFrame(W,0,0))},250);Na.setStatsTimer(W,it);const ye=()=>{O(),(String(D.state)==="suspended"||String(D.state)==="interrupted")&&qe()},Ne=()=>{document.visibilityState==="visible"&&qe()},He=()=>{qe()};D.addEventListener("statechange",ye),document.addEventListener("visibilitychange",Ne),window.addEventListener("pageshow",He),window.addEventListener("pointerdown",He),window.addEventListener("keydown",He),Be("connecting"),Ve(""),O();const pe=(ae,fe,Ee,je,De)=>{if(L.localProcessingAgeMs=Math.max(0,performance.now()-De),le||L.localProcessingAgeMs>xw||!Av(ae,{deviceId:t,streamId:K}))return et(),!1;L.activeStreamId!==K&&(L.activeStreamId=K,L.lastFrameSeq=0,L.maximumAcceptedGapMs=0,rt());const Et=mT(ae,{deviceId:t,streamId:K,lastFrameSeq:L.lastFrameSeq});if(!Et.accepted||!Oe(ae,fe,Ee,je))return et(),!1;L.browserAgeMs=kw(ae.receivedAt),L.captureAgeMs=kw(ae.capturedAt);const at=performance.now();L.lastAcceptedAt>0&&(L.maximumAcceptedGapMs=Math.max(L.maximumAcceptedGapMs,at-L.lastAcceptedAt)),L.lastAcceptedAt=at,L.framesReceived+=1,L.lastFrameSeq=Et.nextFrameSeq,yt=0,ne=0,I.current&&(U.accept(ae),Ge=!0,Na.setRetainedFrame(W,1,0)),String(D.state)!=="running"&&qe();const ft=String(D.state)==="running";return ft&&Ve(""),Be(ft?"playing":"suspended"),!0};$e=(ae="")=>{if(!ve){if(ve=!0,ae&&(Na.recordTerminalFailure(W,ae,ae.includes("setup failed")?"setup":"processor"),Be(ae.includes("AudioWorklet is unavailable")?"unsupported":"error"),Ve(ae),h?.(t,K,"browser-audio-playback-failed").catch(()=>{})),le=!0,Na.deactivate(W),window.clearInterval(it),Na.setStatsTimer(W,null),D.removeEventListener("statechange",ye),document.removeEventListener("visibilitychange",Ne),window.removeEventListener("pageshow",He),window.removeEventListener("pointerdown",He),window.removeEventListener("keydown",He),U.clear(),Na.setRetainedFrame(W,0,0),J)try{J.port.postMessage({type:"dispose"})}catch{}try{q.close()}catch{}q.readyState===WebSocket.CLOSED&&Na.setSocket(W,null),D.close().catch(()=>{}).finally(()=>{Ue(),String(D.state)==="closed"&&Na.setAudioContext(W,null),V()}),g.current===D&&(g.current=null),V()}},B().catch(ae=>{$e(ae instanceof Error?`Remote audio worklet setup failed: ${ae.message}`:"Remote audio worklet setup failed.")}),q.addEventListener("open",()=>{le||(Je=performance.now(),L.lastPacketAt=Je,L.lastAcceptedAt=0,L.lastCaptureStatusAt=0,L.lastPcmAtEpochMs=0,L.captureAlive=null,L.helperAlive=null,L.helperReady=!1,L.captureHealthy=!1,L.captureStatusFailed=!1,L.captureAwaitingCurrentPcm=!1,L.captureAwaitingSinceAt=0,L.capturePhase="",L.backendKind="",L.helperRequired=!1,L.helperPid=0,L.maximumAcceptedGapMs=0,L.silentForMs=0,Be("open"),At(),qe())}),q.addEventListener("message",ae=>{if(typeof ae.data=="string")return;const fe=ae.data instanceof ArrayBuffer?ae.data:null;if(!fe||fe.byteLength<5)return;const Ee=performance.now();L.lastPacketAt=Ee;try{const De=new DataView(fe).getUint32(0,!1);if(De<=0||De+4>fe.byteLength){et();return}const Et=new Uint8Array(fe,4,De),at=JSON.parse(Jv.decode(Et)),ft=new Uint8Array(fe,4+De),jt=String(at.deviceId||""),Ut=String(at.streamId||"");if(!Av({deviceId:jt,streamId:Ut},{deviceId:t,streamId:K})){et();return}const wt=String(at.frameKind||at.kind||"").toLowerCase();if(at.type==="remote.audio.status"||wt==="audio-status"){L.lastCaptureStatusAt=Ee;const gt=pT(at);if(L.captureAlive=gt.captureAlive,L.helperAlive=gt.helperAlive,L.helperReady=gt.helperReady,L.captureHealthy=gt.healthy,L.captureStatusFailed=gt.failed,L.captureAwaitingCurrentPcm=gt.awaitingCurrentPcm,gt.awaitingCurrentPcm?L.captureAwaitingSinceAt||=Ee:L.captureAwaitingSinceAt=0,L.capturePhase=gt.capturePhase,L.backendKind=gt.backendKind,L.helperRequired=gt.helperRequired===!0,L.helperPid=gt.helperPid,L.captureRestartCount=Math.max(0,Number(at.restartCount||0)||0),L.nativeCallbackDiagnosticsAvailable=at.callbackDiagnosticsAvailable===!0,L.nativeRejectedCallbackCount=L.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(at.rejectedCallbackCount||0)||0):0,L.nativeCurrentnessDropCount=L.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(at.currentnessDropCount||0)||0):0,L.nativeLastDropReason=L.nativeCallbackDiagnosticsAvailable?String(at.lastDropReason||""):"",L.lastPcmAtEpochMs=Math.max(0,Number(at.lastPcmAtEpochMs||0)||0),L.silentForMs=Math.max(0,Number(at.silentForMs||0)||0),L.captureAgeMs=L.lastPcmAtEpochMs>0?Math.max(0,Date.now()-L.lastPcmAtEpochMs):L.silentForMs,L.captureHealthy){if(yt=0,ne=0,!Qe){Ve("");const yn=String(D.state)==="running",mt=L.lastAcceptedAt>0&&performance.now()-L.lastAcceptedAt<=Np;Be(yn?mt?"playing":"silent":"suspended")}}else L.captureAwaitingCurrentPcm&&!Qe?Be("open"):L.captureStatusFailed&&!Qe&&Be("stalled");return}const Wt={deviceId:jt,frameSeq:Number(at.frameSeq||0),streamId:Ut,mimeType:String(at.mimeType||"audio/webm;codecs=opus"),sampleRate:Number(at.sampleRate||48e3),channels:Number(at.channels||2),capturedAt:String(at.capturedAt||""),receivedAt:String(at.receivedAt||""),byteLength:Number(at.byteLength||ft.byteLength),payload:gS};if(!Wt.deviceId||le)return;if(performance.now()-Ee>xw){et();return}if(fT(Wt.mimeType)){pe(Wt,fe,ft.byteOffset,ft.byteLength,Ee);return}et(),Be("error"),Ve(`Unsupported remote audio format "${Wt.mimeType}". Requesting a bounded PCM restart.`),!Qe&&yt<qf.length&&(ne=0,We());return}catch(je){le||(Be("error"),Ve(je instanceof Error?je.message:String(je)))}}),q.addEventListener("error",()=>{le||(Be("error"),Ve("Remote audio WebSocket error."))}),q.addEventListener("close",()=>{Na.setSocket(W,null),V(),le||Be("closed")}),H=()=>{$e()}});return F.ready.catch($=>{P||(w("error"),j($ instanceof Error?`Remote audio owner setup failed: ${$.message}`:"Remote audio owner setup failed."))}),()=>{P=!0,H?H():F.cancel()}},[t,n,r,s,f,h]),{state:y,lastFrame:b,stats:k,error:T}}const KT=3;function Mw(t,n,r){const s=Math.max(1,Number(r)||1),l=Math.max(0,Math.min(s,Number(t)-Number(n))),u=Math.min(s/2,KT);return l<=u?0:l>=s-u?1:l/s}function QT(t,n,r){return{normalizedX:Mw(t,r.left,r.width),normalizedY:Mw(n,r.top,r.height)}}const Aw=8,Nv=320,Tw=28,gm=1,bS=4;function tn(t,n=0){const r=Number(t);return Number.isFinite(r)?r:n}function ey(t,n){const r=tn(t?.clientX)-tn(n?.clientX),s=tn(t?.clientY)-tn(n?.clientY);return r*r+s*s}function Zp(t,n,r){return Math.min(r,Math.max(n,t))}function wS(t,n){return{clientX:(tn(t?.clientX)+tn(n?.clientX))/2,clientY:(tn(t?.clientY)+tn(n?.clientY))/2}}function xS(t,n){return Math.sqrt(ey(t,n))}function dh(){return{scale:gm,translateX:0,translateY:0}}function YT(t,n,r,s){const l=r||dh(),u=Zp(tn(l.scale,gm),gm,bS),f={left:tn(s?.left),top:tn(s?.top),width:Math.max(1,tn(s?.width,1)),height:Math.max(1,tn(s?.height,1))},h=wS(t,n);return{startDistance:Math.max(1,xS(t,n)),startScale:u,anchorX:(h.clientX-f.left-tn(l.translateX))/u,anchorY:(h.clientY-f.top-tn(l.translateY))/u,bounds:f}}function XT(t,n,r){if(!t)return dh();const s=wS(n,r),l=Zp(tn(t.startScale,gm)*xS(n,r)/Math.max(1,tn(t.startDistance,1)),gm,bS),u=Math.max(1,tn(t.bounds?.width,1)),f=Math.max(1,tn(t.bounds?.height,1)),h=Zp(s.clientX-tn(t.bounds?.left)-tn(t.anchorX)*l,u*(1-l),0),g=Zp(s.clientY-tn(t.bounds?.top)-tn(t.anchorY)*l,f*(1-l),0);return{scale:l,translateX:h,translateY:g}}function ZT(t,n,r){return{pointerId:tn(t,-1),startClientX:tn(n),startClientY:tn(r),clientX:tn(n),clientY:tn(r),dragged:!1}}function SS(t,n,r,s){if(!t||t.pointerId!==tn(n,-1))return t;const l={...t,clientX:tn(r,t.clientX),clientY:tn(s,t.clientY)},u=Aw*Aw;return{...l,dragged:t.dragged||ey({clientX:t.startClientX,clientY:t.startClientY},l)>=u}}function JT(t,n,r,s,l){if(!t||t.pointerId!==tn(n,-1))return{kind:"ignore",gesture:t,tap:null};const u=SS(t,n,r,s);return{kind:u.dragged?"drag":"tap",gesture:u,tap:u.dragged?null:{clientX:u.clientX,clientY:u.clientY,at:tn(l)}}}function Nw(t,n){if(!t||!n)return!1;const r=tn(n.at)-tn(t.at);if(r<0||r>Nv)return!1;const s=Tw*Tw;return ey(t,n)<=s}const fh=Object.freeze({shiftKey:Object.freeze(["ShiftLeft","ShiftRight"]),ctrlKey:Object.freeze(["ControlLeft","ControlRight"]),altKey:Object.freeze(["AltLeft","AltRight"]),metaKey:Object.freeze(["MetaLeft","MetaRight"])}),eN=Object.freeze({shiftKey:"ShiftLeft",ctrlKey:"ControlLeft",altKey:"AltLeft",metaKey:"MetaLeft"}),Rw=Object.freeze({OSLeft:"MetaLeft",OSRight:"MetaRight"}),Rv=64,tN=256,Ew=Object.freeze({Backspace:Object.freeze({key:"Backspace",code:"Backspace",keyCode:8,location:0}),Tab:Object.freeze({key:"Tab",code:"Tab",keyCode:9,location:0}),Enter:Object.freeze({key:"Enter",code:"Enter",keyCode:13,location:0}),Escape:Object.freeze({key:"Escape",code:"Escape",keyCode:27,location:0}),PageUp:Object.freeze({key:"PageUp",code:"PageUp",keyCode:33,location:0}),PageDown:Object.freeze({key:"PageDown",code:"PageDown",keyCode:34,location:0}),End:Object.freeze({key:"End",code:"End",keyCode:35,location:0}),Home:Object.freeze({key:"Home",code:"Home",keyCode:36,location:0}),ArrowLeft:Object.freeze({key:"ArrowLeft",code:"ArrowLeft",keyCode:37,location:0}),ArrowUp:Object.freeze({key:"ArrowUp",code:"ArrowUp",keyCode:38,location:0}),ArrowRight:Object.freeze({key:"ArrowRight",code:"ArrowRight",keyCode:39,location:0}),ArrowDown:Object.freeze({key:"ArrowDown",code:"ArrowDown",keyCode:40,location:0}),Delete:Object.freeze({key:"Delete",code:"Delete",keyCode:46,location:0})}),jw=Object.freeze({deleteContentBackward:"Backspace",deleteWordBackward:"Backspace",deleteSoftLineBackward:"Backspace",deleteHardLineBackward:"Backspace",deleteContentForward:"Delete",deleteWordForward:"Delete",deleteSoftLineForward:"Delete",deleteHardLineForward:"Delete",insertLineBreak:"Enter",insertParagraph:"Enter"});function ty(t,n=80){return String(t||"").replace(/[\u0000-\u001f\u007f]/g,"").trim().slice(0,n)}function CS(t){const n=String(t??"");return n===" "?" ":ty(n)}function Ev(t){const n=ty(t);return Object.prototype.hasOwnProperty.call(Rw,n)?Rw[n]:n}function Fg(t={}){const n=CS(t.key),r=Number(t.keyCode??t.which);if(n===" "||n==="Spacebar"||r===32)return"Space";const s=Number.isFinite(Number(t.location))?Math.max(0,Math.min(3,Math.trunc(Number(t.location)))):0,l=s===2?"Right":"Left";return n==="Shift"?`Shift${l}`:n==="Control"?`Control${l}`:n==="Alt"||n==="AltGraph"?`Alt${l}`:n==="Meta"||n==="OS"?`Meta${l}`:n?`Key:${s}:${n}`.slice(0,80):""}function jv(t={}){const n=Ev(t.code);return["Shift","Control","Alt","AltGraph","Meta","OS"].includes(n)?Fg({...t,key:n}):n==="Unidentified"?Fg(t):n||Fg(t)}function Jp(t){for(const[n,r]of Object.entries(fh))if(r.includes(t))return n;return""}function sc(t,n){return fh[n].some(r=>t.has(r))}function Rp(t,n,r={},s="",l=""){for(const u of Object.keys(fh)){const f=r[u]===!0,h=fh[u];if(u===s){if(l==="keyup"&&!f)for(const g of h)n.has(g)||t.delete(g);continue}if(f){!sc(t,u)&&t.size<Rv&&t.add(eN[u]);continue}for(const g of h)n.has(g)||t.delete(g)}}function nN(t,n){if(t.length!==n.size)return!1;let r=0;for(const s of n){if(t[r]!==s)return!1;r+=1}return!0}function Dw(t){for(const n of[...t])Jp(n)||t.delete(n)}function Dv(t){return{shiftKey:sc(t,"shiftKey"),ctrlKey:sc(t,"ctrlKey"),altKey:sc(t,"altKey"),metaKey:sc(t,"metaKey")}}function aN(t={},n={}){return{shiftKey:t.shiftKey===!0||n.shiftKey===!0,ctrlKey:t.ctrlKey===!0||n.ctrlKey===!0,altKey:t.altKey===!0||n.altKey===!0,metaKey:t.metaKey===!0||n.metaKey===!0}}function Ep(t){const n=String(t||""),r=Object.prototype.hasOwnProperty.call(jw,n)?jw[n]:n;return Object.prototype.hasOwnProperty.call(Ew,r)?{...Ew[r],repeat:!1}:null}function rN(t){const n=String(t??"").replace(/\0/g,"");if(!n)return[];const r=[];let s=n;for(;s.length>0;){let l=Math.min(tN,s.length);l<s.length&&/[\uD800-\uDBFF]/.test(s[l-1])&&/[\uDC00-\uDFFF]/.test(s[l])&&(l-=1),r.push(s.slice(0,l)),s=s.slice(l)}return r}function sN(t,n,r){const s=jv(t),l=CS(t.key),u=Number(t.keyCode??t.which),f=Number(t.location);return{type:n,key:l,code:s,keyCode:Number.isFinite(u)?Math.max(0,Math.min(65535,Math.trunc(u))):0,location:Number.isFinite(f)?Math.max(0,Math.min(255,Math.trunc(f))):0,text:l.length===1?l:"",repeat:n==="keydown"&&t.repeat===!0,pressedCodes:[...r],...Dv(r)}}function iN(){const t=new Set,n=new Set,r=()=>({pressedCodes:[...t]});return{event(s={},l=""){if(l!=="keydown"&&l!=="keyup")return null;const u=jv(s);if(!u)return null;const f=Jp(u),h=t.has(u),g=[...t];return f?l==="keydown"?(Rp(t,n,s,f,l),t.size<Rv&&t.add(u)):(n.has(u)||t.delete(u),Rp(t,n,s,f,l)):(Rp(t,n,s),l==="keydown"?t.size<Rv&&t.add(u):t.delete(u)),l==="keyup"&&f==="metaKey"&&!sc(t,"metaKey")&&Dw(t),l==="keydown"&&h&&s.repeat!==!0&&nN(g,t)?null:sN(s,l,t)},modifier(s,l){const u=Ev(s),f=Jp(u);if(!f)return null;const h=n.has(u);return l===h?null:(l?(n.add(u),t.add(u)):(n.delete(u),t.delete(u),f==="metaKey"&&!sc(t,"metaKey")&&Dw(t)),{type:l?"keydown":"keyup",key:f==="metaKey"?"Meta":f==="ctrlKey"?"Control":f==="altKey"?"Alt":"Shift",code:u,keyCode:0,location:u.endsWith("Right")?2:1,text:"",repeat:!1,...r(),...Dv(t)})},reset(s="keyboard-owner-reset",l=!1){const u=t.size>0;return t.clear(),n.clear(),!u&&!l?null:{type:"keyboard.reset",reason:ty(s,120)||"keyboard-owner-reset",pressedCodes:[],shiftKey:!1,ctrlKey:!1,altKey:!1,metaKey:!1,repeat:!1}},isPressed(s={}){const l=typeof s=="string"?Ev(s):jv(s);if(t.has(l))return!0;const u=Jp(l);return!!u&&sc(t,u)},snapshot(){return{...r(),latchedCodes:[...n],...Dv(t)}}}}const kS=64,oN=2;function MS(t){const n=Math.floor(Number(t));return Number.isFinite(n)?Math.max(1,Math.min(kS,n)):1}function ny(t){const n=Math.floor(Number(t));return Number.isFinite(n)?Math.max(0,Math.min(kS-1,n)):0}function AS(t){const n=String(t||"").trim().toLowerCase();return n==="macos"||n==="darwin"||n==="mac"||n==="macosx"||n==="linux"||n.startsWith("linux ")}function lN(t,n,r){const s=String(n||"").trim();if(!s)return t||null;const l=String(r||"").trim();return t&&t.fingerprint===s&&(l?t.sampleId===l:t.sampleId==="")?t:{fingerprint:s,sampleId:l,consecutiveSamples:t?.fingerprint===s?t.consecutiveSamples+1:1}}function TS({platform:t,topologyFingerprint:n,consecutiveTopologySamples:r}){return AS(t)?!!String(n||"").trim()&&Number(r)>=oN:!0}function cN({requestedIndex:t,monitorCount:n,platform:r,topologyFingerprint:s,consecutiveTopologySamples:l}){const u=ny(t),f=MS(n);return u<f||!TS({platform:r,topologyFingerprint:s,consecutiveTopologySamples:l})?u:f-1}function uN(t,n,r){const s=ny(t),l=MS(n);return s<l||AS(r)?s:l-1}function mc(t){const n=Number(t);return Number.isSafeInteger(n)&&n>0?n:0}function Ra(t){return String(t||"").trim()}function Bg(t,n,r={}){return{deviceId:Ra(t),transitionGeneration:mc(n),sessionId:Ra(r.sessionId),streamId:Ra(r.streamId),commandId:Ra(r.commandId),captureGeneration:mc(r.captureGeneration),monitorIndex:Math.max(0,Math.floor(Number(r.monitorIndex)||0))}}function Jn(t,n){return!!t&&!!n&&Ra(t.deviceId)===Ra(n.deviceId)&&mc(t.transitionGeneration)===mc(n.transitionGeneration)}function Iw({deviceId:t,requestTransitionGeneration:n,currentTransitionGeneration:r,actualControlOwner:s}){const l=Ra(t),u=mc(n),f=mc(r);return!!l&&u>0&&u===f&&(!s||Ra(s.deviceId)===l)}function Lw(t,n){const r=Promise.resolve(t).catch(()=>{}).then(n);return{result:r,tail:r.then(()=>{},()=>{})}}function jp(t,n,r){const s=Ra(t);return!s||!n||Ra(n.deviceId)!==s?!1:!r||Ra(r.deviceId)!==s}function Hg(t,n){if(!t||!n)return!1;const r=mc(n.captureGeneration),s=Ra(n.commandId),l=Ra(n.sessionId),u=Ra(n.streamId),f=Number(t.monitorIndex);return!r||!s||!l||!u||!Number.isInteger(f)||f<0?!1:Ra(t.deviceId)===Ra(n.deviceId)&&Ra(t.sessionId)===l&&Ra(t.streamId)===u&&Ra(t.commandId)===s&&mc(t.captureGeneration)===r&&Ra(t.streamPurpose).toLowerCase()==="control"&&f===n.monitorIndex}const dN=820,fN=500,Pw=`(max-width: ${dN}px), (orientation: landscape) and (max-height: ${fN}px) and (pointer: coarse)`,mN="1200px 0px 1800px 0px",pN=960,hN=540,gN=68,_w=24,vN=16;function yN(t,n,r,s){return/iPad|iPhone|iPod/i.test(String(t||""))||n==="MacIntel"&&Number(r)>1||typeof s=="boolean"}function bN(t,n){const r=t&&typeof t=="object"?t:{},s={fps:Math.max(1,Math.floor(Number(r.fps)||1)),maxWidth:Math.max(1,Math.floor(Number(r.maxWidth)||1)),maxHeight:Math.max(1,Math.floor(Number(r.maxHeight)||1)),quality:Math.max(1,Math.min(100,Math.floor(Number(r.quality)||1)))};return n?{...s,maxWidth:Math.min(s.maxWidth,pN),maxHeight:Math.min(s.maxHeight,hN),quality:Math.min(s.quality,gN)}:s}function wN(t,n){return!n||!t||typeof t.closest!="function"?null:t.closest(".desk-stage")}function Ow(t,n,r){return!!(t||n&&r)}function xN({isIos:t,standalone:n,safeAreaTop:r,screenHeight:s,layoutViewportHeight:l}){if(!t||!n)return 0;const u=Number(s),f=Number(l);if((Number.isFinite(u)&&u>0&&Number.isFinite(f)&&f>0?Math.max(0,u-f):0)>=vN)return 0;const g=Number(r);return Number.isFinite(g)&&g>0?Math.max(_w,Math.round(g)-20):_w}function SN(t,n,r,s=!1,l=s){const u=Number(t?.height),f=Number(n),h=Number(t?.offsetTop),g=s&&Number.isFinite(f)&&f>0,y=g?0:Number.isFinite(h)?Math.max(0,Math.round(h)):0,w=g?f:Number.isFinite(u)&&u>0?u:Number.isFinite(f)&&f>0?f:1,b=Number(t?.width),S=Number(r),k=l&&Number.isFinite(S)&&S>0,A=k?S:Number.isFinite(b)&&b>0?b:Number.isFinite(S)&&S>0?S:1,T=Number(t?.offsetLeft);return{height:Math.max(1,Math.round(w)),width:Math.max(1,Math.round(A)),offsetTop:y,offsetLeft:k?0:Number.isFinite(T)?Math.max(0,Math.round(T)):0}}function CN(t,n){const r=Promise.resolve(t).catch(()=>{}).then(n);return{result:r,tail:r.then(()=>{},()=>{})}}function kN(){let t=Promise.resolve(),n=Promise.resolve();const r=s=>{const l=CN(t,s);return t=l.tail,l.result};return{enqueue:r,enqueueStop(s){const l=r(s);return n=l.then(()=>{}),n.catch(()=>{}),l},enqueueStart(s){const l=n;return r(async()=>(await l,s()))}}}function MN(t={}){return Number(t.generation)===Number(t.currentGeneration)&&t.enabled===!0&&String(t.deviceId||"")!==""&&String(t.deviceId||"")===String(t.currentDeviceId||"")&&t.documentVisible===!0&&t.presentationVisible===!0&&String(t.streamId||"")!==""&&String(t.streamId||"")===String(t.currentStreamId||"")}function AN(t={}){const n=t.ok!==!1,r=n&&t.staleOwner===!0;return{confirmed:n&&(r||t.captureStopConfirmed===!0||t.alreadyStopped===!0),staleOwner:r,preserveNewerOwner:r&&(t.retainedNewerOwner===!0||String(t.activeStreamId||"")!=="")}}const ta=Object.freeze({automaticDirectH264:!0,interactiveDirectFps:30,slowWallFps:5,fastWallFps:30,directPopulationThrottle:!1,adaptiveMinimumCurrentSampleMs:750,adaptiveDownshiftStableMs:6e3,adaptiveDownshiftConsecutiveSamples:3,missingDeliveryRatio:.72,recoveryDeliveryRatio:.88,recoveryByteRatio:.52,recoveryGapRatio:.7,controlWallReuseMaxFps:30,controlWallReuseStarvationFactor:1.5,scalableAtlasMinInputFps:8,scalableAtlasMaxInputFps:20,scalableAtlasAggregateInputFps:120,atlasOutputFps:20,directDecodeAcceleration:"prefer-hardware",directLatencyMode:"interactive"});function Iv(t){return t==="slow"?ta.slowWallFps:ta.fastWallFps}function Fw({paintStale:t,lastRecoveryAt:n,now:r,recoveryCooldownMs:s,transportRecoveryAfterMs:l}){if(t!==!0)return"none";const u=Math.max(0,Number(r)||0),f=Math.max(0,Number(n)||0),h=f>0?u-f:Number.POSITIVE_INFINITY;return f>0&&h>=Math.max(1,Number(l)||1)?"recover-transport":f<=0||h>=Math.max(1,Number(s)||1)?"reset-decoder":"wait"}function Bw({lastReceivedAt:t,lastPaintedAt:n,now:r,staleAfterMs:s}){const l=Math.max(0,Number(t)||0);if(l<=0)return!1;const u=Math.max(0,Number(n)||0),f=u>0?u:l;return Math.max(0,Number(r)||0)-f>Math.max(1,Number(s)||1)}function TN(t){return t==="share-files"||t==="agents"}function NN({captureOwnershipActive:t,localFeatureAccess:n,controlSessionDeviceId:r,planAllowed:s,sessionState:l,controlFocusVisible:u,presentationCanvasMounted:f,wallPresentationVisible:h,wallPresentationCanvasMounted:g,decoderOwnerExists:y}){const w=l==="connecting"||l==="active"||l==="warm";return t!==!0||n!==!0||!String(r||"").trim()||s!==!0||!w?!1:y===!0||u===!0&&f===!0||h===!0&&g===!0}function RN({decodeWidth:t,decodeHeight:n,presentationCssWidth:r,presentationCssHeight:s,devicePixelRatio:l,sourceWidth:u,sourceHeight:f}){const h=Math.max(0,Number(t)||0),g=Math.max(0,Number(n)||0),y=Math.max(0,Number(r)||0),w=Math.max(0,Number(s)||0),b=Math.max(1,Math.min(2,Number(l)||1)),S=Math.max(0,Number(u)||0),k=Math.max(0,Number(f)||0);if(h<=0||g<=0||y<=0||w<=0||S<=0||k<=0)return!1;const A=y*b,T=w*b,j=Math.min(1,A/S,T/k),I=Math.max(1,Math.round(S*j)),N=Math.max(1,Math.round(k*j));return h<I*.9||g<N*.9}function EN({cadenceCredit:t,targetFps:n,sourceFps:r,elapsedSincePaintMs:s=0,nowMs:l=0,scheduledPaintAtMs:u=0,force:f=!1}){const h=Math.max(1,Number(n)||1),g=Math.max(1,Number(r)||1);if(h>=g)return{shouldPaint:!0,nextCadenceCredit:0,sourceCadencePassthrough:!0,nextScheduledPaintAtMs:0};const y=Math.max(0,Number(l)||0),w=Math.max(0,Number(u)||0),b=y>0&&w>0,S=1e3/h,k=Math.min(S/3,1e3/g*.5),A=Number.isFinite(Number(t))?Math.max(0,Math.min(g-Number.EPSILON,Number(t))):0;if(f)return{shouldPaint:!0,nextCadenceCredit:A,sourceCadencePassthrough:!1,nextScheduledPaintAtMs:b?w:y>0?y+S:0};const T=A+h,j=T>=g,I=1e3/h*ta.controlWallReuseStarvationFactor,N=!j&&Number(s)>=I,P=b&&y+k>=w,H=b?P||N:j||N;let F=w;return H&&y>0&&(!b||N?F=y+S:(F=w+S,F<=y-S&&(F=y+S))),{shouldPaint:H,nextCadenceCredit:N?0:j&&H?T-g:Math.min(g-Number.EPSILON,T),sourceCadencePassthrough:!1,deadlineForced:N,scheduleSelected:P,nextScheduledPaintAtMs:F}}function jN(t,n){const r=Number.isFinite(Number(n))?Math.max(0,Math.floor(Number(n))):Number.POSITIVE_INFINITY;if(r<=0)return[];const s=(Array.isArray(t)?t:[]).filter(f=>f&&String(f.deviceId||"").trim()).slice().sort((f,h)=>{const g=Number.isFinite(Number(f.slotNumber))?Number(f.slotNumber):Number.MAX_SAFE_INTEGER,y=Number.isFinite(Number(h.slotNumber))?Number(h.slotNumber):Number.MAX_SAFE_INTEGER;return g!==y?g-y:String(f.deviceId).localeCompare(String(h.deviceId))}),l=[],u=new Set;for(const f of s){const h=String(f.deviceId).trim();if(!u.has(h)&&(u.add(h),l.push(h),l.length>=r))break}return l}function DN(t,n){const r=Math.max(0,Math.floor(Number(n)||0));return t===!0&&r>0}function Wf({mode4Enabled:t,directMode4WallEnabled:n,isMac:r}){return"direct"}function IN({mode4Enabled:t,directMode4WallEnabled:n,adaptiveFps:r,directDeviceCount:s,adaptive:l=!0}){return Math.max(1,Math.floor(Number(r)||1))}function LN({directDeviceCount:t,requestedFps:n,measuredFramesPerSecond:r,measuredPaintFramesPerSecond:s,measuredBytesPerSecond:l,maxBytesPerSecond:u,worstReceiveGapMs:f,worstPaintP95Ms:h,maxFrameGapMs:g}){const y=Math.max(1,Math.floor(Number(t)||1)),w=Math.max(1,Number(n)||1),b=Math.max(0,Number(r)||0),S=Math.max(0,Number(s)||0),k=Math.max(0,Number(l)||0),A=Math.max(1,Number(u)||1),T=Math.max(0,Number(f)||0),j=Math.max(0,Number(h)||0),I=Math.max(1,Number(g)||1),N=y*w,P=N>8&&b<N*ta.missingDeliveryRatio,H=N>8&&S<N*ta.missingDeliveryRatio,F=k>A||T>I||P||H,$=b>=N*ta.recoveryDeliveryRatio&&S>=N*ta.recoveryDeliveryRatio&&k<A*ta.recoveryByteRatio&&T<I*ta.recoveryGapRatio&&j<I*ta.recoveryGapRatio;return{expectedFramesPerSecond:N,estimatedMissingFrames:P,estimatedMissingPaints:H,overloaded:F,healthyForRecovery:$}}function PN({receiveSampleMs:t,paintSampleMs:n,currentGenerationVerified:r,frameRequestedFps:s,adaptiveFps:l}){const u=Number(t),f=Number(n),h=Number(s),g=Number(l);return r===!0&&Number.isFinite(u)&&u>=ta.adaptiveMinimumCurrentSampleMs&&Number.isFinite(f)&&f>=ta.adaptiveMinimumCurrentSampleMs&&Number.isFinite(h)&&h>0&&h===g}function _N({deviceCount:t,targetFps:n,adaptive:r=!0}){const s=Math.max(1,Math.floor(Number(t)||1)),l=Math.max(1,Math.min(ta.scalableAtlasMaxInputFps,Math.floor(Number(n)||ta.scalableAtlasMaxInputFps)));if(!r)return l;const u=Math.max(ta.scalableAtlasMinInputFps,Math.min(ta.scalableAtlasMaxInputFps,Math.floor(ta.scalableAtlasAggregateInputFps/s)));return Math.min(l,u)}function ON(t,n){return{acceleration:ta.directDecodeAcceleration,latencyMode:ta.directLatencyMode}}const mh=0,xu=100,FN=25,BN=50,Hw=300,HN=560;function xm(t){return Number.isFinite(t)?Math.min(xu,Math.max(mh,Math.round(t))):xu}function zN(t){const n=xm(t);return n===mh?"list":n<BN?"medium":"large"}function $N(t){const r=(Math.max(1,xm(t))-1)/(xu-1);return Math.round(Hw+r*(HN-Hw))}const uu={revision:0,settings:{connection:{showThisComputer:!1},security:{accessMode:"trusted-only"},control:{allowKeyboardMouse:!0,allowRemoteRestart:!1},filesAudio:{allowFileTransfer:!0,allowRemoteAudio:!0,rollingBufferEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0}}},zw=[{id:"connection",label:"Connection",icon:bh},{id:"remote-access",label:"Remote Access",icon:Ea},{id:"capture-audio",label:"Capture & Audio",icon:uv},{id:"agent",label:"Agent",icon:lc}];function Zf(t,n){return t?.settings?.[n]||uu.settings[n]||{}}function $w(t,n){return{...t,settings:{...t.settings,[n.section]:{...Zf(t,n.section),[n.key]:n.value}}}}function zg(t){return{revision:Number(t.revision||0),updatedAt:t.updatedAt,settings:t.settings}}function ec({icon:t,title:n,description:r,children:s,recommended:l=!1}){return o.jsxs("div",{className:"product-setting-row",children:[o.jsx("div",{className:"product-setting-control",children:s}),t&&o.jsx("span",{className:"product-setting-icon",children:o.jsx(t,{size:17})}),o.jsxs("div",{className:"product-setting-copy",children:[o.jsx("strong",{children:n}),l&&o.jsx("em",{children:"Recommended"}),o.jsx("small",{children:r})]})]})}function Nd({checked:t,onChange:n,label:r}){return o.jsxs("label",{className:"product-switch",children:[o.jsx("input",{"aria-label":r,type:"checkbox",checked:t,onChange:s=>n(s.target.checked)}),o.jsx("span",{})]})}function Uw({value:t,onChange:n,options:r,label:s}){return o.jsx("select",{"aria-label":s,value:String(t),onChange:l=>n(l.target.value),children:r.map(([l,u])=>o.jsx("option",{value:l,children:u},l))})}function UN({hubUrl:t="",mobileLayout:n=!1,runtimeRole:r="hub",runtimeDeviceId:s="",sessionAccessToken:l="",showThisComputerSetting:u=!0,onShowThisComputerChange:f,initialTab:h="connection",pin:g,agent:y,captureGallery:w,desktopUpdate:b}){const[S,k]=d.useState(()=>n&&h==="connection"?"remote-access":h),[A,T]=d.useState(null),[j,I]=d.useState("loading"),[N,P]=d.useState(""),[H,F]=d.useState("idle"),[$,D]=d.useState(""),K=d.useRef(null),z=d.useRef(null),q=d.useRef([]),W=d.useRef(Promise.resolve()),Y=d.useRef(0),V=d.useRef(0);d.useEffect(()=>{const de=++V.current;let Be=!0;return q.current=[],z.current=null,K.current=null,W.current=Promise.resolve(),I("loading"),lt("/api/settings",void 0,t).then(Ve=>{if(!Be||de!==V.current)return;const Je=zg(Ve);z.current=Je,K.current=Je,T(Je),I("saved")}).catch(Ve=>{!Be||de!==V.current||(P(Ve instanceof Error?Ve.message:String(Ve)),z.current=uu,K.current=uu,T(uu),I("failed"))}),()=>{Be=!1}},[t]);const he=async(de,Be,Ve)=>{const Je={id:++Y.current,section:de,key:Be,value:Ve},Qe=V.current;q.current.push(Je);const yt=$w(K.current||z.current||uu,Je);K.current=yt,T(yt),I("saving"),P(""),W.current=W.current.then(async()=>{if(Qe!==V.current)return;let ne=null,me=null;for(let ge=0;ge<2&&!ne;ge+=1){const Ue=z.current||uu;try{const Me=await lt("/api/settings",{method:"PATCH",body:JSON.stringify({revision:Ue.revision,[Je.section]:{[Je.key]:Je.value}})},t);ne=zg(Me)}catch(Me){if(me=Me,ge!==0||!String(Me instanceof Error?Me.message:Me).startsWith("409 "))break;try{const rt=await lt("/api/settings",void 0,t);if(Qe!==V.current)return;z.current=zg(rt)}catch(rt){me=rt;break}}}if(Qe!==V.current)return;q.current=q.current.filter(ge=>ge.id!==Je.id),ne&&(z.current=ne);const Ge=z.current||uu,Se=q.current.reduce($w,Ge);K.current=Se,T(Se),ne?(P(""),I(q.current.length>0?"saving":"saved")):(I(q.current.length>0?"saving":"failed"),P(me instanceof Error?me.message:String(me||"Settings could not be saved.")))}),await W.current},ee=(de,Be)=>Ve=>{he(de,Be,Ve)},U=async()=>{if(r!=="hub"||!s||!l){F("failed"),D("Sign in to this Hub before changing its runtime role.");return}F("changing"),D("");try{const de=await lt("/api/runtime/status",void 0,t);await lt("/api/runtime/role",{method:"POST",headers:{Authorization:`Bearer ${l}`},body:JSON.stringify({role:"client"})},t),F("accepted"),await I0({baseUrl:t,targetRole:"client",previousRuntimePid:Number(de.runtimePid||0),allowedStates:["running","waiting-auth"]}),CA(5179)}catch(de){F("failed"),D(de instanceof Error?de.message:String(de))}},L=Zf(A,"security"),le=Zf(A,"control"),ve=Zf(A,"filesAudio"),J=Zf(A,"connection"),Ae=`settings-panel-${S}`,ce=n?zw.filter(de=>de.id!=="connection"):zw;d.useEffect(()=>{n&&S==="connection"&&k("remote-access")},[S,n]),d.useEffect(()=>{A&&f?.(!!J.showThisComputer)},[J.showThisComputer,f,A]);const Te=o.jsxs("div",{className:"settings-tab-content product-settings-content",children:[g,b,u&&o.jsxs("section",{className:"settings-section-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Hub computer list"}),o.jsx("h3",{children:"This computer"})]}),o.jsx(nr,{size:20})]}),o.jsx(ec,{icon:nr,title:"Show this computer",description:"Show this Hub computer in its own Wall and computer lists. It stays available from other computers and the mobile app when hidden.",children:o.jsx(Nd,{checked:!!J.showThisComputer,onChange:ee("connection","showThisComputer"),label:"Show this computer"})})]}),o.jsxs("section",{className:"settings-section-card runtime-role-settings",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Runtime role"}),o.jsx("h3",{children:"Use this computer as a Client"})]}),o.jsx(g0,{size:20})]}),o.jsx("p",{className:"settings-help",children:"Stop hosting from this computer and reconnect it to the selected Hub."}),H==="accepted"?o.jsx("p",{className:"settings-help runtime-role-success",children:"LiveDesk is restarting as Client."}):$?o.jsx("p",{className:"settings-help runtime-role-error",role:"alert",children:$}):null,o.jsx("button",{className:"settings-reset",onClick:()=>{U()},disabled:H==="changing"||r!=="hub",type:"button",children:H==="changing"?"Switching role...":"Switch this computer to Client"})]})]}),Fe=o.jsxs("div",{className:"settings-tab-content product-settings-content",children:[o.jsxs("section",{className:"settings-section-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Remote access"}),o.jsx("h3",{children:"Who may connect?"})]}),o.jsx(el,{size:20})]}),o.jsx(ec,{icon:Ea,title:"Access mode",description:"Choose the default permission boundary for remote sessions.",recommended:!0,children:o.jsx(Uw,{value:String(L.accessMode),onChange:ee("security","accessMode"),label:"Access mode",options:[["trusted-only","Trusted devices only"],["block-remote-access","Block remote access"]]})})]}),o.jsxs("section",{className:"settings-section-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Session permissions"}),o.jsx("h3",{children:"What may remote users do?"})]}),o.jsx(nr,{size:20})]}),o.jsx(ec,{icon:nr,title:"Keyboard and mouse control",description:"Allow Control to send keyboard and pointer input.",recommended:!0,children:o.jsx(Nd,{checked:!!le.allowKeyboardMouse,onChange:ee("control","allowKeyboardMouse"),label:"Keyboard and mouse control"})}),o.jsx(ec,{icon:v0,title:"Power actions",description:"Allow confirmed sleep, restart, and shut down commands from the Hub.",children:o.jsx(Nd,{checked:!!le.allowRemoteRestart,onChange:ee("control","allowRemoteRestart"),label:"Power actions"})}),o.jsx(ec,{icon:uv,title:"File transfer",description:"Allow files to be delivered to connected computers.",children:o.jsx(Nd,{checked:!!ve.allowFileTransfer,onChange:ee("filesAudio","allowFileTransfer"),label:"File transfer"})}),o.jsx(ec,{icon:Ld,title:"Remote audio",description:"Allow sound capture from connected computers.",children:o.jsx(Nd,{checked:!!ve.allowRemoteAudio,onChange:ee("filesAudio","allowRemoteAudio"),label:"Remote audio"})})]})]}),$e=o.jsxs("div",{className:"settings-tab-content product-settings-content",children:[o.jsxs("section",{className:"settings-section-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Capture"}),o.jsx("h3",{children:"Recording defaults"})]}),o.jsx(uv,{size:20})]}),o.jsx(ec,{icon:Ld,title:"Keep a Last 30s buffer",description:"Keep recent video in memory until you explicitly save it.",children:o.jsx(Nd,{checked:!!ve.rollingBufferEnabled,onChange:ee("filesAudio","rollingBufferEnabled"),label:"Keep a Last 30s buffer"})}),o.jsx(ec,{icon:Ld,title:"Timelapse interval",description:"Choose how often a timelapse frame is captured.",children:o.jsx(Uw,{value:Number(ve.timelapseIntervalSeconds),onChange:de=>ee("filesAudio","timelapseIntervalSeconds")(Number(de)),label:"Timelapse interval",options:[["5","5 seconds"],["10","10 seconds"],["30","30 seconds"],["60","60 seconds"]]})})]}),w]}),Ze=S==="connection"?Te:S==="remote-access"?Fe:S==="capture-audio"?$e:y;return o.jsxs("section",{className:"settings-page",children:[o.jsx("div",{className:"settings-page-tabs",role:"tablist","aria-label":"LiveDesk settings",children:ce.map(({id:de,label:Be,icon:Ve})=>o.jsxs("button",{className:S===de?"active":"",id:`settings-tab-${de}`,role:"tab","aria-selected":S===de,"aria-controls":`settings-panel-${de}`,tabIndex:S===de?0:-1,onClick:()=>k(de),type:"button",children:[o.jsx(Ve,{size:16}),Be]},de))}),j==="saving"&&o.jsx("div",{className:"product-save-state",role:"status",children:"Saving settings..."}),N&&o.jsx("div",{className:"agent-settings-alert error",role:"alert",children:N}),o.jsx("section",{className:"settings-page-panel",id:Ae,role:"tabpanel","aria-labelledby":`settings-tab-${S}`,tabIndex:0,children:Ze})]})}function qN({children:t}){return o.jsx("div",{className:"settings-tab-content",children:t})}const qw={enabled:!1};function Ww(t){return{enabled:t?.enabled===!0}}async function WN(t,n,r){let s=null;for(let l=0;l<2;l+=1){const u=await lt("/api/settings",{signal:r},n);if(u.settings.agent?.enabled===t)return;try{await lt("/api/settings",{method:"PATCH",signal:r,body:JSON.stringify({revision:u.revision,agent:{enabled:t}})},n);return}catch(f){if(s=f,l!==0||!String(f instanceof Error?f.message:f).startsWith("409 "))throw f}}throw s}function GN({hubUrl:t,showToast:n}){const[r,s]=d.useState(qw),[l,u]=d.useState(null),[f,h]=d.useState(""),[g,y]=d.useState(""),[w,b]=d.useState(""),S=d.useRef(0),k=d.useRef(null);d.useEffect(()=>{let $=!0;k.current?.abort();const D=new AbortController;k.current=D;const K=++S.current;return u(null),s(qw),h(""),b(""),y(""),lt("/api/settings/agent",{signal:D.signal},t).then(z=>{!$||D.signal.aborted||K!==S.current||(u(z.settings),s(Ww(z.settings)))}).catch(z=>{$&&!D.signal.aborted&&K===S.current&&b(z instanceof Error?z.message:String(z))}),()=>{$=!1,D.abort(),k.current===D&&(k.current=null)}},[t]);const A=($,D)=>s(K=>({...K,[$]:D})),T=$=>{u($),s(Ww($))},j=()=>({generation:S.current,controller:k.current}),I=$=>$.generation===S.current&&$.controller!==null&&$.controller===k.current&&!$.controller.signal.aborted,N=async()=>{if(!l){b("Agent settings are not available yet.");return}const $=j();if(I($)){h("save"),b(""),y("");try{if(await WN(r.enabled,t,$.controller.signal),!I($))return;const D=await lt("/api/settings/agent",{signal:$.controller.signal},t);if(!I($))return;T(D.settings),y("Codex Agent settings saved.")}catch(D){I($)&&b(D instanceof Error?D.message:String(D))}finally{I($)&&h("")}}},P=async()=>{const $=j();if(I($)){h("test"),b(""),y("");try{const D=await lt("/api/settings/agent/test",{method:"POST",signal:$.controller.signal,body:JSON.stringify({})},t);if(!I($))return;const K=await lt("/api/settings/agent",{signal:$.controller.signal},t);if(!I($))return;T(K.settings);const z=Number.isFinite(D.connection?.latencyMs)?Math.max(0,Math.round(D.connection.latencyMs)):null;n(`Codex Agent connection verified${z!==null?` in ${z} ms.`:"."}`,"success")}catch(D){I($)&&b(D instanceof Error?D.message:String(D))}finally{I($)&&h("")}}},H=l?.codexInstallation==="installed"&&l.codexAuth==="signed-in",F=l!==null;return o.jsxs("div",{className:"settings-tab-content agent-settings-content",children:[o.jsx("section",{className:"settings-section-card agent-enable-card",children:o.jsxs("label",{className:"settings-toggle agent-enable-toggle",children:[o.jsx("input",{type:"checkbox",checked:r.enabled,onChange:$=>A("enabled",$.target.checked),disabled:!F||f!==""}),o.jsx("span",{children:"Enable Codex Agent"})]})}),w&&o.jsx("div",{className:"agent-settings-alert error",role:"alert",children:w}),g&&o.jsx("div",{className:"agent-settings-alert success",role:"status",children:g}),o.jsxs("section",{className:"settings-section-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Connection"}),o.jsx("h3",{children:"Codex SDK / CLI"})]}),o.jsx(Ea,{size:20})]}),o.jsxs("div",{className:"agent-connection-row",children:[o.jsx("span",{className:`agent-connection-dot ${H?"connected":l?.codexAuth==="not-signed-in"?"unavailable":""}`}),o.jsx("span",{children:l?.codexInstallation==="not-installed"?"Codex SDK not installed":l?.codexAuth==="signed-in"?"Codex CLI signed in":l?.codexAuth==="not-signed-in"?"Codex CLI sign-in required":"Codex status not tested"}),o.jsxs("button",{className:"settings-reset",onClick:()=>{P()},disabled:f!=="",type:"button",children:[o.jsx(Gk,{size:15})," ",f==="test"?"Testing":"Test connection"]})]}),o.jsxs("p",{className:"settings-help",children:[o.jsx(Vk,{size:12})," The Hub uses the installed Codex SDK / CLI to plan approved commands and run them through LiveDesk Agent tools on selected computers."]})]}),o.jsx("div",{className:"settings-action-row agent-settings-actions",children:o.jsxs("button",{className:"text-button primary",onClick:()=>{N()},disabled:!F||f!=="",type:"button",children:[o.jsx(Kk,{size:15})," ",f==="save"?"Saving":"Save Agent settings"]})})]})}new Date().valueOf();function po(t){const[n,r]=d.useState(t),s=d.useRef(t);return d.useEffect(()=>{if(s.current!==t){if(Array.isArray(s.current)&&Array.isArray(t)&&s.current.length===0&&t.length===0)return;s.current=t,r(t)}},[t]),[n,r]}function ay(t,n){return typeof t=="function"?typeof n=="object"?t(n):t():t}function Hd(t,n="data-id"){let r=t;for(!r.tagName&&t.target&&(r=t.target);r;){if(r.getAttribute&&r.getAttribute(n))return r;r=r.parentNode}return null}function VN(t,n="data-id"){const r=Hd(t,n);return r?r.getAttribute(n):null}function vm(t,n="data-id"){const r=Hd(t,n);return r?Rh(r,n):null}function Rh(t,n="data-id"){const r=t.getAttribute(n);return r?KN(r):null}function ar(t){return typeof t=="string"?":"+t:t}function KN(t){if(t.startsWith(":"))return t.substring(1);const n=t*1;return isNaN(n)?t:n}function QN(){return{detect:()=>!0,addEvent:function(t,n,r){return t.addEventListener(n,r),()=>t.removeEventListener(n,r)},addGlobalEvent:function(t,n){return document.addEventListener(t,n),()=>document.removeEventListener(t,n)},getTopNode:function(){return window.document.body}}}var gs=QN();function ry(t){Object.assign(gs,t)}function Gw(t,n,r){function s(l){const u=Hd(l);if(!u)return;const f=Rh(u);if(typeof n=="function")return n(f,l);let h,g=l.target;for(;g!=u;){if(h=g.dataset?g.dataset.action:null,h&&n[h]){n[h](f,l);return}g=g.parentNode}n[r]&&n[r](f,l)}gs.addEvent(t,r,s)}function zd(t,n){Gw(t,n,"click"),n.dblclick&&Gw(t,n.dblclick,"dblclick")}function YN(t,n){for(let r=t.length-1;r>=0;r--)if(t[r]===n){t.splice(r,1);break}}function XN(t,n,r){for(let s=0;s<nl.length;s++){if(s===r)continue;const l=nl[s],u=l.props.parent?.();if(u&&t.contains(u)&&l.node.contains(n))return!0}return!1}var NS=new Date,ph=!1,Dp=[],nl=[],Vw=t=>{const n=t.target;if(ph||!n.isConnected){ph=!1;return}for(let r=nl.length-1;r>=0;r--){const{node:s,date:l,props:u}=nl[r];if(!(l>NS)&&!s.contains(n)&&s!==n&&(XN(s,n,r)||(u.callback&&u.callback(t),u.modal||t.defaultPrevented)))break}},ZN=t=>{NS=new Date,ph=!0;for(let n=nl.length-1;n>=0;n--){const{node:r}=nl[n];if(!r.contains(t.target)&&r!==t.target){ph=!1;break}}};function ho(t,n){Dp.length||(Dp=[gs.addGlobalEvent("click",Vw,t),gs.addGlobalEvent("contextmenu",Vw,t),gs.addGlobalEvent("mousedown",ZN,t)]),typeof n!="object"&&(n={callback:n});const r={node:t,date:new Date,props:n};return nl.push(r),{destroy(){YN(nl,r),nl.length||(Dp.forEach(s=>s()),Dp=[])}}}var Ip=t=>t.indexOf("bottom")!==-1,Lp=t=>t.indexOf("left")!==-1,Pp=t=>t.indexOf("right")!==-1,$g=t=>t.indexOf("top")!==-1,Kw=t=>t.indexOf("fit")!==-1,Gf=t=>t.indexOf("overlap")!==-1,JN=t=>t.split("-").every(n=>["center","fit"].indexOf(n)>-1),eR=t=>{const n=t.match(/(start|center|end)/);return n?n[0]:null};function tR(t,n){let r=0;const s=gs.getTopNode(t);for(;t&&t!==s;){const l=getComputedStyle(t).position;if((l==="absolute"||l==="relative"||l==="fixed")&&(r=parseInt(getComputedStyle(t).zIndex)||0),t=t.parentNode,t===n)break}return r}var Ta,Rr,Vf,gr;function RS(t,n,r="bottom",s=0,l=0){if(!t)return null;Ta=s,Rr=l,Vf="auto";let u=0,f=0,h=r;const g=ES(t),y=Gf(r)?gs.getTopNode(t):g;if(!g)return null;const w=g.getBoundingClientRect(),b=t.getBoundingClientRect(),S=y.getBoundingClientRect(),k=window.getComputedStyle(y),A={left:0,top:0,bottom:0,right:0};for(const H in A){const F=`border-${H}-width`;A[H]=parseFloat(k.getPropertyValue(F))}if(n){const H=tR(n,g);u=Math.max(H+1,20)}if(n){if(gr=n.getBoundingClientRect(),Kw(r)&&(Vf=gr.width+"px"),r!=="point")if(JN(r))Kw(r)?Ta=0:(Ta=S.width/2,f=1),Rr=(S.height-b.height)/2;else{const H=Gf(r)?0:1;Ta=Pp(r)?gr.right+H:gr.left-H,Rr=Ip(r)?gr.bottom+1:gr.top;const F=eR(r);F&&(Pp(r)||Lp(r)?F==="center"?Rr-=(b.height-gr.height)/2:F==="end"&&(Rr-=b.height-gr.height):(Ip(r)||$g(r))&&(F==="center"?Ta-=(b.width-gr.width)/2:F==="end"&&(Ta-=b.width-gr.width),Gf(r)||(Ta+=1)))}}else gr={left:s,right:s,top:l,bottom:l};const T=(Lp(r)||Pp(r))&&(Ip(r)||$g(r));Lp(r)&&(f=2);const j=Ta-b.width-S.left;n&&Lp(r)&&!T&&j<0&&(Ta=gr.right,f=0,h=h.replace("left","right"));const I=Ta+b.width*(1-f/2)-S.right;if(I>0)if(!Pp(r))Ta=S.right-A.right-b.width;else{const H=gr.left-S.x-b.width;n&&!T&&H>=0?(Ta=gr.left-b.width,h=h.replace("right","left")):Ta-=I+A.right}f&&(Ta=Math.round(Ta-b.width*f/2));const N=j<0||I>0||!T;$g(r)&&(Rr=gr.top-b.height,n&&Rr<S.y&&N&&(Rr=gr.bottom,h=h.replace("top","bottom")));const P=Rr+b.height-S.bottom;return P>0&&(n&&Ip(r)&&N?(Rr-=b.height+gr.height+1,h=h.replace("bottom","top")):Rr-=P+A.bottom),Ta-=w.left+A.left,Rr-=w.top+A.top,Ta=(Gf(r)?Ta:Math.max(Ta,0))+y.scrollLeft,Rr=(Gf(r)?Rr:Math.max(Rr,0))+y.scrollTop,Vf=Vf||"auto",{at:h,x:Ta,y:Rr,z:u,width:Vf}}function ES(t){const n=gs.getTopNode(t);for(t&&(t=t.parentElement);t;){const r=getComputedStyle(t).position;if(t===n||r==="relative"||r==="absolute"||r==="fixed")return t;t=t.parentNode}return null}function nR(t){const n=[];let r=t;const s=gs.getTopNode(t);for(;r&&r!==s&&!r.getAttribute("data-wx-portal-root");)getComputedStyle(r).position==="absolute"&&n.push(r),r=r.parentNode;return n}var Qw=new Date().valueOf();function sy(){return Qw+=1,Qw}function jr(t){return t<10?"0"+t:t.toString()}function aR(t){const n=jr(t);return n.length==2?"0"+n:n}function jS(t){const n=Math.floor(t/11)*11;return{start:n,end:n+11}}function Ug(t){const n=(t.getDay()+6)%7,r=new Date(t.valueOf());r.setDate(t.getDate()+(3-n)),r.setHours(0,0,0,0);const s=new Date(r.getFullYear(),0,1),l=Math.round((r.getTime()-s.getTime())/864e5);return 1+Math.floor(l/7)}var Yw=["",""];function rR(t,n,r){switch(t){case"%d":return jr(n.getDate());case"%m":return jr(n.getMonth()+1);case"%j":return n.getDate();case"%n":return n.getMonth()+1;case"%y":return jr(n.getFullYear()%100);case"%Y":return n.getFullYear();case"%D":return r.dayShort[n.getDay()];case"%l":return r.dayFull[n.getDay()];case"%M":return r.monthShort[n.getMonth()];case"%F":return r.monthFull[n.getMonth()];case"%h":return jr((n.getHours()+11)%12+1);case"%g":return(n.getHours()+11)%12+1;case"%G":return n.getHours();case"%H":return jr(n.getHours());case"%i":return jr(n.getMinutes());case"%a":return((n.getHours()>11?r.pm:r.am)||Yw)[0];case"%A":return((n.getHours()>11?r.pm:r.am)||Yw)[1];case"%s":return jr(n.getSeconds());case"%S":return aR(n.getMilliseconds());case"%W":return jr(Ug(n));case"%w":{const s=r.weekStart??1;if(s===1)return jr(Ug(n));const l=(n.getDay()-s+7)%7,u=(1-s+7)%7,f=new Date(n.valueOf());return f.setDate(n.getDate()+(u-l)),jr(Ug(f))}case"%c":{let s=n.getFullYear()+"";return s+="-"+jr(n.getMonth()+1),s+="-"+jr(n.getDate()),s+="T",s+=jr(n.getHours()),s+=":"+jr(n.getMinutes()),s+=":"+jr(n.getSeconds()),s}case"%Q":return Math.floor(n.getMonth()/3)+1;default:return t}}var sR=/%[a-zA-Z]/g;function _d(t,n){return typeof t=="function"?t:function(r){return r?(r.getMonth||(r=new Date(r)),t.replace(sR,s=>rR(s,r,n))):""}}function Xw(t){return t&&typeof t=="object"&&!Array.isArray(t)}function Lv(t,n){for(const r in n){const s=n[r];Xw(t[r])&&Xw(s)?t[r]=Lv({...t[r]},n[r]):t[r]=n[r]}return t}function Sm(t){return{getGroup(n){const r=t[n];return s=>r&&r[s]||s},getRaw(){return t},extend(n,r){if(!n)return this;let s;return r?s=Lv({...n},t):s=Lv({...t},n),Sm(s)}}}var iR=A0();const oR="en-US",lR={monthFull:["January","February","March","April","May","June","July","August","September","October","November","December"],monthShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayFull:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],hours:"Hours",minutes:"Minutes",done:"Done",clear:"Clear",today:"Today",am:["am","AM"],pm:["pm","PM"],weekStart:0,clockFormat:24},cR={ok:"OK",cancel:"Cancel",select:"Select","No data":"No data","Rows per page":"Rows per page","Total pages":"Total pages"},uR={timeFormat:"%H:%i",dateFormat:"%m/%d/%Y",monthYearFormat:"%F %Y",yearFormat:"%Y"},DS={core:cR,calendar:lR,formats:uR,lang:oR},iy=d.createContext(""),IS=d.createContext({}),Ni=d.createContext(null),LS=d.createContext(null),sr=Object.freeze(Object.defineProperty({__proto__:null,fieldId:LS,helpers:IS,i18n:Ni,theme:iy},Symbol.toStringTag,{value:"Module"}));function PS(t){const n=d.useContext(LS),[r]=d.useState(()=>t||n||sy());return r}function um({type:t="",css:n="",icon:r="",disabled:s=!1,title:l="",tooltip:u,text:f="",children:h,onClick:g}){const y=d.useMemo(()=>{let b=t?t.split(" ").filter(S=>S!=="").map(S=>"wx-"+S).join(" "):"";return n+(n?" ":"")+b},[t,n]),w=b=>{g&&g(b)};return o.jsxs("button",{title:l,className:`wx-2ZWgb4 wx-button ${y} ${r&&!h?"wx-icon":""}`,disabled:s,onClick:w,"data-tooltip-text":u,children:[r&&o.jsx("i",{className:"wx-2ZWgb4 "+r}),h||f||" "]})}function dR({id:t,label:n="",inputValue:r="",value:s=!1,onChange:l,disabled:u=!1,css:f=""}){const h=PS(t),[g,y]=po(s),w=({target:b})=>{const S=b.checked;y(S),l&&l({value:S,inputValue:r})};return o.jsxs("div",{className:`wx-2IvefP wx-checkbox ${f}`,children:[o.jsx("input",{type:"checkbox",id:h,disabled:u,className:"wx-2IvefP wx-check",checked:g,value:r,onChange:w}),o.jsxs("label",{htmlFor:h,className:"wx-2IvefP wx-label",children:[o.jsx("span",{className:"wx-2IvefP wx-before"}),n&&o.jsx("span",{className:"wx-2IvefP wx-after",children:n})]})]})}function oy({theme:t="",target:n,children:r}){const s=d.useRef(null),l=d.useRef(null),[u,f]=d.useState(null);s.current||(s.current=document.createElement("div"));const h=d.useContext(iy);return d.useEffect(()=>{f(n||fR(l.current)||gs.getTopNode(l.current))},[l.current]),o.jsxs(o.Fragment,{children:[o.jsx("span",{ref:l,style:{display:"none"}}),l.current&&u?iR.createPortal(o.jsx("div",{className:`wx-3ZWsT0 wx-${t||h}-theme`,children:r}),u):null]})}function fR(t){const n=gs.getTopNode(t);for(;t&&t!==n&&!t.getAttribute("data-wx-portal-root");)t=t.parentNode;return t}function mR({left:t=0,top:n=0,at:r="bottom",parent:s=null,width:l="auto",css:u="",onCancel:f,children:h,trackScroll:g=!1}){const[y,w]=d.useState(0),[b,S]=d.useState(0),[k,A]=d.useState("auto"),[T,j]=d.useState(!1),I=d.useRef(null),N=d.useRef(null),P=d.useRef(f);d.useEffect(()=>{P.current=f},[f]);function H($){return s&&(l+"").indexOf("%")>-1?l.replace(/(\d+)%/,(D,K)=>(K=K*s.offsetWidth/100+"px",l.replace(D,K))):l&&l!=="auto"?l:$}const F=d.useCallback(()=>{if(!I.current)return;const $=RS(I.current,s,r,t,n);$&&(w($.x),S($.y),A(H($.width)))},[I,s,r,t,n,l]);return d.useLayoutEffect(()=>{const $=K=>{P.current&&K.target!==N.current&&I.current&&!I.current.contains(K.target)&&P.current(K)};let D;return requestAnimationFrame(()=>{F(),j(!0),g&&I.current&&(N.current=ES(I.current),N.current&&N.current.addEventListener("scroll",$,!0)),s&&(D=new ResizeObserver(F),D.observe(s))}),()=>{g&&N.current&&N.current.removeEventListener("scroll",$,!0),D?.disconnect()}},[]),d.useLayoutEffect(()=>{F()},[s,r,t,n]),d.useEffect(()=>{const $=D=>{P.current&&P.current(D)};if(I.current)return ho(I.current,{callback:$,parent:()=>s}).destroy},[s]),o.jsx("div",{ref:I,className:["wx-37M6Fj","wx-popup",u].filter(Boolean).join(" "),style:{position:"absolute",visibility:T?"visible":"hidden",top:b+"px",left:y+"px",width:k},children:h})}function pR({position:t="bottom",align:n="start",autoFit:r=!0,onCancel:s=null,width:l="100%",css:u="",children:f}){const h=d.useRef(null),[g,y]=d.useState(t),[w,b]=d.useState(n),S=d.useRef(s);return d.useEffect(()=>{S.current=s},[s]),d.useEffect(()=>{if(r){const k=h.current;if(k){const A=k.getBoundingClientRect(),T=document.body.getBoundingClientRect();A.right>=T.right&&b("end"),A.bottom>=T.bottom&&y("top")}}},[]),d.useEffect(()=>{if(h.current){const k=A=>{S.current&&S.current(A)};return ho(h.current,k).destroy}},[]),o.jsx("div",{ref:h,className:["wx-dropdown",`wx-${g}-${w}`,u||"","wx-aaaVytZW"].filter(Boolean).join(" "),style:{width:l},children:f})}function ly({position:t="bottom",align:n="start",autoFit:r=!0,inline:s=!1,onCancel:l,width:u="100%",children:f,...h}){const[g,y]=d.useState(void 0),w=d.useRef(null),b=d.useMemo(()=>`${t}-${n}`,[t,n]);return d.useLayoutEffect(()=>{w.current&&y(w.current.parentNode)},[]),o.jsxs(o.Fragment,{children:[g&&(s?o.jsx(pR,{onCancel:l,position:t,align:n,autoFit:r,width:u,...h,children:f}):o.jsx(oy,{children:o.jsx(mR,{parent:g,at:b,onCancel:l,width:u,...h,children:f})})),o.jsx("span",{ref:w,className:"wx-portal-node wx-32GZ52"})]})}function Eh(){return Sm(DS)}function hR(){let t=null,n=!1,r=!1,s,l,u,f;const h=(b,S,k,A,T)=>{s=b,l=S,u=k,f=A,r=T},g=b=>{t=b,n=t!==null,u(t)},y=(b,S)=>{if(!r&&b!==null&&s){const k=s.querySelectorAll(".wx-list > .wx-item")[b];k&&(k.scrollIntoView({block:"nearest"}),S&&S.preventDefault())}},w=(b,S)=>{const k=b===null?null:Math.max(0,Math.min(t+b,l.length-1));k!==t&&(g(k),s?y(k,S):requestAnimationFrame(()=>y(k,S)))};return{move:b=>{const S=vm(b),k=l.findIndex(A=>A.id===S);k!==t&&g(k)},keydown:(b,S)=>{switch(b.code){case"Enter":n?f():g(0);break;case"Space":n||g(0);break;case"Escape":u(t=null);break;case"Tab":u(t=null);break;case"ArrowDown":w(n?1:S||0,b);break;case"ArrowUp":w(n?-1:S||0,b);break}},init:h,navigate:w}}const Zw=10,gR=d.memo(function({data:t,checkboxes:n,itemTemplate:r,value:s}){return o.jsxs(o.Fragment,{children:[n&&o.jsx(dR,{id:t.id,css:"wx-list-checkbox",value:s&&s.includes(t.id)}),r?ay(r,{option:t}):t.label]})});function Jw({visibleItems:t,visibleRange:n,navIndex:r,checkboxes:s,itemTemplate:l,value:u,measureRefCallback:f}){return t.map((h,g)=>{const y=n.start+g;return o.jsx("div",{ref:g===0?f:void 0,className:`wx-233fr7 wx-item ${y===r?"wx-focus":""}`,"data-id":h.id,children:o.jsx(gR,{data:h,checkboxes:s,itemTemplate:l,value:u})},h.id)})}function jh({items:t=[],children:n,onSelect:r,onReady:s,virtualized:l=!1,checkboxes:u,multiselect:f,value:h,...g}){const y=d.useRef(),w=d.useRef(!1),b=d.useRef(hR()),[S,k]=d.useState(null),A=d.useRef(S),[T,j]=d.useState(0),[I,N]=d.useState(24),P=d.useRef(!1),H=(d.useContext(Ni)||Eh()).getGroup("core"),F=d.useRef(t);d.useEffect(()=>{F.current=t},[t]);const $=d.useRef(h);d.useEffect(()=>{$.current=h},[h]);const D=d.useRef(0);d.useEffect(()=>{D.current=I},[I]);const K=d.useCallback(ce=>{ce&&ce.stopPropagation();const Te=F.current,Fe=$.current,$e=A.current;let Ze;const de=Te[$e]?.id;f?Fe&&Fe.includes(de)?Ze=Fe.filter(Be=>Be!==de):Ze=[...Fe||[],de]:Ze=de,r&&r({id:Ze})},[f,r]),z=d.useRef(K);d.useEffect(()=>{z.current=K},[K]);const q=d.useCallback(ce=>{if(y.current){let Te=ce*D.current-y.current.clientHeight+D.current;j(Te),y.current.scrollTop=Te}},[D.current]),W=d.useCallback(ce=>{y.current=ce,l&&(ce&&!w.current&&A.current!==null&&requestAnimationFrame(()=>{y.current&&(q(A.current),w.current=!0)}),ce||(w.current=!1))},[q]),Y=d.useCallback(ce=>{if(!ce||P.current)return;const Te=ce.getBoundingClientRect().height;Te&&(N(Te),D.current=Te,P.current=!0)},[]);d.useEffect(()=>{b.current.init(y.current,t,ce=>{k(ce),A.current=ce},ce=>z.current(ce),l)},[t,y.current,l]),d.useEffect(()=>{const ce=(Fe,$e)=>{b.current.navigate(Fe,$e),q(A.current)},Te=(Fe,$e)=>{const Ze=A.current,de=F.current;if(Ze!==0&&Ze!==de.length-1&&(Fe.key==="ArrowDown"||Fe.key==="ArrowUp")&&Fe.preventDefault(),b.current.keydown(Fe,$e),y.current){const Be=y.current.scrollTop<=A.current*D.current,Ve=y.current.scrollTop+y.current.clientHeight>=A.current*D.current+D.current;Be?Ve||q(A.current):(y.current.scrollTop=A.current*D.current,j(y.current.scrollTop))}};s&&s({navigate:l?ce:b.current.navigate,keydown:l?Te:b.current.keydown,move:b.current.move})},[]);const V=d.useRef(0),he=d.useRef(t);he.current!==t&&(he.current=t,V.current+=1);const ee=d.useCallback(()=>{b.current.navigate(null)},[b]),U=d.useCallback(ce=>{l&&j(ce.target.scrollTop)},[l]),L=d.useMemo(()=>Math.ceil((y.current?.clientHeight||0)/I),[I,T]),le=d.useMemo(()=>{if(!l)return{start:0,end:t.length};if(!t.length)return{start:0,end:0};const ce=Math.floor(T/I),Te=ce+L;return{start:Math.max(0,ce-Zw),end:Math.min(t.length,Te+Zw)}},[l,t,T,I,L]),ve=d.useMemo(()=>{if(!l)return t;const{start:ce,end:Te}=le;return t.slice(ce,Te).map(Fe=>({...Fe}))},[l,t,le]),J=le.start*I,Ae=t.length*I;return d.useEffect(()=>{l&&j(0)},[t,l]),d.useEffect(()=>{S===null&&(w.current=!1)},[S]),S===null?null:o.jsx(ly,{onCancel:ee,...g,children:o.jsx("div",{className:"wx-233fr7 wx-list",ref:W,onClick:K,onMouseMove:b.current.move,onScroll:U,children:t.length?l?o.jsx("div",{className:"wx-233fr7 wx-list-wrapper",style:{height:`${Ae}px`},children:o.jsx("div",{className:"wx-233fr7 wx-list-content",style:{transform:`translateY(${J}px)`},children:o.jsx(Jw,{visibleRange:le,visibleItems:ve,navIndex:S,measureRefCallback:Y,checkboxes:u,itemTemplate:n,value:h})})}):o.jsx(Jw,{visibleRange:le,visibleItems:ve,navIndex:S,measureRefCallback:Y,checkboxes:u,itemTemplate:n,value:h}):o.jsx("div",{className:"wx-233fr7 wx-no-data",children:H("No data")})})},V.current)}function cy({value:t="",id:n,readonly:r=!1,focus:s=!1,select:l=!1,type:u="text",placeholder:f="",disabled:h=!1,error:g=!1,title:y="",tooltip:w,css:b="",icon:S="",clear:k=!1,onChange:A}){const T=PS(n),[j,I]=po(t),N=d.useRef(null),P=d.useMemo(()=>S&&b.indexOf("wx-icon-left")===-1?"wx-icon-right "+b:b,[S,b]),H=d.useMemo(()=>S&&b.indexOf("wx-icon-left")!==-1,[S,b]);d.useEffect(()=>{const z=setTimeout(()=>{s&&N.current&&N.current.focus(),l&&N.current&&N.current.select()},1);return()=>clearTimeout(z)},[s,l]);const F=d.useCallback(z=>{const q=z.target.value;I(q),A&&A({value:q,input:!0})},[A]),$=d.useCallback(z=>A&&A({value:z.target.value}),[A]);function D(z){z.stopPropagation(),I(""),A&&A({value:""})}let K=u;return u!=="password"&&u!=="number"&&(K="text"),d.useEffect(()=>{const z=$,q=N.current;return q.addEventListener("change",z),()=>{q&&q.removeEventListener("change",z)}},[$]),o.jsxs("div",{className:`wx-hQ64J4 wx-text ${P} ${g?"wx-error":""} ${h?"wx-disabled":""} ${k?"wx-clear":""}`,"data-tooltip-text":w,children:[o.jsx("input",{className:"wx-hQ64J4 wx-input",ref:N,id:T,readOnly:r,disabled:h,placeholder:f,type:K,title:y,value:j,onInput:F}),k&&!h&&j?o.jsxs(o.Fragment,{children:[o.jsx("i",{className:"wx-hQ64J4 wx-icon wxi-close",onClick:D}),H&&o.jsx("i",{className:`wx-hQ64J4 wx-icon ${S}`})]}):S?o.jsx("i",{className:`wx-hQ64J4 wx-icon ${S}`}):null]})}function vR({date:t,type:n,part:r,onShift:s}){const{calendar:l,formats:u}=d.useContext(Ni).getRaw(),f=t.getFullYear(),h=d.useMemo(()=>{switch(n){case"month":return _d(u.monthYearFormat,l)(t);case"year":return _d(u.yearFormat,l)(t);case"duodecade":{const{start:y,end:w}=jS(f),b=_d(u.yearFormat,l);return`${b(new Date(y,0,1))} - ${b(new Date(w,11,31))}`}default:return""}},[t,n,f,l,u]);function g(){s&&s({diff:0,type:n})}return o.jsxs("div",{className:"wx-8HQVQV wx-header",children:[r!=="right"?o.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-left",onClick:()=>s&&s({diff:-1,type:n})}):o.jsx("span",{className:"wx-8HQVQV wx-spacer"}),o.jsx("span",{className:"wx-8HQVQV wx-label",onClick:g,children:h}),r!=="left"?o.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-right",onClick:()=>s&&s({diff:1,type:n})}):o.jsx("span",{className:"wx-8HQVQV wx-spacer"})]})}function uy({onClick:t,children:n}){return o.jsx("button",{className:"wx-3s8W4d wx-button",onClick:t,children:n})}function yR({value:t,current:n,part:r="",markers:s=null,css:l="",onCancel:u,onChange:f}){const h=(d.useContext(Ni)||Eh()).getRaw().calendar,g=(h.weekStart||7)%7,y=h.dayShort.slice(g).concat(h.dayShort.slice(0,g)),w=(F,$,D)=>new Date(F.getFullYear(),F.getMonth()+($||0),F.getDate()+(D||0));let b=r!=="normal";function S(F){const $=F.getDay();return $===0||$===6}function k(){const F=w(n,0,1-n.getDate());return F.setDate(F.getDate()-(F.getDay()-(g-7))%7),F}function A(){const F=w(n,1,-n.getDate());return F.setDate(F.getDate()+(6-F.getDay()+g)%7),F}const T=d.useRef(0);function j(F,$){$.timeStamp!==T.current&&(T.current=$.timeStamp,$.stopPropagation(),f&&f(new Date(F)),u&&u())}const I=d.useMemo(()=>r=="normal"?[t?w(t).valueOf():0]:t?[t.start?w(t.start).valueOf():0,t.end?w(t.end).valueOf():0]:[0,0],[r,t]),N=d.useMemo(()=>{const F=k(),$=A(),D=n.getMonth();let K=[];for(let z=F;z<=$;z.setDate(z.getDate()+1)){const q={day:z.getDate(),in:z.getMonth()===D,date:z.valueOf()};let W="";if(W+=q.in?"":" wx-inactive",W+=I.indexOf(q.date)>-1?" wx-selected":"",b){const Y=q.date==I[0],V=q.date==I[1];Y&&!V?W+=" wx-left":V&&!Y&&(W+=" wx-right"),q.date>I[0]&&q.date<I[1]&&(W+=" wx-inrange")}if(W+=S(z)?" wx-weekend":"",s){const Y=s(z);Y&&(W+=" "+Y)}K.push({...q,css:W})}return K},[n,I,b,s]),P=d.useRef(null);let H=d.useRef({});return H.current.click=j,d.useEffect(()=>{zd(P.current,H.current)},[]),o.jsxs("div",{className:`wx-398RBS wx-month ${l}`,children:[o.jsx("div",{className:"wx-398RBS wx-weekdays",children:y.map(F=>o.jsx("div",{className:"wx-398RBS wx-weekday",children:F},F))}),o.jsx("div",{className:"wx-398RBS wx-days",ref:P,children:N.map(F=>o.jsx("div",{className:`wx-398RBS wx-day ${F.css} ${F.in?"":"wx-out"}`,"data-id":F.date,children:F.day},F.date))})]})}function bR({value:t,current:n,part:r,onCancel:s,onChange:l,onShift:u}){const f=d.useRef(new Date),[h,g]=po(t||f.current),[y,w]=po(n||f.current),b=d.useContext(Ni).getRaw().calendar,S=b.monthShort||[],k=d.useMemo(()=>y.getMonth(),[y]),A=d.useCallback((I,N)=>{if(I!=null){N.stopPropagation();const P=new Date(y);P.setMonth(I),w(P),u&&u({current:P})}r==="normal"&&g(new Date(y)),s&&s()},[y,r,u,s]),T=d.useCallback(()=>{const I=new Date(_S(h,r)||y);I.setMonth(y.getMonth()),I.setFullYear(y.getFullYear()),l&&l(I)},[h,y,r,l]),j=d.useCallback(I=>{const N=I.target.closest("[data-id]");if(N){const P=parseInt(N.getAttribute("data-id"),10);A(P,I)}},[A]);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"wx-34U8T8 wx-months",onClick:j,children:S.map((I,N)=>o.jsx("div",{className:"wx-34U8T8 wx-month"+(k===N?" wx-current":""),"data-id":N,children:I},N))}),o.jsx("div",{className:"wx-34U8T8 wx-buttons",children:o.jsx(uy,{onClick:T,children:b.done})})]})}const qg="wx-1XEF33",wR=({value:t,current:n,onCancel:r,onChange:s,onShift:l,part:u})=>{const f=d.useContext(Ni).getRaw().calendar,[h,g]=po(n),[y,w]=po(t),b=d.useMemo(()=>h.getFullYear(),[h]),S=d.useMemo(()=>{const{start:I,end:N}=jS(b),P=[];for(let H=I;H<=N;++H)P.push(H);return P},[b]),k={click:A};function A(I,N){if(I){N.stopPropagation();const P=new Date(h);P.setFullYear(I),g(P),l&&l({current:P})}u==="normal"&&w(new Date(h)),r&&r()}function T(){const I=new Date(_S(y,u)||h);I.setFullYear(h.getFullYear()),s&&s(I)}const j=d.useRef(null);return d.useEffect(()=>{j.current&&zd(j.current,k)},[]),o.jsxs(o.Fragment,{children:[o.jsx("div",{className:qg+" wx-years",ref:j,children:S.map((I,N)=>o.jsx("div",{className:qg+` wx-year ${b==I?"wx-current":""} ${N===0?"wx-prev-decade":""} ${N===11?"wx-next-decade":""}`,"data-id":I,children:I},N))}),o.jsx("div",{className:qg+" wx-buttons",children:o.jsx(uy,{onClick:T,children:f.done})})]})},ex={month:{component:yR,next:SR,prev:xR},year:{component:bR,next:kR,prev:CR},duodecade:{component:wR,next:AR,prev:MR}};function xR(t){return t=new Date(t),t.setMonth(t.getMonth()-1),t}function SR(t){return t=new Date(t),t.setMonth(t.getMonth()+1),t}function CR(t){return t=new Date(t),t.setFullYear(t.getFullYear()-1),t}function kR(t){return t=new Date(t),t.setFullYear(t.getFullYear()+1),t}function MR(t){return t=new Date(t),t.setFullYear(t.getFullYear()-10),t}function AR(t){return t=new Date(t),t.setFullYear(t.getFullYear()+10),t}function _S(t,n){let r;if(n==="normal")r=t;else{const{start:s,end:l}=t;n==="left"?r=s:n=="right"?r=l:r=s&&l}return r}const TR=["clear","today"];function NR(t){if(t==="done")return-1;if(t==="clear")return null;if(t==="today")return new Date}function RR({value:t,current:n,onCurrentChange:r,part:s="normal",markers:l=null,buttons:u,css:f="",onShift:h,onChange:g}){const y=d.useContext(Ni).getGroup("calendar"),[w,b]=d.useState("month"),S=Array.isArray(u)?u:u?TR:[],k=(N,P)=>{N.preventDefault(),g&&g({value:P})},A=()=>{w==="duodecade"?b("year"):w==="year"&&b("month")},T=N=>{const{diff:P,current:H}=N;if(P===0){w==="month"?b("year"):w==="year"&&b("duodecade");return}if(P){const F=ex[w];r(P>0?F.next(n):F.prev(n))}else H&&r(H);h&&h()},j=N=>{b("month"),g&&g({select:!0,value:N})},I=d.useMemo(()=>ex[w].component,[w]);return o.jsx("div",{className:`wx-2Gr4AS wx-calendar ${s!=="normal"&&s!=="both"?"wx-part":""} ${f}`,children:o.jsxs("div",{className:"wx-2Gr4AS wx-wrap",children:[o.jsx(vR,{date:n,part:s,type:w,onShift:T}),o.jsxs("div",{children:[o.jsx(I,{value:t,current:n,onCurrentChange:r,part:s,markers:l,onCancel:A,onChange:j,onShift:T}),w==="month"&&S.length>0&&o.jsx("div",{className:"wx-2Gr4AS wx-buttons",children:S.map(N=>o.jsx("div",{className:"wx-2Gr4AS wx-button-item",children:o.jsx(uy,{onClick:P=>k(P,NR(N)),children:y(N)})},N))})]})]})})}function dy(t){let{words:n=null,optional:r=!1,children:s}=t,l=d.useContext(Ni);const u=d.useMemo(()=>{let f=l;return(!f||!f.extend)&&(f=Sm(DS)),n!==null&&(f=f.extend(n,r)),f},[n,r,l]);return o.jsx(Ni.Provider,{value:u,children:s})}function tx(t,n,r,s){if(!t||s){const l=n?new Date(n):new Date;l.setDate(1),r(l)}else if(t.getDate()!==1){const l=new Date(t);l.setDate(1),r(l)}}const ER=["clear","today"];function OS({value:t,current:n,markers:r=null,buttons:s=ER,css:l="",onChange:u}){const[f,h]=po(t),[g,y]=po(n);d.useEffect(()=>{tx(g,f,y,!1)},[f,g]);const w=d.useCallback(S=>{const k=S.value;k?(h(new Date(k)),tx(g,new Date(k),y,!0)):h(null),u&&u({value:k?new Date(k):null})},[u,g]),b=d.useCallback(S=>{y(S)},[y]);return g?o.jsx(dy,{children:o.jsx(RR,{value:f,current:g,markers:r,buttons:s,css:l,onChange:w,onCurrentChange:b})}):null}function jR(t){return t||(t={}),t.width||(t.width="unset"),t}const DR=["clear","today"];function IR({value:t,id:n,disabled:r=!1,error:s=!1,placeholder:l="",format:u="",buttons:f=DR,css:h="",title:g="",tooltip:y,editable:w=!1,clear:b=!1,onChange:S,dropdown:k={}}){const{calendar:A,formats:T}=(d.useContext(Ni)||Eh()).getRaw(),j=u||T?.dateFormat;let I=typeof j=="function"?j:_d(j,A);const[N,P]=d.useState(t),[H,F]=d.useState(!1);d.useEffect(()=>{P(t)},[t]);function $(){F(!1)}function D(q){const W=q===N||q&&N&&q.valueOf()===N.valueOf()||!q&&!N;P(q),W||S&&S({value:q}),setTimeout($,1)}const K=d.useMemo(()=>N?I(N):"",[N,I]);function z({value:q,input:W}){if(!w&&!b||W)return;let Y=typeof w=="function"?w(q):q?new Date(q):null;Y=isNaN(Y)?N||null:Y||null,D(Y)}return d.useEffect(()=>{const q=$;return window.addEventListener("scroll",q),()=>window.removeEventListener("scroll",q)},[]),o.jsxs("div",{className:"wx-1lKOFG wx-datepicker",onClick:()=>F(!0),children:[o.jsx(cy,{css:`wx-date-input ${h}`,title:g,tooltip:y,value:K,id:n,readonly:!w,disabled:r,error:s,placeholder:l,onInput:$,onChange:z,icon:"wxi-calendar",clear:b}),H&&!r&&o.jsx(ly,{onCancel:$,...jR(k),children:o.jsx(OS,{buttons:f,value:N,onChange:q=>D(q.value)})})]})}function LR({value:t="",options:n=[],textOptions:r=null,placeholder:s="",disabled:l=!1,error:u=!1,title:f="",tooltip:h,textField:g="label",clear:y=!1,css:w="",children:b,onChange:S,dropdown:k={}}){const A=d.useRef(null),T=d.useRef(null);let[j,I]=po(t);function N(D){A.current=D.navigate,T.current=D.keydown}const P=d.useMemo(()=>j||j===0?(r||n).find(D=>D.id===j):null,[j,r,n]),H=d.useCallback(({id:D})=>{(D||D===0)&&(I(D),A.current(null),S&&S({value:D}))},[I,S]),F=d.useCallback(D=>{D.stopPropagation(),I(""),S&&S({value:""})},[I,S]),$=d.useCallback(()=>n.findIndex(D=>D.id===j),[n,j]);return o.jsxs("div",{className:`wx-2YgblL wx-richselect ${w} ${u?"wx-2YgblL wx-error":""} ${l?"wx-2YgblL wx-disabled":""} ${b?"":"wx-2YgblL wx-nowrap"}`,title:f,onClick:()=>A.current($()),onKeyDown:D=>T.current(D,$()),tabIndex:0,"data-tooltip-text":h,children:[o.jsx("div",{className:"wx-2YgblL wx-label",children:P?b?b(P):P[g]:s?o.jsx("span",{className:"wx-2YgblL wx-placeholder",children:s}):" "}),y&&!l&&j?o.jsx("i",{className:"wx-2YgblL wx-icon wxi-close",onClick:F}):o.jsx("i",{className:"wx-2YgblL wx-icon wxi-angle-down"}),!l&&o.jsx(jh,{items:n,onReady:N,onSelect:H,...k,children:({option:D})=>b?b(D):D[g]})]})}const PR=({options:t=[],value:n="",css:r="",children:s,onChange:l})=>{const[u,f]=d.useState(n),h=g=>{f(g),l&&l({value:g})};return d.useEffect(()=>{f(n)},[n]),o.jsx("div",{className:`wx-0hMO7P wx-segmented ${r}`,children:t.map(g=>o.jsx("button",{className:`wx-0hMO7P wx-segment ${g.css} ${g.id===u?"wx-selected":""}`,title:g.title,onClick:()=>h(g.id),"data-tooltip-text":g.tooltip,children:s?ay(s,{option:g}):o.jsxs(o.Fragment,{children:[g.icon&&o.jsx("i",{className:`wx-0hMO7P wx-icon ${g.icon} ${g.label?"":"wx-only"}`}),g.label&&o.jsx("span",{className:"wx-0hMO7P wx-label",children:g.label})]})},g.id))})};function _R({notice:t={}}){function n(){t.remove&&t.remove()}return o.jsxs("div",{className:`wx-11sNg5 wx-notice wx-${t.type?t.type:""}`,role:"status","aria-live":"polite",children:[o.jsx("div",{className:"wx-11sNg5 wx-text",children:t.text}),o.jsx("div",{className:"wx-11sNg5 wx-button",children:o.jsx("i",{className:"wx-11sNg5 wxi-close",onClick:n})})]})}function OR({data:t=[]}){return o.jsx("div",{className:"wx-3nwoO9 wx-notices",children:t.map(n=>o.jsx(_R,{notice:n},n.id))})}function Pv({title:t="",buttons:n=["cancel","ok"],header:r,children:s,footer:l,css:u="",onConfirm:f,onCancel:h}){const g=(d.useContext(Ni)||Eh()).getGroup("core"),y=d.useRef(null);d.useEffect(()=>{y.current?.focus()},[]);function w(S){switch(S.code){case"Enter":{const k=S.target.tagName;if(k==="TEXTAREA"||k==="BUTTON")return;f&&f({event:S});break}case"Escape":h&&h({event:S});break}}function b(S,k){const A={event:S,button:k};k==="cancel"?h&&h(A):f&&f(A)}return o.jsx("div",{className:`wx-1FxkZa wx-modal ${u}`,ref:y,tabIndex:0,onKeyDown:w,children:o.jsxs("div",{className:"wx-1FxkZa wx-window",children:[r||(t?o.jsx("div",{className:"wx-1FxkZa wx-header",children:t}):null),o.jsx("div",{children:s}),l||n&&o.jsx("div",{className:"wx-1FxkZa wx-buttons",children:n.map(S=>o.jsx("div",{className:"wx-1FxkZa wx-button",children:o.jsx(um,{type:`block ${S==="ok"?"primary":"secondary"}`,onClick:k=>b(k,S),children:g(S)})},S))})]})})}function FR({children:t},n){const[r,s]=d.useState(null),[l,u]=d.useState([]);return d.useImperativeHandle(n,()=>({showModal:f=>{const h={...f};return s(h),new Promise((g,y)=>{h.resolve=w=>{s(null),g(w)},h.reject=w=>{s(null),y(w)}})},showNotice:f=>{f={...f},f.id=f.id||sy(),f.remove=()=>u(h=>h.filter(g=>g.id!==f.id)),f.expire!=-1&&setTimeout(f.remove,f.expire||5100),u(h=>[...h,f])}}),[]),o.jsxs(o.Fragment,{children:[t,r&&o.jsx(Pv,{title:r.title,buttons:r.buttons,onConfirm:r.resolve,onCancel:r.reject,children:r.message}),o.jsx(OR,{data:l})]})}const BR=d.forwardRef(FR);function HR(t){let{children:n}=t,r=d.useRef();const s=d.useMemo(()=>({showNotice:l=>r.current.showNotice(l),showModal:l=>r.current.showModal(l)}),[]);return o.jsx(IS.Provider,{value:s,children:o.jsx(BR,{ref:r,children:n})})}const zR=({value:t=!1,type:n="",icon:r="",disabled:s=!1,iconActive:l="",onClick:u,title:f="",tooltip:h,css:g="",text:y="",textActive:w="",children:b,active:S,onChange:k})=>{const[A,T]=po(t),j=d.useMemo(()=>(A?"pressed":"")+(n?" "+n:""),[A,n]),I=d.useCallback(N=>{let P=!A;u&&u(N),N.defaultPrevented||(T(P),k&&k({value:P}))},[A,u,k]);return A&&S?o.jsx(um,{title:f,tooltip:h,text:A&&w||y,css:g,type:j,icon:A&&l||r,onClick:I,disabled:s,children:ay(S,{value:A})}):b?o.jsx(um,{title:f,tooltip:h,text:A&&w||y,css:g,type:j,icon:A&&l||r,onClick:I,disabled:s,children:b}):o.jsx(um,{title:f,tooltip:h,text:A&&w||y,css:g,type:j,icon:A&&l||r,onClick:I,disabled:s})};function $R(){return o.jsx(o.Fragment,{})}function nx(t){const{fonts:n=!0,children:r}=t;return o.jsx(iy.Provider,{value:"willow",children:o.jsxs(o.Fragment,{children:[r&&r&&o.jsx("div",{className:"wx-theme wx-willow-theme",children:r}),n&&o.jsxs(o.Fragment,{children:[o.jsx("link",{rel:"preconnect",href:"https://cdn.svar.dev",crossOrigin:"true"}),o.jsx($R,{}),o.jsx("link",{rel:"stylesheet",href:"https://cdn.svar.dev/fonts/wxi/wx-icons.css"})]})]})})}ry(gs);const fy={grid:{"Add before":"Add before","Add after":"Add after",Copy:"Copy",Cut:"Cut",Paste:"Paste",Delete:"Delete","New row":"New row","Move up":"Move up","Move down":"Move down",Undo:"Undo",Redo:"Redo",selected:"selected"}};new Date().valueOf();var FS=class{constructor(t){this._nextHandler=null,this._dispatch=t,this.exec=this.exec.bind(this)}async exec(t,n){return this._dispatch(t,n),this._nextHandler&&await this._nextHandler.exec(t,n),n}setNext(t){return this._nextHandler=t}};new Date().valueOf();var UR=class{constructor(t){const n={id:0,$level:0,data:[],parent:null},r=new Map;r.set(0,n),this._pool=r,t&&t.length&&this.parse(t,0)}parse(t,n){const r=this._pool;for(let l=0;l<t.length;l++){const u=t[l];u.parent=u.parent||n,u.data=null,r.set(u.id,u)}for(let l=0;l<t.length;l++){const u=t[l],f=r.get(u.parent);f&&(f.data||(f.data=[]),f.data.push(u))}const s=r.get(n);this.setLevel(s,s.$level+1,!1)}add(t,n){const r=this._pool.get(t.parent||0);t.$level=r.$level+1,this._pool.set(t.id,t),r.data?n===-1?r.data=[...r.data,t]:ax(r,n,t):r.data=[t]}addAfter(t,n){if(!n)return this.add(t,-1);const r=this.byId(n),s=this.byId(r.parent),l=_p(s,r.id)+1;t.parent=s.id,t.$level=s.$level+1,this.add(t,l)}remove(t){const n=this._pool.get(t);this._remove(n);const r=this._pool.get(n.parent);r.data=r.data.filter(s=>s.id!=t),this._clearBranch(r)}_remove(t){t.data&&t.data.forEach(n=>this._remove(n)),this._pool.delete(t.id)}update(t,n){let r=this._pool.get(t);const s=this._pool.get(r.parent),l=_p(s,r.id);r={...r,...n},s&&l>=0&&(s.data[l]=r,s.data=[...s.data]),this._pool.set(r.id,r)}move(t,n,r){const s=this._pool.get(t),l=n==="child",u=this._pool.get(r),f=u.$level+(l?1:0);if(!s||!u)return;const h=this._pool.get(s.parent),g=l?u:this._pool.get(u.parent);g.data||(g.data=[]);const y=_p(h,s.id);qR(h,y);const w=l?g.data.length:_p(g,u.id)+(n==="after"?1:0);if(ax(g,w,s),h.id===g.id&&y===w)return null;s.parent=g.id,s.$level!==f&&(s.$level=f,this.setLevel(s,f+1,!0)),this.update(s.id,s),this._clearBranch(h)}_clearBranch(t){t.data&&!t.data.length&&(t.open&&delete t.open,this.update(t.id,{data:null}))}toArray(){const t=[],n=this._pool.get(0).data;return n&&BS(n,t),t}byId(t){return this._pool.get(t)}getBranch(t){return this._pool.get(t).data}forEach(t){this._pool.forEach((n,r)=>{r!==0&&t(n)})}eachChild(t,n){const r=this.byId(n);!r||!r.data||r.data.forEach((s,l)=>{t(this.byId(s.id),l),this.eachChild(t,s.id)})}setLevel(t,n,r){t.data&&(t.data=t.data.map(s=>(r&&(s={...s},this._pool.set(s.id,s)),s.$level=n,s.data&&this.setLevel(s,n+1,r),s)))}};function BS(t,n){t.forEach(r=>{n.push(r),r.open===!0&&BS(r.data,n)})}function qR(t,n){const r=[...t.data];r.splice(n,1),t.data=r}function ax(t,n,r){const s=[...t.data];s.splice(n,0,r),t.data=s}function _p(t,n){return t?.data.findIndex(r=>r.id===n)}var HS=2,WR=class{constructor(n){n&&(this._writable=n.writable,this._async=n.async),this._values={},this._state={}}setState(n,r=0){const s={};return this._wrapProperties(n,this._state,this._values,"",s,r),s}getState(){return this._values}getReactive(){return this._state}_wrapProperties(n,r,s,l,u,f){for(const h in n){const g=r[h],y=s[h],w=n[h];if(g&&(y===w&&typeof w!="object"||w instanceof Date&&y instanceof Date&&y.getTime()===w.getTime()))continue;const b=l+(l?".":"")+h;g?(g.__parse(w,b,u,f)&&(s[h]=w),f&HS?u[b]=g.__trigger:g.__trigger()):(w&&w.__reactive?r[h]=this._wrapNested(w,w,b,u):r[h]=this._wrapWritable(w),s[h]=w),u[b]=u[b]||null}}_wrapNested(n,r,s,l){const u=this._wrapWritable(n);return this._wrapProperties(n,u,r,s,l,0),u.__parse=(f,h,g,y)=>(this._wrapProperties(f,u,r,h,g,y),!1),u}_wrapWritable(n){const r=[],s=function(){for(let l=0;l<r.length;l++)r[l](n)};return{subscribe:l=>(r.push(l),this._async?setTimeout(l,1,n):l(n),()=>{const u=r.indexOf(l);u>=0&&r.splice(u,1)}),__trigger:()=>{r.length&&(this._async?setTimeout(s,1):s())},__parse:function(l){return n=l,!0}}}};function rx(t,n){return Object.defineProperty(t,"__reactive",{value:!0,enumerable:!1,writable:!1}),t}var GR=class{constructor(n,r,s,l){typeof n=="function"?this._setter=n:this._setter=n.setState.bind(n),this._routes=r,this._parsers=s,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(u=>{u.in.forEach(f=>{const h=this._triggers.get(f)||[];h.push(u),this._triggers.set(f,h)}),u.out.forEach(f=>{const h=this._sources.get(f)||{};u.in.forEach(g=>h[g]=!0),this._sources.set(f,h)})}),this._routes.forEach(u=>{u.length=Math.max(...u.in.map(f=>zS(f,this._sources,1)))}),this._bus=l}init(n){const r={};for(const s in n)if(this._prev[s]!==n[s]){const l=this._parsers[s];r[s]=l?l(n[s]):n[s]}this._prev=this._prev?{...this._prev,...n}:{...n},this.setState(r),this._bus&&this._bus.exec("init-state",r)}setStateAsync(n){const r=this._setter(n,HS);return this._async?Object.assign(this._async.signals,r):this._async={signals:r,timer:setTimeout(this._applyState.bind(this),1)},r}_applyState(){const n=this._async;if(n){this._async=null,this._triggerUpdates(n.signals,[]);for(const r in n.signals){const s=n.signals[r];s&&s()}}}setState(n,r=[]){const s=this._setter(n);return this._triggerUpdates(s,r),s}_triggerUpdates(n,r){const s=Object.keys(n),l=!r.length;r=r||[];for(let u=0;u<s.length;u++){const f=s[u],h=this._triggers.get(f);h&&h.forEach(g=>{r.indexOf(g)==-1&&r.push(g)})}l&&this._execNext(r)}_execNext(n){for(;n.length;){n.sort((s,l)=>s.length<l.length?1:-1);const r=n[n.length-1];n.splice(n.length-1),r.exec(n)}}};function zS(t,n,r){const s=n.get(t);if(!s)return r;const l=Object.keys(s).map(u=>zS(u,n,r+1));return Math.max(...l)}var VR=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(n,r,s){let l=this._handlers[n];l?s&&s.intercept?l.unshift(r):l.push(r):l=this._handlers[n]=[r],s&&s.tag&&this._tag.set(r,s.tag)}intercept(n,r,s){this.on(n,r,{...s,intercept:!0})}detach(n){for(const r in this._handlers){const s=this._handlers[r];for(let l=s.length-1;l>=0;l--)this._tag.get(s[l])===n&&s.splice(l,1)}}async exec(n,r){const s=this._handlers[n];if(s)for(let l=0;l<s.length;l++){const u=s[l](r);if(u===!1||u&&u.then&&await u===!1)return}return this._nextHandler&&await this._nextHandler.exec(n,r),r}setNext(n){return this._nextHandler=n}};const Rd=1024;function ym(t){return t<Rd?`${t} B`:t<Rd**2?`${(t/Rd).toFixed(1)} KB`:t<Rd**3?`${(t/Rd**2).toFixed(1)} MB`:`${(t/Rd**3).toFixed(1)} GB`}function sx(t,n){n||(n={key:"name",order:"asc"});const r=t.filter(f=>f.type==="folder"),s=t.filter(f=>f.type!=="folder"),l=r.sort(ix(n)),u=s.sort(ix(n));return[...l,...u]}function KR(t,n){return typeof t=="string"?t.localeCompare(n,void 0,{numeric:!0}):typeof t=="object"?t.getTime()-n.getTime():(t??0)-(n??0)}function QR(t,n){return typeof t=="string"?-t.localeCompare(n,void 0,{numeric:!0}):typeof n=="object"?n.getTime()-t.getTime():(n??0)-(t??0)}function ix({key:t,order:n}){const r=n==="asc"?KR:QR;return(s,l)=>r(s[t],l[t])}function my(t,n){const r=t==="/"?1:t.split("/").length;return r>=n.length?null:n[r].id}function YR(t){return t.length>1?t[t.length-2].id:null}let XR=class extends UR{constructor(n){const r={id:"/",name:"My files",open:!0,$level:1,parent:0,ext:"",type:"folder"};super([r]),this.parse(n,"/")}parse(n,r,s){!n||!n.length||(n.forEach(l=>this.parseId(l,s?r:void 0)),super.parse(n,r))}parseId(n,r){if(n.parent===0)return;const s=n.id,l=s.lastIndexOf("/");if(n.parent=r??(l===0?"/":s.slice(0,l)),n.name=s.slice(l+1),n.type=n.type||"file",n.type!=="folder"){const u=n.name.lastIndexOf("."),f=u!==-1?n.name.slice(u+1):"";n.ext=f!=="new"?f?.toLocaleLowerCase():""}}getParents(n){const r=[];let s=this.byId(n);if(!s)return r;for(;s.id!==0;)r.push(s),s=this.byId(s.parent);return r.reverse()}findFiles(n,r="/"){const s=[],l=n.toLocaleLowerCase();return this.eachChild(u=>{u.name.toLowerCase().indexOf(l)!==-1&&s.push(u)},r),s}add(n,r){const s=this.byId(n.parent||"/"),l=n.data?[...n.data]:null;n.data=null,super.add(n,r??s.data?s.data.length:0),l&&l.forEach(u=>this.add(u))}renameFiles(n,r,s){const l=this.byId(n),u=this.normalizeFile(l,r),f=[];return u.data?.forEach(h=>f.push(this.renameFiles(h.id,u.id,s))),f.length&&(u.data=f),s[n]=u.id,u}copyFiles(n,r,s){const l={};return n.forEach(u=>{const f=this.renameFiles(u,r,l);this.add(f),s&&this.remove(u),l[u]=f.id}),l}moveFiles(n,r){if(this.byId(n[0]).parent!==r)return this.copyFiles(n,r,!0)}serialize(n="/"){const r=[],s=this.byId(n);return s?(s.data?.forEach(l=>{const{id:u,date:f,type:h,size:g,lazy:y}=l,w={id:u,date:f,type:h??"file"};y&&(w.lazy=y),g&&(w.size=g),r.push(w);const b=this.serialize(u);b.length&&r.push(...b)}),r):null}normalizeFile(n,r){const s=n.name,l=s.lastIndexOf("."),u=l!==-1?s.slice(l+1):"",f=u?`.${u}`:"";let h=l!==-1?s.slice(0,l):s,g=r+(r==="/"?"":"/")+h;for(;this.byId(g+f);){const y=".new";g+=y,h+=y}return{...n,id:g+f,name:h+f,parent:r,ext:u.toLocaleLowerCase()}}},ZR=class extends WR{in;_router;constructor(n){super({writable:n,async:!1});const r=[];for(let u=0;u<2;u++)r.push({in:["data",`panels.${u}.path`],out:[`panels.${u}._crumbs`],exec:f=>{const{data:h,panels:g}=this.getState(),y=[];y[u]={_crumbs:h.getParents(g[u].path)},this.setState({panels:y},f)}}),r.push({in:["data",`panels.${u}.path`,`panels.${u}._sorts`,"search"],out:[`panels.${u}._files`],exec:f=>{const{data:h,panels:g,search:y}=this.getState();let w;y?w=h.findFiles(y,g[u].path):w=h.byId(g[u].path)?.data||[];const{path:b,_sorts:S}=g[u];w=sx(w,S[b]);const k=[];k[u]={_files:w},this.setState({panels:k},f)}}),r.push({in:["data",`panels.${u}.selected`,`panels.${u}._sorts`],out:[`panels.${u}._selected`],exec:f=>{const{data:h,panels:g}=this.getState(),y=[];g[u].selected.forEach(A=>{const T=h.byId(A);T&&y.push(T)});const{path:w,_sorts:b}=g[u],S=sx(y,b[w]),k=[];k[u]={_selected:S},this.setState({panels:k},f)}});this._router=new GR(super.setState.bind(this),r,{data:u=>new XR(u)});const s=this.in=new VR;s.on("select-file",({id:u,toggle:f,range:h,panel:g,type:y})=>{const{panels:w,activePanel:b}=this.getState();typeof g>"u"&&(g=b),u||(f=h=!1);let S=[...w[g].selected];if(f){const A=S.indexOf(u);A===-1?S.push(u):S.splice(A,1)}else if(h&&w[g]._lastSelected){const A=w[g]._files;let T=A.findIndex(N=>N.id==w[g]._lastSelected),j=A.findIndex(N=>N.id==u);j<T&&([T,j]=[j,T]);const I=A.slice(T,j+1).map(N=>N.id);S=[...new Set([...S,...I])]}else S=u?[u]:[];const k=[];k[g]={selected:S,_lastSelected:u,_selectNavigation:y==="navigation"},this.setState({panels:k})}),s.on("set-path",({id:u,panel:f,selected:h})=>{const{data:g,activePanel:y}=this.getState(),w=g.byId(u);if(w){const b=[];typeof f>"u"&&(f=y),b[f]={path:u},this.setState({panels:b}),s.exec("select-file",{panel:f}),h&&h.forEach(S=>s.exec("select-file",{id:S,panel:f,toggle:!0})),w.lazy&&s.exec("request-data",{id:u})}}),s.on("provide-data",({id:u,data:f})=>{const{mode:h,data:g}=this.getState(),y=g.byId(u);y&&(y.lazy||(y.data=[]),y.lazy=!1,g.parse(f,u,h==="search"),this.setState({data:g}))}),s.on("open-tree-folder",({id:u,mode:f})=>{const{data:h}=this.getState();h.update(u,{open:f}),this.setState({data:h})}),s.on("show-preview",({mode:u})=>{this.setState({preview:u})}),s.on("rename-file",u=>{const{id:f,name:h}=u,{data:g,panels:y}=this.getState(),w=g.byId(f);if(w.name!==h){w.name=h;const b=g.normalizeFile(w,w.parent);u.newId=b.id,b.data=null,g.add(b);let S={[f]:b.id};w.data?.forEach(A=>S={...g.moveFiles([A.id],b.id),...S});const k=y.map(A=>({selected:A.selected,_crumbs:A._crumbs,_lastSelected:A._lastSelected,_sorts:A._sorts}));g.remove(f),this._updatePanels(k,S),this.setState({data:g,panels:k})}}),s.on("create-file",u=>{const{file:f,parent:h}=u,{data:g}=this.getState(),y=g.normalizeFile(f,h);y.type=f.type||"file",u.newId=y.id,g.add(y),this.setState({data:g}),s.exec("select-file",{id:y.id})}),s.on("delete-files",({ids:u})=>{const{data:f,panels:h}=this.getState(),g=h.map(y=>({selected:y.selected,_crumbs:y._crumbs,_lastSelected:y._lastSelected,_sorts:y._sorts}));u.forEach(y=>f.remove(y)),this._updatePanels(g,{}),this.setState({data:f,panels:g})}),s.on("copy-files",u=>{const{ids:f,target:h}=u;if(this._isPlacedIntoSelf(f,h)){console.error("You cannot copy a folder into itself"),u.skipProvider=!0;return}const{data:g,panels:y,activePanel:w}=this.getState(),b=g.copyFiles(f,h);u.newIds=f.map(S=>b[S]),this.setState({data:g}),y[w].path==h&&(s.exec("select-file",{}),f.forEach(S=>{s.exec("select-file",{id:b[S],toggle:!0})}))}),s.on("move-files",u=>{const{ids:f,target:h}=u;if(this._isPlacedIntoSelf(f,h)){console.error("You cannot move a folder into itself"),u.skipProvider=!0;return}const{data:g,panels:y,activePanel:w}=this.getState(),b=g.moveFiles(f,h);if(b){u.newIds=f.map(k=>b[k]);const S=y.map(k=>({selected:k.selected,_crumbs:k._crumbs,_lastSelected:k._lastSelected,_sorts:k._sorts}));this._updatePanels(S,b,!0),this.setState({data:g,panels:S}),y[w].path==h&&(s.exec("select-file",{}),f.forEach(k=>{s.exec("select-file",{id:b[k],toggle:!0})}))}});let l=null;s.on("filter-files",({text:u})=>{if(!u){l&&this.setState({...l});return}s.exec("select-file",{});const{panels:f,mode:h}=this.getState();l||(l={panels:f,mode:h,search:""}),this.setState({mode:"search",search:u})}),s.on("set-mode",({mode:u})=>{const{activePanel:f}=this.getState(),h=[];h[f]={_selectNavigation:!1};const g={mode:u,search:"",panels:h};l=null,this.setState(g)}),s.on("set-active-panel",({panel:u})=>{this.setState({activePanel:u})}),s.on("sort-files",({key:u,order:f,panel:h,path:g})=>{const{activePanel:y,panels:w}=this.getState();h=h??y,g=g??w[h].path;const b=[];b[h]={_sorts:{...w[h]._sorts,[g]:{key:u,order:f}}},this.setState({panels:b})}),this.initOnce()}initOnce(){const n=[];for(let s=0;s<2;s++)n[s]=rx({_crumbs:[],_files:[],_selected:[],_sorts:{},path:"/",selected:[],...n[s]});const r={panels:rx(n),data:[],search:""};this._router.init(r)}init(n){const r={...n};this._router.init(r)}setState(n,r){return this._router.setState(n,r)}getFile(n){const{data:r}=this.getState();return r.byId(n)||null}serialize(n){const{data:r}=this.getState();return r.serialize(n)}_updatePanels(n,r,s){const{data:l}=this.getState();n.forEach(u=>{const f=[];u.selected.forEach(y=>{l.byId(y)?f.push(y):!s&&r[y]&&f.push(r[y])}),u.selected=f,l.byId(u._lastSelected)||(u._lastSelected=s?null:r[u._lastSelected]||null);const h={};Object.keys(u._sorts).forEach(y=>{l.byId(y)?h[y]=u._sorts[y]:r[y]&&!s&&(h[r[y]]=u._sorts[y])}),u._sorts=h;const g=u._crumbs[u._crumbs.length-1];g?.id!=="/"&&(r[g.id]?u.path=r[g.id]:l.byId(g.id)||(u.path="/"))})}_isPlacedIntoSelf(n,r){return n.some(s=>s===r||this.getState().data.getParents(r).some(l=>l.id===s))}};function JR(t){switch(t){case"body":return[{icon:"wxi-content-paste",text:"Paste",hotkey:"Ctrl+V",id:"paste"}];case"add":return[{icon:"mdi mdi-folder-plus-outline",text:"Add new file",id:"add-file"},{icon:"mdi mdi-file-plus-outline",text:"Add new folder",id:"add-folder"},{icon:"mdi mdi-file-upload-outline",text:"Upload file",id:"upload",comp:"upload"}];case"multiselect":return[{icon:"wxi-content-copy",text:"Copy",hotkey:"Ctrl+C",id:"copy"},{icon:"wxi-content-cut",text:"Cut",hotkey:"Ctrl+X",id:"move"},{comp:"separator"},{icon:"wxi-close",text:"Delete",hotkey:"Delete",id:"delete"}];default:return[t==="folder"?null:{icon:"wxi-download",text:"Download",hotkey:"Ctrl+D",id:"download"},{icon:"wxi-content-copy",text:"Copy",hotkey:"Ctrl+C",id:"copy"},{icon:"wxi-content-cut",text:"Cut",hotkey:"Ctrl+X",id:"move"},{icon:"wxi-content-paste",text:"Paste",hotkey:"Ctrl+V",id:"paste"},{comp:"separator"},{icon:"wxi-edit",text:"Rename",hotkey:"Ctrl+R",id:"rename"},{icon:"wxi-close",text:"Delete",hotkey:"Delete",id:"delete"}].filter(n=>n!==null)}}function eE(t,n="data-id"){let r=t;for(!r.tagName&&t.target&&(r=t.target);r;){if(r.getAttribute&&r.getAttribute(n))return r;r=r.parentNode}return null}function tE(t,n="data-id"){const r=eE(t,n);return r?r.getAttribute(n):null}new Date().valueOf();function nE(t,n){const{api:r}=n;function s(u,f){const h=n.getPanel(),g=h.selected,y=f.ctrlKey||f.metaKey,w=f.shiftKey;let b;const S=g?.[0]?r.getFile(g[0]):null;g?.length?g.length>1?b=n.menuOptions("multiselect"):b=n.menuOptions(S.type,S):b=n.menuOptions("body");const k=`${y?"ctrl+":""}${w?"shift+":""}${u}`,A=b?b.find(j=>j.hotkey?.toLowerCase()===k):!1,T=n.performAction;if(A)switch(k){case"ctrl+c":T("copy");break;case"ctrl+x":T("move");break;case"ctrl+v":T("paste",S);break;case"delete":T("delete");break;case"ctrl+r":f.preventDefault(),T("rename",S);break;case"ctrl+d":f.preventDefault(),T("download",S);break;default:A.handler?.({context:S})}switch(u){case"enter":{if(y||w)break;const{_crumbs:j,_selectNavigation:I}=h;if(I){const N=YR(j);if(N){const P=my(N,j);r.exec("set-path",{id:N,selected:[P]})}}else if(g.length===1){const N=r.getFile(g[0]);N&&r.exec(N.type==="folder"?"set-path":"open-file",{id:N.id})}break}case"arrowup":case"arrowleft":{const{_files:j,_selected:I,path:N,_selectNavigation:P}=h;let H;if(I.length){const F=I.at(0).id,$=j.findIndex(D=>D.id===F);if($!==-1){const D=$-1;j[D]?H=j[D].id:N!=="/"&&!(y||w)&&r.exec("select-file",{type:"navigation"})}}else{if(P)break;if(N!=="/"){r.exec("select-file",{type:"navigation"});break}H=j.at(0)?.id}H&&r.exec("select-file",{id:H,toggle:y,range:w});break}case"arrowdown":case"arrowright":{const{_files:j,_selected:I,path:N,_selectNavigation:P}=h;let H;if(I.length){const F=I.at(-1).id,$=j.findIndex(D=>D.id===F);if($!==-1){const D=$+1;j[D]&&(H=j[D].id)}}else{if(N!=="/"&&!P){r.exec("select-file",{type:"navigation"});break}H=j.at(0)?.id}H&&r.exec("select-file",{id:H,toggle:y,range:w});break}}}function l(u){const f=u.code.replace("Key","").toLowerCase();s(f,u),f=="tab"&&setTimeout(()=>{const h=document.activeElement;h.className.indexOf("table")!=-1&&r.exec("set-active-panel",{panel:+tE(h,"data-panel")})})}return t.addEventListener("keydown",l),{destroy:()=>{t.removeEventListener("keydown",l)}}}function aE(t,n="data-id"){let r=t;for(!r.tagName&&t.target&&(r=t.target);r;){if(r.getAttribute&&r.getAttribute(n))return r;r=r.parentNode}return null}function rE(t,n="data-id"){const r=t.getAttribute(n);return r?sE(r):null}function sE(t){if(t.startsWith(":"))return t.substring(1);const n=t*1;return isNaN(n)?t:n}function iE(){return{detect:()=>!0,addEvent:function(t,n,r){return t.addEventListener(n,r),()=>t.removeEventListener(n,r)},addGlobalEvent:function(t,n){return document.addEventListener(t,n),()=>document.removeEventListener(t,n)},getTopNode:function(){return window.document.body}}}var oE=iE();new Date().valueOf();function $S(t){const[n,r]=d.useState(t),s=d.useRef(t);return d.useEffect(()=>{if(s.current!==t){if(Array.isArray(s.current)&&Array.isArray(t)&&s.current.length===0&&t.length===0)return;s.current=t,r(t)}},[t]),[n,r]}function lE(t,n,r){const[s,l]=d.useState(()=>n);return t||console.warn(`Writable ${r} is not defined`),d.useEffect(()=>t?t.subscribe(f=>{l(()=>f)}):void 0,[t]),s}function Bt(t,n){const r=t.getState(),s=t.getReactiveState();return lE(s[n],r[n],n)}function cE(t,n){const r=d.useRef(n);r.current=n;const[s,l]=d.useState(1);return d.useEffect(()=>t.subscribe(f=>{r.current=f,l(h=>h+1)}),[t]),[r.current,s]}function ai(t,n){const r=t.getState(),s=t.getReactiveState();return cE(s[n],r[n])}function US(t){const n={};return t.split(";").forEach(r=>{const[s,l]=r.split(":");if(l){let u=s.trim();u.indexOf("-")&&(u=u.replace(/-([a-z])/g,(f,h)=>h.toUpperCase())),n[u]=l.trim()}}),n}function qS(t){let n=t,r=[];return{subscribe:h=>{r.push(h),h(n)},unsubscribe:h=>{r=r.filter(g=>g!==h)},set:h=>{n=h,r.forEach(g=>g(n))},update:h=>{n=h(n),r.forEach(g=>g(n))}}}function ox(t,n,r){function s(l){const u=aE(l);if(!u)return;const f=rE(u);if(typeof n=="function")return n(f,l);let h,g=l.target;for(;g!=u;){if(h=g.dataset?g.dataset.action:null,h&&n[h]){n[h](f,l);return}g=g.parentNode}n[r]&&n[r](f,l)}return oE.addEvent(t,r,s)}function uE(t,n){const r=[ox(t,n,"click")];return n.dblclick&&r.push(ox(t,n.dblclick,"dblclick")),()=>{r.forEach(s=>s())}}function WS(t,n){return t.map((r,s)=>{const l=n(r,s);return r.data&&r.data.length&&(l.data=WS(r.data,n)),l}).filter(Boolean)}function GS(t,n){const r=[];return t.forEach(s=>{if(s.data){const l=GS(s.data,n);l.length&&r.push({...s,data:l})}else n(s)&&r.push(s)}),r}function dE(t){return WS(t,(n,r)=>{const s={...n,id:n.id||sy()};return s.type&&(s.comp=s.type),s.comp==="separator"&&t[r-1]?.comp==="separator"?null:s})}const VS={};function fE(t){return VS[t]||t}function mE(t,n){VS[t]=n}function pE({onClick:t,onShow:n,option:r}){const s=d.useRef(null),l=d.useCallback(()=>{n(r.data?r.id:!1,s.current)},[n,r]),u=d.useCallback(h=>{if(r.data){h.stopPropagation(),n(r.id,s.current);return}t(h)},[t,n,r]),f=d.useMemo(()=>r&&r.comp?fE(r.comp):null,[r]);return o.jsxs("div",{ref:s,className:`wx-cDCz9rZQ wx-option ${r.css||""} ${r.disabled?"wx-disabled":""}`,"data-id":ar(r.id),onMouseEnter:l,onClick:u,children:[r.icon?o.jsx("i",{className:`wx-cDCz9rZQ wx-icon ${r.icon}`}):null,r.comp?f?o.jsx(f,{item:r,option:r}):null:o.jsxs("span",{className:"wx-cDCz9rZQ wx-value",children:[" ",r.text," "]}),r.subtext?o.jsx("span",{className:"wx-cDCz9rZQ wx-subtext",children:r.subtext}):null,r.data?o.jsx("i",{className:"wx-cDCz9rZQ wx-sub-icon wxi-angle-right"}):null]})}function py({options:t,left:n=0,top:r=0,at:s="bottom",parent:l=null,mount:u=null,context:f=null,css:h="",onClick:g,onCancel:y}){const[w,b]=d.useState(-1e4),[S,k]=d.useState(-1e4),[A,T]=d.useState(20),[j,I]=d.useState(),N=d.useRef(null),[P,H]=d.useState(!1),[F,$]=d.useState(null),D=d.useCallback(()=>{const he=RS(N.current,l,s,n,r);he&&(b(he.x),k(he.y),I(he.width));let ee=he?.z??20;const U=l?nR(l):[];let L=0;for(const le of U){const ve=parseInt(getComputedStyle(le).zIndex,10);ve>L&&(L=ve)}L>=ee&&(ee=L+1),T(ee)},[l,s,n,r]);d.useEffect(()=>{u&&u(D)},[]);const K=d.useCallback(()=>{H(!1)},[]),z=d.useCallback((he,ee)=>{H(he),$(ee)},[]),q=d.useMemo(()=>dE(t),[t]);d.useEffect(()=>{D()},[l,D]);const W=d.useRef(g),Y=d.useRef(y),V=d.useRef(l);return d.useEffect(()=>{W.current=g},[g]),d.useEffect(()=>{Y.current=y},[y]),d.useEffect(()=>{V.current=l},[l]),d.useEffect(()=>{if(!N.current)return;function he(ee){Y.current?Y.current(ee):W.current&&W.current({action:null,option:null})}return ho(N.current,{callback:he,modal:!0,parent:()=>V.current}).destroy},[]),o.jsx("div",{ref:N,"data-wx-menu":"true",className:`wx-XMmAGqVx wx-menu ${h}`,style:{position:"absolute",top:S+"px",left:w+"px",width:j,zIndex:A},onMouseLeave:K,children:q.map(he=>o.jsxs(d.Fragment,{children:[he.comp==="separator"?o.jsx("div",{className:"wx-XMmAGqVx wx-separator"}):o.jsx(pE,{option:he,onShow:z,onClick:ee=>{if(!he.data&&!ee.defaultPrevented){const U={context:f,action:he,option:he,event:ee};he.handler&&he.handler(U),g&&g(U),ee.stopPropagation()}}}),he.data&&P===he.id?o.jsx(py,{css:h,options:he.data,at:"right-overlap",parent:F,context:f,onClick:g,onCancel:y}):null]},he.id))})}const KS=d.forwardRef(function(t,n){const{options:r,at:s="bottom",resolver:l=null,dataKey:u="contextId",filter:f=null,css:h="",children:g,onClick:y}=t,[w,b]=d.useState(null),[S,k]=d.useState(null),[A,T]=d.useState(0),[j,I]=d.useState(0),N=d.useRef(null),P=d.useMemo(()=>`data-${u.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,[u]),H=d.useMemo(()=>w!==null&&f?GS(r,K=>f(K,w)):r,[w,f,r]);function F(K){k(null),y&&y(K)}function $(K){if(N.current===K){N.current=null;return}k(null),y&&y({action:null,option:null})}const D=d.useCallback((K,z)=>{if(!K){k(null);return}if(K.defaultPrevented)return;const q=K.target;if(q&&q.dataset&&q.dataset.menuIgnore)return;if(S&&S===q){k(null),K.preventDefault();return}T(K.clientX+1),I(K.clientY+1);let W=typeof z<"u"?z:vm(q,P);l&&(W=l(W,K),!W)||(b(W),k(q),N.current=K.nativeEvent||K,K.preventDefault())},[S,P,l]);return d.useImperativeHandle(n,()=>({show:D}),[D]),o.jsxs(o.Fragment,{children:[g?o.jsx("span",{onClick:D,"data-menu-ignore":"true",children:typeof g=="function"?g():g}):null,S?o.jsx(oy,{children:o.jsx(py,{css:h,at:s,top:j,left:A,parent:S,context:w,onClick:F,onCancel:$,options:H},S)}):null]})}),hE=d.forwardRef(function(t,n){const{options:r,at:s="bottom",css:l="",children:u,onClick:f}=t,[h,g]=d.useState(null),y=d.useRef(null);function w(A){g(null),f&&f(A)}function b(A){if(y.current===A){y.current=null;return}g(null),f&&f({action:null,option:null})}const S=d.useCallback(A=>{g(A.target),y.current=A.nativeEvent||A,A.preventDefault()},[]);d.useImperativeHandle(n,()=>({show:S}),[S]);function k(A){let T=A.target;for(;!T.dataset.menuIgnore;)g(T),T=T.parentNode}return o.jsxs(o.Fragment,{children:[o.jsx("span",{onClick:k,"data-menu-ignore":"true",children:u}),h?o.jsx(oy,{children:o.jsx(py,{css:l,at:s,parent:h,options:r,onClick:w,onCancel:b})}):null]})}),gE=d.forwardRef(function(t,n){const{options:r,at:s="bottom",resolver:l=null,dataKey:u="contextId",filter:f=null,css:h="",children:g,onClick:y}=t,w=d.useRef(null),b=d.useCallback((S,k)=>{w.current.show(S,k)},[]);return d.useImperativeHandle(n,()=>({show:b}),[b]),o.jsxs(o.Fragment,{children:[g?o.jsx("span",{onContextMenu:b,"data-menu-ignore":"true",children:g}):null,o.jsx(KS,{css:h,at:s,options:r,resolver:l,dataKey:u,filter:f,ref:w,onClick:y})]})}),vE={uploader:{B:"B",KB:"KB",MB:"MB",GB:"GB",TB:"TB",PB:"PB",EB:"EB","Drop files here or":"Drop files here or","select files":"select files"}};let yE=class{constructor(n,r,s,l,u){this.setFiles=n,this.setReady=r,this.setSignal=s,this.setDrag=l,u&&u.length&&this.setFiles(u)}open(n){this.setSignal(["click",n||{}])}getState(){let n="server";const r=this.files;for(let s=0;s<r.length;s++){if(r[s].status==="client")return"client";r[s].status==="error"&&(n="error")}return n}droparea(n,r){r=r||{};const s=()=>{r.dragEnter&&r.dragEnter(),this.setDrag(!0)},l=()=>{r.dragLeave&&r.dragLeave(),this.setDrag(!1)},u=h=>{h.preventDefault()},f=h=>{h.preventDefault(),this.setDrag(!1),this.setSignal(["drop",r,h]),r.dragLeave&&r.dragLeave(),r.drop&&r.drop()};return n.addEventListener("dragenter",s),n.addEventListener("dragleave",l),n.addEventListener("dragover",u,!0),n.addEventListener("drop",f,!0),()=>{n.removeEventListener("dragenter",s),n.removeEventListener("dragleave",l),n.removeEventListener("dragover",u,!0),n.removeEventListener("drop",f,!0)}}updateFile(n,r){const s=this.files.findIndex(u=>u.id===n);if(s===-1)return;const l=[...this.files];return l[s]={...l[s],...r},this.files=l,this.setFiles(this.files),this.files[s]}deleteFile(n){this.files=this.files.filter(r=>r.id!==n),this.setFiles(this.files)}addFile(n,r){r?this.files=[...this.files,n]:this.files=[n],this.setFiles(this.files)}deleteAll(){this.files=[],this.setFiles(this.files)}};function QS(t){const[n,r]=d.useState([]),[s,l]=d.useState(Promise.resolve(null)),[u,f]=d.useState(null),[h,g]=d.useState(!1),y=d.useRef();return y.current||(y.current=new yE(r,l,f,g,t)),y.current.files=n,y.current.ready=s,y.current.signal=u,y.current.drag=h,y.current}function bE(t,n){{if(t){const r=t.getGroup(n);if(r)return r}return Sm(vE).getGroup(n)}}const wE=()=>Math.random().toString(36).substr(2,9),xE=({data:t,accept:n="",multiple:r=!0,folder:s=!1,uploadURL:l="",apiOnly:u=!1,disabled:f=!1,children:h,onChange:g,onUpload:y})=>{const w=d.useRef(null),b=d.useRef(null),[S,k]=d.useState({}),A=QS(),T=t||A,j=d.useContext(sr.i18n),I=bE(j,"uploader");d.useEffect(()=>{w.current&&s&&(w.current.webkitdirectory=!0)},[s]),d.useEffect(()=>{if(!u&&b.current&&!f)return T.droparea(b.current)},[u,f,b]);const N=q=>{const W=new FormData;return W.append("upload",q.file),fetch(l,{method:"POST",body:W}).then(Y=>Y.json()).then(Y=>({id:q.id,...Y}),()=>({id:q.id,status:"error"})).catch(Y=>(console.log(Y),{id:q.id,status:"error"}))},P=(q,W)=>{const Y=T.updateFile(q,W),V={...Y,status:T.getState()};Y&&Y.uploaded&&Y.uploaded(V),y&&y(V),Y.temp&&T.deleteFile(Y.id)},H=q=>{if(!q)return;const W=typeof l=="function"?l(q):N(q);T.setReady(W.then(Y=>{Y.status=Y.status||"server",P(q.id,Y)}).catch(Y=>{P(q.id,{status:"error",error:Y})}))},F=(q,W)=>{const Y={...W||S,id:wE(),status:"client",name:q.name,file:q};Y.selected&&Y.selected(Y),g&&g(Y),T.addFile(Y,r),H(Y),w.current&&(w.current.value="")},$=(q,W,Y)=>{q.isFile?q.file(V=>{F(V,Y)}):q.isDirectory&&q.createReader().readEntries(V=>{V.forEach(he=>{$(he,W+he.name+"/",Y)})})},D=q=>{Array.from(q.target.files).forEach(W=>F(W))},K=(q,W)=>{Array.from(q.dataTransfer.items).forEach(Y=>{const V=Y.webkitGetAsEntry();V&&$(V,"",W)})},z=()=>{w.current&&w.current.click()};return d.useEffect(()=>{if(T.signal){const[q,W,Y]=T.signal;k(W),q==="click"?z():q==="drop"&&K(Y,W),T.setSignal(null)}},[T.signal]),u?o.jsxs(o.Fragment,{children:[o.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:w,onChange:D,accept:n,multiple:r,disabled:f}),h]}):o.jsxs("div",{className:`wx-at1A8tb8 wx-label ${T.drag?"wx-active":""} ${f?"wx-disabled":""}`,ref:b,children:[o.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:w,onChange:D,accept:n,multiple:r,disabled:f}),h||o.jsx("div",{className:"wx-at1A8tb8 wx-dropzone",children:o.jsxs("span",{children:[I("Drop files here or")," ",o.jsx("span",{className:"wx-at1A8tb8 wx-action",onClick:z,children:I("select files")})]})})]})};new Date().valueOf();function SE(t,n){if(Object.keys(t).length!==Object.keys(n).length)return!1;for(const r in n){const s=t[r],l=n[r];if(!Dh(s,l))return!1}return!0}function Dh(t,n){if(typeof t=="number"||typeof t=="string"||typeof t=="boolean"||t===null)return t===n;if(typeof t!=typeof n||(t===null||n===null)&&t!==n||t instanceof Date&&n instanceof Date&&t.getTime()!==n.getTime())return!1;if(typeof t=="object")if(Array.isArray(t)&&Array.isArray(n)){if(t.length!==n.length)return!1;for(let r=t.length-1;r>=0;r--)if(!Dh(t[r],n[r]))return!1;return!0}else return SE(t,n);return t===n}function _v(t){if(typeof t!="object"||t===null)return t;if(t instanceof Date)return new Date(t);if(t instanceof Array)return t.map(_v);const n={};for(const r in t)n[r]=_v(t[r]);return n}var YS=2,CE=class{constructor(t){t&&(this._writable=t.writable,this._async=t.async),this._values={},this._state={}}setState(t,n=0){const r={};return this._wrapProperties(t,this._state,this._values,"",r,n),r}getState(){return this._values}getReactive(){return this._state}_wrapProperties(t,n,r,s,l,u){for(const f in t){const h=n[f],g=r[f],y=t[f];if(h&&(g===y&&typeof y!="object"||y instanceof Date&&g instanceof Date&&g.getTime()===y.getTime()))continue;const w=s+(s?".":"")+f;h?(h.__parse(y,w,l,u)&&(r[f]=y),u&YS?l[w]=h.__trigger:h.__trigger()):(y&&y.__reactive?n[f]=this._wrapNested(y,y,w,l):n[f]=this._wrapWritable(y),r[f]=y),l[w]=l[w]||null}}_wrapNested(t,n,r,s){const l=this._wrapWritable(t);return this._wrapProperties(t,l,n,r,s,0),l.__parse=(u,f,h,g)=>(this._wrapProperties(u,l,n,f,h,g),!1),l}_wrapWritable(t){const n=[],r=function(){for(let s=0;s<n.length;s++)n[s](t)};return{subscribe:s=>(n.push(s),this._async?setTimeout(s,1,t):s(t),()=>{const l=n.indexOf(s);l>=0&&n.splice(l,1)}),__trigger:()=>{n.length&&(this._async?setTimeout(r,1):r())},__parse:function(s){return t=s,!0}}}},kE=class{constructor(t,n,r,s){typeof t=="function"?this._setter=t:this._setter=t.setState.bind(t),this._routes=n,this._parsers=r,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(l=>{l.in.forEach(u=>{const f=this._triggers.get(u)||[];f.push(l),this._triggers.set(u,f)}),l.out.forEach(u=>{const f=this._sources.get(u)||{};l.in.forEach(h=>f[h]=!0),this._sources.set(u,f)})}),this._routes.forEach(l=>{l.length=Math.max(...l.in.map(u=>XS(u,this._sources,1)))}),this._bus=s}init(t){const n={};for(const r in t)if(this._prev[r]!==t[r]){const s=this._parsers[r];n[r]=s?s(t[r]):t[r]}this._prev=this._prev?{...this._prev,...t}:{...t},this.setState(n),this._bus&&this._bus.exec("init-state",n)}setStateAsync(t){const n=this._setter(t,YS);return this._async?Object.assign(this._async.signals,n):this._async={signals:n,timer:setTimeout(this._applyState.bind(this),1)},n}_applyState(){const t=this._async;if(t){this._async=null,this._triggerUpdates(t.signals,[]);for(const n in t.signals){const r=t.signals[n];r&&r()}}}setState(t,n=[]){const r=this._setter(t);return this._triggerUpdates(r,n),r}_triggerUpdates(t,n){const r=Object.keys(t),s=!n.length;n=n||[];for(let l=0;l<r.length;l++){const u=r[l],f=this._triggers.get(u);f&&f.forEach(h=>{n.indexOf(h)==-1&&n.push(h)})}s&&this._execNext(n)}_execNext(t){for(;t.length;){t.sort((r,s)=>r.length<s.length?1:-1);const n=t[t.length-1];t.splice(t.length-1),n.exec(t)}}};function XS(t,n,r){const s=n.get(t);if(!s)return r;const l=Object.keys(s).map(u=>XS(u,n,r+1));return Math.max(...l)}var ME=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(t,n,r){let s=this._handlers[t];s?r&&r.intercept?s.unshift(n):s.push(n):s=this._handlers[t]=[n],r&&r.tag&&this._tag.set(n,r.tag)}intercept(t,n,r){this.on(t,n,{...r,intercept:!0})}detach(t){for(const n in this._handlers){const r=this._handlers[n];for(let s=r.length-1;s>=0;s--)this._tag.get(r[s])===t&&r.splice(s,1)}}async exec(t,n){const r=this._handlers[t];if(r)for(let s=0;s<r.length;s++){const l=r[s](n);if(l===!1||l&&l.then&&await l===!1)return}return this._nextHandler&&await this._nextHandler.exec(t,n),n}setNext(t){return this._nextHandler=t}};function AE(t){return n=>n[t]}function TE(t){return(n,r)=>n[t]=r}function pc(t,n){return(n.getter||AE(n.id))(t)}function Wg(t,n,r){return(n.setter||TE(n.id))(t,r)}function NE(t,n){const r=document.createElement("a");r.href=URL.createObjectURL(t),r.download=n,document.body.appendChild(r),r.click(),document.body.removeChild(r)}function cc(t,n){let r=pc(t,n)??"";return n.template?r=n.template(r,t,n):n.optionsMap&&(Array.isArray(r)?r=r.map(s=>n.optionsMap.get(s)).join(", "):r=n.optionsMap.get(r)),typeof r>"u"?"":r+""}function RE(t,n){const r=/\n|"|;|,/;let s="";const l=n.rows||`
178
- `,u=n.cols||" ",f=t._columns,h=t.flatData;n.header!==!1&&f[0].header&&(s=lx("header",f,s,u,l));for(let g=0;g<h.length;g++){const y=[];for(let w=0;w<f.length;w++){let b=cc(h[g],f[w]);r.test(b)&&(b='"'+b.replace(/"/g,'""')+'"'),y.push(b)}s+=(s?l:"")+y.join(u)}return n.footer!==!1&&f[0].footer&&(s=lx("footer",f,s,u,l)),s}function lx(t,n,r,s,l){const u=/\n|"|;|,/;for(let f=0;f<n[0][t].length;f++){const h=[];for(let g=0;g<n.length;g++){let y=(n[g][t][f].text||"")+"";u.test(y)&&(y='"'+y.replace(/"/g,'""')+'"'),h.push(y)}r+=(r?l:"")+h.join(s)}return r}const EE="portrait",jE=100,DE="a4",IE={a3:{width:11.7,height:16.5},a4:{width:8.27,height:11.7},letter:{width:8.5,height:11}};function LE(t,n){const r=[];let s=[],l=0;const u=t.filter(h=>!h.hidden),f=PE(n);return u.forEach((h,g)=>{l+h.width<=f?(l+=h.width,s.push(h)):(s.length&&r.push(s),s=[h],l=h.width),g===u.length-1&&s.length&&r.push(s)}),r}function cx(t,n,r){const s=[];return t.forEach((l,u)=>{const f=l[n];for(let h=0;h<r.length;h++){s[h]||(s[h]=[]);const g={...f[h]};if(s[h][u]!==null){if(!u&&!g.rowspan&&!g.colspan){let y=1,w=t[u+y][n][h],b=g.width;for(;!w.rowspan&&!w.colspan;)y++,w=t[u+y][n][h],b+=w.width;g.colspan=y,g.width=b,g.height=r[h]}if(s[h].push(g),!g.collapsed&&g.colspan>1){let y=g.colspan-1;if(g.colspan+u>t.length){const w=g.colspan-(g.colspan+u-t.length);g.colspan=w,g.width=t.slice(u,u+y+1).reduce((b,S)=>b+S.width,0),w>1&&(y=w-1)}for(let w=0;w<y;w++)s[h].push(null)}if(g.rowspan>1){const y=g.rowspan;for(let w=1;w<y;w++)s[h+w]||(s[h+w]=[]),s[h+w].push(null)}}}if(l.collapsed)for(let h=0;h<s.length;h++){const g=s[h],y=g[u];if(y&&y.collapsed){if(g[u]=null,!h)break}else{const w=y||g.findLast(b=>b?.colspan>=1);w&&(w.colspan=w.colspan-1,w.width=w.width-l.width)}}}),s.map(l=>l.filter(u=>u&&u.colspan!==0))}function PE(t){const{mode:n,ppi:r,paper:s}=t,{width:l,height:u}=IE[s];return _E(n==="portrait"?l:u,r)}function _E(t,n){return t*n}function OE(t={}){const{mode:n,ppi:r,paper:s}=t;return{mode:n||EE,ppi:r||jE,paper:s||DE}}function ZS(t,n){return t.flexgrow?`min-width:${n}px;width:auto`:`width:${t.width}px; max-width:${t.width}px; height:${t.height}px`}function FE(t,n,r){let s=t[r.id];if(r.filter.type==="richselect"&&s){const l=r.filter.config?.options||n.find(({id:u})=>u==r.id).options;l&&(s=l.find(({id:u})=>u==s).label)}return s??""}const ux=["resize-column","hide-column","update-cell"],BE=["delete-row","update-row","update-cell"],HE=["move-item"],zE=["resize-column","move-item"];class $E{undo=[];redo=[];progress={};in;getState;setState;_previousValues={};constructor(n,r,s){this.in=n,this.getState=r,this.setState=s,this.setHandlers(),this.resetStateHistory()}getHandlers(){return{"add-row":{handler:n=>({action:"delete-row",data:{id:n.id},source:{action:"add-row",data:n}})},"delete-row":{handler:n=>{const{id:r}=n,{data:s}=this.getPrev(),l=s.findIndex(u=>u.id===r);return{action:"add-row",data:{id:r,row:s[l],before:l<s.length-1?s[l+1].id:void 0},source:{action:"delete-row",data:n}}}},"update-cell":{handler:n=>{const{id:r,column:s}=n,l=this.getRow(r),u=this.getColumn(s),f=pc(l,u);return Dh(f,n.value)?null:{action:"update-cell",data:{id:r,column:s,value:f},source:{action:"update-cell",data:n}}}},"update-row":{handler:n=>{const{id:r,row:s}=n,l=this.getRow(r);for(const u in s)Object.keys(l).includes(u)||(l[u]=void 0);return{action:"update-row",data:{id:r,row:l},source:{action:"update-row",data:n}}}},"copy-row":{handler:n=>{const{id:r}=n,{data:s}=this.getState(),l=s.findIndex(f=>f.id===r),u=s[l];return{action:"delete-row",data:{id:r},source:{action:"add-row",data:{id:r,row:u,before:l<s.length-1?s[l+1].id:void 0}}}}},"resize-column":{handler:n=>{const{id:r,width:s}=n,l=this.getColumn(r),{_sizes:u}=this.getState();return{action:"resize-column",data:{id:r,width:l.width??u.columnWidth},source:{action:"resize-column",data:{id:r,width:s}}}}},"hide-column":{handler:n=>{const{id:r}=n,s=this.getColumn(r);return{action:"hide-column",data:{id:r,mode:s.hidden},source:{action:"hide-column",data:n}}}},"collapse-column":{handler:n=>{const{id:r,row:s,mode:l}=n;return{action:"collapse-column",data:{id:r,row:s,mode:typeof l=="boolean"?!l:l},source:{action:"collapse-column",data:n}}}},"move-item":{handler:n=>{const{id:r,target:s,mode:l}=n,{flatData:u}=this.getPrev(),f=u.findIndex(h=>h.id===r);return{action:"move-item",data:{id:r,target:u[f+(f?-1:1)].id,mode:f?"after":"before"},source:{action:"move-item",data:{id:r,target:s,mode:l}}}}},"open-row":{handler:n=>{const{id:r,nested:s}=n;return{action:"close-row",data:{id:r,nested:s},source:{action:"open-row",data:n}}}},"close-row":{handler:n=>{const{id:r,nested:s}=n;return{action:"open-row",data:{id:r,nested:s},source:{action:"close-row",data:n}}}}}}resetHistory(){this.undo=[],this.redo=[],this.progress={},this.resetStateHistory()}getPrev(){return this._previousValues}setHandlers(){const n=this.getHandlers();for(const r in n)this.in.intercept(r,s=>{if(!(s.eventSource==="undo"||s.eventSource==="redo"||s.skipUndo)){if(zE.includes(r)){(s.inProgress&&!this.progress[r]||typeof s.inProgress!="boolean")&&(HE.includes(r)&&this.setPrev("flatData"),ux.includes(r)&&this.setPrev("columns")),this.progress[r]=s.inProgress;return}BE.includes(r)&&this.setPrev("data"),ux.includes(r)&&this.setPrev("columns")}}),this.in.on(r,s=>{if(s.eventSource==="undo"||s.eventSource==="redo"||s.skipUndo||s.inProgress)return;const l=n[r].handler(s);l&&this.addToHistory(l)})}setPrev(n){this._previousValues[n]=_v(this.getState()[n])}addToHistory(n){this.undo.push(n),this.redo=[],this.setStateHistory()}handleUndo(){if(!this.undo.length)return;const n=this.undo.pop();this.redo.push({...n.source,source:n}),this.in.exec(n.action,{...n.data,eventSource:"undo"}),this.setStateHistory()}handleRedo(){if(!this.redo.length)return;const n=this.redo.pop();this.undo.push({...n.source,source:n}),this.in.exec(n.action,{...n.data,eventSource:"redo"}),this.setStateHistory()}resetStateHistory(){this.setState({history:{undo:0,redo:0}})}setStateHistory(){this.setState({history:{undo:this.undo.length,redo:this.redo.length}})}getRow(n){const{data:r}=this.getPrev();return this.getState().tree?this.getTreeRow(r,n):r.find(s=>s.id===n)}getTreeRow(n,r){for(let s=0;s<n.length;s++){if(n[s].id===r)return n[s];if(n[s].data){const l=this.getTreeRow(n[s].data,r);if(l)return l}}return null}getColumn(n){const{columns:r}=this.getPrev();return r.find(s=>s.id===n)}}function JS(t,n){return typeof t>"u"||t===null?-1:typeof n>"u"||n===null?1:t===n?0:t>n?1:-1}function UE(t,n){return-JS(t,n)}function qE(t,n){if(typeof n.sort=="function")return function(s,l){const u=n.sort(s,l);return t==="asc"?u:-u};const r=t==="asc"?JS:UE;return function(s,l){return r(pc(s,n),pc(l,n))}}function WE(t,n){if(!t||!t.length)return;const r=t.map(s=>{const l=n.find(u=>u.id==s.key);return qE(s.order,l)});return t.length===1?r[0]:function(s,l){for(let u=0;u<r.length;u++){const f=r[u](s,l);if(f!==0)return f}return 0}}const Op=28,GE=20;function VE(){if(typeof document>"u")return"willow";const t=document.querySelector('[class^="wx"][class$="theme"]');return t?t.className.substring(3,t.className.length-6):"willow"}function hh(t,n,r,s,l){const u=document.createElement("div"),f=document.createElement("div"),h=document.body;l=l?`${l}px`:"auto";let g,y;f.className=n,u.classList.add(`wx-${r}-theme`),u.style.cssText=`height:auto;position:absolute;top:0px;left:100px;overflow:hidden;width=${l};white-space:nowrap;`,u.appendChild(f),h.appendChild(u),typeof t!="object"&&(t=[t]);for(let w=0;w<t.length;w++){f.innerText=t[w]+"";const b=u.getBoundingClientRect(),S=Math.ceil(b.width)+(s&&s.length?s[w]:0),k=Math.ceil(b.height);g=Math.max(g||0,S),y=Math.max(y||0,k)}return u.remove(),{width:g,height:y}}function dx(t,n,r,s,l){const u=[];for(let f=0;f<t.length;f++){const h=t[f][n],g=h.length;for(let y=0;y<g;y++){const{text:w,vertical:b,collapsed:S,rowspan:k,css:A}=h[y];if(!w){u[y]=Math.max(u[y]||0,s);continue}let T=0;if(b&&!S){let j=`wx-measure-cell-${n}`;if(j+=A?` ${A}`:"",T=hh(w,j,l).width,(k>1||!h[y+1])&&r>y+1){const I=k||r-y,N=u.slice(y,y+I).reduce((P,H)=>P+H,0);if(N<T){const P=Math.ceil((T-N)/I);for(let H=y;H<y+I;H++)u[H]=(u[H]||s)+P}continue}}u[y]=Math.max(u[y]||s,T)}}return u}function KE(t,n,r){const s=[],l=[];let u="wx-measure-cell-body";u+=t.css?` ${t.css}`:"";for(let f=0;f<n.length;f++){const h=n[f],g=cc(h,t);g&&(s.push(g),t.treetoggle?l.push(n[f].$level*Op+(n[f].$count?Op:0)+(t.draggable?Op:0)):t.draggable&&l.push(Op))}return hh(s,u,r,l).width}function QE(t,n){const r="wx-measure-cell-header",s=t.sort?GE:0;let l=t.header;if(typeof l=="string")return hh(l,r,n).width+s;let u;Array.isArray(l)||(l=[l]);for(let f=0;f<l.length;f++){const h=l[f],g=typeof h=="string"?h:h.text,y=r+(typeof h=="string"?"":` ${h.css}`);let w=hh(g,y,n).width;f===l.length-1&&(w+=s),u=Math.max(u||0,w)}return u}const YE={text:(t,n)=>t?t.toString().toLowerCase().indexOf(n.toLowerCase())!==-1:!n,richselect:(t,n)=>typeof n!="number"&&!n?!0:t==n,datepicker:(t,n)=>n?t&&ZE(t,n):!0,multiselect:(t,n)=>!n||n?.length===0?!0:Array.isArray(t)?t?.some(r=>n.includes(r)):t&&n.includes(t)};function eC(t){return YE[t]}function XE(t,n){const r=[];for(const s in t){const l=n.find(g=>g.id==s),{config:u,type:f}=l.header.find(g=>g.filter).filter,h=t[s];r.push(g=>{const y=pc(g,l);return u?.handler?u.handler(y,h):eC(f)(y,h)})}return s=>{for(let l=0;l<r.length;l++)if(!r[l](s))return!1;return!0}}function ZE(t,n){return t.getFullYear()===n.getFullYear()&&t.getMonth()===n.getMonth()&&t.getDate()===n.getDate()}let JE=class extends CE{in;_router;_branches;_xlsxWorker;_historyManager;constructor(n){super({writable:n,async:!1});const r={rowHeight:37,columnWidth:160,headerHeight:36,footerHeight:36};this._router=new kE(super.setState.bind(this),[{in:["columns","sizes","_skin"],out:["_columns","_sizes"],exec:l=>{const{columns:u,sizes:f,_skin:h}=this.getState(),g=this.copyColumns(u),y=g.reduce((S,k)=>Math.max(k.header.length,S),0),w=g.reduce((S,k)=>Math.max(k.footer.length,S),0);g.forEach(this.setCollapsibleColumns);const b=this.normalizeSizes(g,f,y,w,h);for(let S=0;S<g.length;S++)this.normalizeColumns(g,S,"header",y,b),this.normalizeColumns(g,S,"footer",w,b);this.setState({_columns:g,_sizes:b},l)}},{in:["data","tree","_filterIds"],out:["flatData","_rowHeightFromData"],exec:l=>{const{data:u,tree:f,dynamic:h,_filterIds:g}=this.getState(),y=g&&new Set(g),w=f?this.flattenRows(u,[],g):y?u.filter(S=>y.has(S.id)):u,b=!h&&w.some(S=>S.rowHeight);this.setState({flatData:w,_rowHeightFromData:b},l)}}],{sizes:l=>({...r,...l})});const s=this.in=new ME;s.on("close-editor",({ignore:l})=>{const{editor:u}=this.getState();u&&(l||s.exec("update-cell",u),this.setState({editor:null}))}),s.on("open-editor",({id:l,column:u})=>{let f=this.getState().editor;f&&s.exec("close-editor",{});const h=this.getRow(l),g=u?this.getColumn(u):this.getNextEditor(h);if(g?.editor){let y=g.editor;if(typeof y=="function"&&(y=y(h,g)),!y)return;f={column:g.id,id:l,value:pc(h,g)??"",renderedValue:cc(h,g),type:y.type||y},typeof y=="object"&&y.config&&(f.config=y.config,y.config.options&&(f.options=y.config.options)),g.options&&!f.options&&(f.options=g.options),this.setState({editor:f})}}),s.on("editor",({value:l})=>{let u=this.getState().editor;if(u){u={...u},u.value=l;const f=this.getColumn(u.column),h={...this.getRow(u.id)};Wg(h,f,l),u.renderedValue=cc(h,f),this.setState({editor:u})}}),s.on("add-row",l=>{const u=this.getState();let{data:f}=u;const{select:h,_filterIds:g}=u,{row:y,before:w,after:b,select:S}=l;if(l.id=y.id=l.id||y.id||Fp(),w||b){const A=w||b,T=f.findIndex(j=>j.id===A);f=[...f],f.splice(T+(b?1:0),0,l.row)}else f=[...f,l.row];const k={data:f};g&&(k._filterIds=[...g,l.id]),this.setState(k),!(typeof S=="boolean"&&!S)&&(S||h)&&s.exec("select-row",{id:y.id,show:!0})}),s.on("delete-row",l=>{const{data:u,selectedRows:f,focusCell:h,editor:g}=this.getState(),{id:y}=l,w={data:u.filter(b=>b.id!==y)};this.isSelected(y)&&(w.selectedRows=f.filter(b=>b!==y)),g?.id===y&&(w.editor=null),this.setState(w),h?.row===y&&this.in.exec("focus-cell",{eventSource:"delete-row"})}),s.on("update-cell",l=>{const u=this.getState();let{data:f}=u;f=[...f];const{tree:h}=u,{id:g,column:y,value:w}=l,b=this.getColumn(y);if(h){const S={...this._branches[g]};Wg(S,b,w);const k=this.updateTreeRow(S);S.$parent===0&&(f=k)}else{const S=f.findIndex(A=>A.id===g),k={...f[S]};Wg(k,b,w),f[S]=k}this.setState({data:f})}),s.on("update-row",l=>{let{data:u}=this.getState();const{id:f,row:h}=l,g=u.findIndex(y=>y.id===f);u=[...u],u[g]={...u[g],...h},this.setState({data:u})}),s.on("select-row",({id:l,toggle:u,range:f,mode:h,show:g,column:y})=>{const w=this.getState(),{focusCell:b}=w;let{selectedRows:S}=w;if(S.length||(f=u=!1),f){const{data:k}=this.getState();let A=k.findIndex(j=>j.id===S[S.length-1]),T=k.findIndex(j=>j.id===l);A>T&&([A,T]=[T,A]),k.slice(A,T+1).forEach(j=>{this.isSelected(j.id)||S.push(j.id)})}else if(u&&this.isSelected(l)){if(h===!0)return;S=S.filter(k=>k!==l)}else if(u){if(h===!1)return;S.push(l)}else S=[l];this.setState({selectedRows:[...S]}),b?.row!==l&&this.in.exec("focus-cell",{eventSource:"select-row"}),g&&this.in.exec("scroll",{row:l,column:y})}),this.in.on("focus-cell",l=>{const{row:u,column:f,eventSource:h}=l,{_columns:g,split:y}=this.getState();u&&f?(this.setState({focusCell:{row:u,column:f}}),h!=="click"&&((!y.left||g.findIndex(w=>w.id===l.column)>=y.left)&&(!y.right||g.findIndex(w=>w.id===l.column)<g.length-y.right)?this.in.exec("scroll",{row:u,column:f}):this.in.exec("scroll",{row:u}))):this.setState({focusCell:null})}),s.on("resize-column",l=>{const{id:u,auto:f,maxRows:h,inProgress:g}=l;if(g===!1)return;let y=l.width||0;const w=[...this.getState().columns],b=this.getColumn(u);if(f){if(f==="data"||f===!0){const{flatData:S,_skin:k}=this.getState();let A=S.length;h&&(A=Math.min(h,A));const T=S.slice(0,A);y=KE(b,T,k)}if(f==="header"||f===!0){const{_skin:S}=this.getState();y=Math.max(QE(b,S),y)}}b.width=Math.max(17,y),delete b.flexgrow,this.setState({columns:w})}),s.on("hide-column",l=>{const{id:u,mode:f}=l,h=[...this.getState().columns],g=this.getColumn(u),y=h.reduce((w,b)=>w+(b.hidden?0:1),0);!f||y>1?(g.hidden=!g.hidden,this.setState({columns:h})):l.skipUndo=!0}),s.on("sort-rows",l=>{const{key:u,add:f,sort:h}=l,g=this.getState(),{columns:y,data:w,tree:b}=g;if(h){const N=[...w];N.sort(h),this.setState({data:N});return}const{order:S="asc"}=l;let k=g.sortMarks;const A=Object.keys(k),T=A.length;!f||!T||T===1&&k[u]?k={[u]:{order:S}}:(T===1&&(k[A[0]]={...k[A[0]],index:0}),k={...k,[u]:{order:S,index:typeof f=="number"?f:k[u]?.index??T}});const j=Object.keys(k).sort((N,P)=>k[N].index-k[P].index).map(N=>({key:N,order:k[N].order}));this.setState({sortMarks:k});const I=WE(j,y);if(I){const N=[...w];b?this.sortTree(N,I):N.sort(I),this.setState({data:N})}}),s.on("filter-rows",l=>{const{value:u,key:f,filter:h}=l;if(!Object.keys(l).length){this.setState({filterValues:{},_filterIds:null});return}const g=this.getState(),{data:y,tree:w,_columns:b}=g;let S=g.filterValues;const k={};f&&(S={...S,[f]:u},k.filterValues=S);const A=h??XE(S,b);let T=[];w?T=this.filterTree(y,A,T):y.forEach(j=>{A(j)&&T.push(j.id)}),k._filterIds=T,this.setState(k)}),s.on("collapse-column",l=>{const{id:u,row:f,mode:h}=l,g=[...this.getState().columns],y=this.getColumn(u).header,w=Array.isArray(y)?y[f]:y;typeof w=="object"&&(w.collapsed=h??!w.collapsed,this.setState({columns:g}))}),s.on("move-item",l=>{const{id:u,inProgress:f}=l;let{target:h,mode:g="after"}=l;const{data:y,flatData:w,tree:b}=this.getState(),S=w.findIndex(T=>T.id===u);let k;if(g==="up"||g==="down"){if(g==="up"){if(S===0)return;k=S-1,g="before"}else if(g==="down"){if(S===w.length-1)return;k=S+1,g="after"}h=w[k]&&w[k].id}else k=w.findIndex(T=>T.id===h);if(S===-1||k===-1||f===!1)return;let A;b||(A=this.moveItem(u,h,y,g)),this.setState({data:b?this.normalizeTreeRows(A):A})}),s.on("copy-row",l=>{const{id:u,target:f,mode:h="after"}=l,g=this.getState(),{flatData:y,_filterIds:w}=g;let{data:b}=g;const S=this.getRow(u);if(!S)return;const k={...S,id:Fp()};l.id=k.id;const A=y.findIndex(j=>j.id===f);if(A===-1)return;b.splice(A+(h==="after"?1:0),0,k),b=[...b];const T={data:b};w&&(T._filterIds=[...w,k.id]),this.setState(T)}),s.on("open-row",l=>{const{id:u,nested:f}=l;this.toggleBranch(u,!0,f)}),s.on("close-row",l=>{const{id:u,nested:f}=l;this.toggleBranch(u,!1,f)}),s.on("export-data",l=>new Promise((u,f)=>{const h=l.format||"csv",g=`${l.fileName||"data"}.${h}`;if(h==="csv"){const y=RE(this.getState(),l.csv||{});l.download!==!1?NE(new Blob(["\uFEFF"+y],{type:"text/csv"}),g):l.result=y,u(!0)}else f()})),s.on("hotkey",({key:l,event:u,isInput:f})=>{switch(l){case"arrowup":{const{flatData:h,focusCell:g,select:y}=this.getState();if(u.preventDefault(),f)return;const w=g?g.column:this._getFirstVisibleColumn()?.id,b=g?this.getPrevRow(g.row)?.id:h[h.length-1]?.id;w&&b&&(this.in.exec("focus-cell",{row:b,column:w,eventSource:"key"}),y&&this.in.exec("select-row",{id:b}));break}case"arrowdown":{const{flatData:h,focusCell:g,select:y}=this.getState();if(u.preventDefault(),f)return;const w=g?g.column:this._getFirstVisibleColumn()?.id,b=g?this.getNextRow(g.row)?.id:h[0]?.id;w&&b&&(this.in.exec("focus-cell",{row:b,column:w,eventSource:"key"}),y&&this.in.exec("select-row",{id:b}));break}case"arrowright":{const{focusCell:h}=this.getState();if(f)return;if(u.preventDefault(),h){const g=this.getNextColumn(h.column,!0)?.id;g&&this.in.exec("focus-cell",{row:h.row,column:g,eventSource:"key"})}break}case"arrowleft":{const{focusCell:h}=this.getState();if(f)return;if(u.preventDefault(),h){const g=this.getPrevColumn(h.column,!0)?.id;g&&this.in.exec("focus-cell",{row:h.row,column:g,eventSource:"key"})}break}case"tab":{const{editor:h,focusCell:g,select:y}=this.getState();if(h){u.preventDefault();const w=h.column;let b=h.id,S=this.getNextEditor(this.getRow(b),this.getColumn(w));if(!S){const k=this.getNextRow(b);k&&(b=k.id,S=this.getNextEditor(k))}S&&(this.in.exec("open-editor",{id:b,column:S.id}),this.in.exec("focus-cell",{row:b,column:S.id,eventSource:"key"}),y&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}else g&&this.in.exec("focus-cell",{eventSource:"key"});break}case"shift+tab":{const{editor:h,focusCell:g,select:y}=this.getState();if(h){u.preventDefault();const w=h.column;let b=h.id,S=this.getPrevEditor(this.getRow(b),this.getColumn(w));if(!S){const k=this.getPrevRow(b);k&&(b=k.id,S=this.getPrevEditor(k))}S&&(this.in.exec("open-editor",{id:b,column:S.id}),this.in.exec("focus-cell",{row:b,column:S.id,eventSource:"key"}),y&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}else g&&this.in.exec("focus-cell",{eventSource:"key"});break}case"escape":{const{editor:h}=this.getState();h&&(this.in.exec("close-editor",{ignore:h.type!="multiselect"}),this.in.exec("focus-cell",{row:h.id,column:h.column,eventSource:"key"}));break}case"f2":{const{editor:h,focusCell:g}=this.getState();!h&&g&&this.in.exec("open-editor",{id:g.row,column:g.column});break}case"enter":{const{focusCell:h,tree:g}=this.getState();if(!f&&g&&h&&this.getColumn(h.column).treetoggle){const y=this.getRow(h.row);if(!y.data)return;this.in.exec(y.open?"close-row":"open-row",{id:h.row,nested:!0})}break}case"home":{const{editor:h,focusCell:g}=this.getState();if(!h&&g){u.preventDefault();const y=this._getFirstVisibleColumn()?.id;this.in.exec("focus-cell",{row:g.row,column:y,eventSource:"key"})}break}case"ctrl+home":{const{editor:h,focusCell:g,flatData:y,select:w}=this.getState();if(!h&&g){u.preventDefault();const b=y[0]?.id,S=this._getFirstVisibleColumn()?.id;b&&S&&(this.in.exec("focus-cell",{row:b,column:S,eventSource:"key"}),w&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}break}case"end":{const{editor:h,focusCell:g}=this.getState();if(!h&&g){u.preventDefault();const y=this._getLastVisibleColumn()?.id,w=g.row;this.in.exec("focus-cell",{row:w,column:y,eventSource:"key"})}break}case"ctrl+end":{const{editor:h,focusCell:g,flatData:y,select:w}=this.getState();if(!h&&g){u.preventDefault();const b=y.at(-1).id,S=this._getLastVisibleColumn()?.id;b&&S&&(this.in.exec("focus-cell",{row:b,column:S,eventSource:"key"}),w&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}break}case"ctrl+z":{this.in.exec("undo",{});break}case"ctrl+y":{this.in.exec("redo",{});break}}}),s.on("scroll",l=>{const{_columns:u,split:f,_sizes:h,flatData:g,dynamic:y,_rowHeightFromData:w}=this.getState();let b=-1,S=-1,k=0,A=0;if(l.column){b=0;const T=u.findIndex(j=>j.id===l.column);k=u[T].width;for(let j=f.left??0;j<T;j++){const I=u[j];I.hidden||(b+=I.width)}}if(l.row&&!y){const T=g.findIndex(j=>j.id===l.row);T>=0&&(w?(S=g.slice(0,T).reduce((j,I)=>j+(I.rowHeight||h.rowHeight),0),A=g[T].rowHeight):S=h.rowHeight*T)}this.setState({scroll:{top:S,left:b,width:k,height:A||h.rowHeight}})}),s.on("scroll-to",l=>{const u={};l.top!==void 0&&(u.scrollTop=l.top),l.left!==void 0&&(u.scrollLeft=l.left),Object.keys(u).length&&this.setState(u)}),s.on("print",l=>{const u=OE(l);this.setState({_print:u}),this.setStateAsync({_print:null})}),s.on("undo",()=>{this._historyManager?.handleUndo()}),s.on("redo",()=>{this._historyManager?.handleRedo()}),this.initOnce()}getXlsxWorker(n){if(!this._xlsxWorker){const r=window.URL.createObjectURL(new Blob([`importScripts('${n}');`],{type:"text/javascript"}));this._xlsxWorker=new Promise(s=>{const l=new Worker(r);l.addEventListener("message",u=>{u.data.type==="init"&&s(l)})})}return this._xlsxWorker}initOnce(){const n={sortMarks:{},_filterIds:null,data:[],filterValues:{},scroll:null,scrollLeft:0,scrollTop:0,editor:null,focusCell:null,_print:null,history:{undo:0,redo:0},search:null};this._router.init(n)}init(n){n.hasOwnProperty("_skin")&&!n._skin&&(n._skin=VE()),n.columns&&n.columns.forEach(r=>{r.options&&(r.optionsMap=new Map(r.options.map(s=>[s.id,s.label])))}),Dh(this.getState().data,n.data)||(n.tree?n.data=this.normalizeTreeRows(n.data):n.data=this.normalizeRows(n.data),this.setState({_filterIds:null,filterValues:{},sortMarks:{},search:null}),this._historyManager&&this._historyManager.resetHistory()),n.tree&&(n.undo=!1,n.reorder=!1),n.split?.right&&(n.split.right=0),n.undo&&!this._historyManager&&(this._historyManager=new $E(this.in,this.getState.bind(this),this.setState.bind(this))),this._router.init({...n})}setState(n,r){return this._router.setState(n,r)}setStateAsync(n){this._router.setStateAsync(n)}getRow(n){const{tree:r}=this.getState();return r?this._branches[n]:this.getState().data.find(s=>s.id===n)}getRowIndex(n,r){return r||(r=this.getState().flatData),r.findIndex(s=>s.id===n)}getNextRow(n){const r=this.getState().flatData,s=this.getRowIndex(n,r);return r[s+1]}getPrevRow(n){const r=this.getState().flatData,s=this.getRowIndex(n,r);return r[s-1]}getColumn(n){return this.getState().columns.find(r=>r.id===n)}getNextColumn(n,r){const s=this.getState()._columns,l=s.findIndex(u=>u.id===n);return r?this._getFirstVisibleColumn(l+1):s[l+1]}getPrevColumn(n,r){const s=this.getState()._columns,l=s.findIndex(u=>u.id===n);return r?this._getLastVisibleColumn(l-1):s[l-1]}_getFirstVisibleColumn(n){const r=this.getState()._columns;let s=n??0;for(;s<r.length&&(r[s]?.hidden||r[s]?.collapsed);)s++;return r[s]}_getLastVisibleColumn(n){const r=this.getState()._columns;let s=n??r.length-1;for(;s<r.length&&(r[s]?.hidden||r[s]?.collapsed);)s--;return r[s]}isCellEditable(n,r){const{editor:s,hidden:l}=r;return!s||l?!1:typeof s=="function"?s(n,r):!0}getNextEditor(n,r){let s=this.getState().columns;if(r){const l=s.findIndex(u=>u.id===r.id);s=s.slice(l+1)}return s.find(l=>this.isCellEditable(n,l))}getPrevEditor(n,r){let s=this.getState().columns;if(r){const l=s.findLastIndex(u=>u.id===r.id);s=s.slice(0,l)}return s.findLast(l=>this.isCellEditable(n,l))}toggleBranch(n,r,s){let l=this._branches[n],{data:u}=this.getState();if(u=[...u],n!==0){l={...l,open:r};const f=this.updateTreeRow(l);l.$parent===0&&(u=f)}s&&l.data?.length&&l.data.forEach(f=>{const h=this.toggleKids(f,r,s);n===0&&(u=h)}),this.setState({data:u})}toggleKids(n,r,s){n={...n,open:r};const l=this.updateTreeRow(n);return s&&n.data?.length&&n.data.forEach(u=>{this.toggleKids(u,r,s)}),l}updateTreeRow(n){const r=n.id;this._branches[r]=n;const s=this._branches[n.$parent],l=s.data.findIndex(u=>u.id===r);return s.data=[...s.data],s.data[l]=n,s.data}isSelected(n){return this.getState().selectedRows.indexOf(n)!==-1}findAndRemove(n,r){for(let s=0;s<n.length;s++){if(n[s].id===r)return n.splice(s,1)[0];if(n[s].data){const l=[...n[s].data],u=this.findAndRemove(l,r);if(u)return n[s]={...n[s],data:l},u}}return null}insertItem(n,r,s,l){for(let u=0;u<n.length;u++){if(n[u].id===r){const f=n[u],h=l==="before"?u:u+1;if(f.data){if(l==="before"){const g=u>0?n[u-1]:null;return g?.data&&g.open?n[u-1]={...g,data:[...g.data,s]}:n.splice(h,0,s),!0}else if(f.open)return n[u]={...f,data:[s,...f.data]},!0}return n.splice(h,0,s),!0}if(n[u].data&&(n[u]={...n[u],data:[...n[u].data]},this.insertItem(n[u].data,r,s,l)))return!0}return!1}moveItem(n,r,s,l){const u=[...s],f=this.findAndRemove(u,n);return this.insertItem(u,r,f,l),u}copyColumns(n){const r=[];for(let s=0;s<n.length;s++){const l={...n[s]};this.copyHeaderFooter(l,"header"),this.copyHeaderFooter(l,"footer"),r[s]=l}return r}copyHeaderFooter(n,r){let s=n[r];s=Array.isArray(s)?[...s]:[s],s.forEach((l,u)=>{s[u]=typeof l=="string"?{text:l}:{...l}}),n[r]=s}setCollapsibleColumns(n,r,s){let l=n.header;for(let u=0;u<l.length;u++){const f=l[u];if(f.collapsible&&f.collapsed){if(f.collapsible!=="first"){n.collapsed=!0,n.width=36,f.vertical=!0;const g=l.length-u;l=l.slice(0,u+1),l[u].rowspan=g}const h=f.colspan;if(h){const g=l[u+1];let y=1;g&&g.colspan&&!g.collapsed&&(y=g.colspan);for(let w=y;w<h;w++){const b=s[r+w];b&&(b.hidden=!0)}}}}}normalizeColumns(n,r,s,l,u){const f=n[r];f.width||(f.width=f.flexgrow?17:u.columnWidth),f._colindex=r+1;const h=f[s],g=u[`${s}RowHeights`];for(let y=0;y<l;y++){const w=h[y];w.id=f.id,y===h.length-1&&(w.rowspan=w.rowspan?Math.min(w.rowspan,l-y):l-y);for(let b=1;b<w.rowspan;b++){h.splice(y+b,0,{_hidden:!0});for(let S=1;S<w.colspan;S++)n[r+S][s].splice(y+b,0,{})}if(w.rowspan){const b=(w.rowspan===l?g:g.slice(y,w.rowspan+y)).reduce((S,k)=>S+k,0);w.height=b,y+w.rowspan!=l&&w.height--}if(w.colspan){let b=f.width,S=f.flexgrow||0;const k=w.colspan;for(let A=1;A<k;A++){const T=n[r+A];T&&(T.hidden?w.colspan-=1:T.flexgrow?S+=T.flexgrow:b+=T.width||u.columnWidth),S?w.flexgrow=S:w.width=b}}else w.width=f.width,w.flexgrow=f.flexgrow;s==="header"&&w.filter&&typeof w.filter=="string"&&(w.filter={type:w.filter})}h.length>l&&(h.length=l),f[s]=h}normalizeRows(n){for(let r=0;r<n.length;r++)n[r].id||(n[r].id=Fp());return n}normalizeTreeRows(n,r,s){return!r&&!s&&(this._branches={0:{data:n}}),n.forEach(l=>{l.id||(l.id=Fp()),l.$level=r||0,l.$parent=s||0,this._branches[l.id]=l,l.data&&(l.data.length?(l.$count=l.data.length,this.normalizeTreeRows(l.data,l.$level+1,l.id)):(delete l.data,delete l.$count,delete l.open))}),n}sortTree(n,r){n.sort(r),n.forEach(s=>{s.data&&this.sortTree(s.data,r)})}filterTree(n,r,s){return n.forEach(l=>{r(l)&&s.push(l.id),l.data&&this.filterTree(l.data,r,s)}),s}flattenRows(n,r,s){const l=r;return n.forEach(u=>{(!s||s.includes(u.id))&&l.push(u),u.data?.length&&u.open!==!1&&this.flattenRows(u.data,l,s)}),l}createFilter(n){const{_columns:r}=this.getState(),s=[];for(const l in n){const u=r.find(y=>y.id==l),{config:f,type:h}=u.header.find(y=>y.filter).filter,g=n[l];s.push(y=>{const w=pc(y,u);return f?.handler?f.handler(w,g):eC(h)(w,g)})}return l=>{for(let u=0;u<s.length;u++)if(!s[u](l))return!1;return!0}}searchRows(n,r){n=n.trim().toLowerCase();const s={};if(!n)return s;const{flatData:l,columns:u}=this.getState(),f=r?u.filter(h=>r[h.id]):u;return l.forEach(h=>{const g={};f.forEach(y=>{const w=cc(h,y);String(w).toLowerCase().includes(n)&&(g[y.id]=!0)}),Object.keys(g).length&&(s[h.id]=g)}),s}normalizeSizes(n,r,s,l,u){const f=dx(n,"header",s,r.headerHeight,u),h=dx(n,"footer",l,r.footerHeight,u),g=f.reduce((w,b)=>w+b,0),y=h.reduce((w,b)=>w+b,0);return{...r,headerRowHeights:f,footerRowHeights:h,headerHeight:g,footerHeight:y}}},ej=new Date().valueOf();function Fp(){return"temp://"+ej++}function tj(t,n="data-id"){let r=t;for(!r.tagName&&t.target&&(r=t.target);r;){if(r.getAttribute&&r.getAttribute(n))return r;r=r.parentNode}return null}new Date().valueOf();var nj=class{constructor(){this.store=new Map}configure(t,n){this.node=n;for(const r in t)if(t[r]){const s=r.toLowerCase().replace(/[ ]/g,""),l=t[r];this.store.set(s,l)}}},Od=[],aj={subscribe:t=>{rj();const n=new nj;return Od.push(n),t(n),()=>{const r=Od.findIndex(s=>s===n);r>=0&&Od.splice(r,1)}}},fx=!1;function rj(){fx||(fx=!0,document.addEventListener("keydown",t=>{if(Od.length&&(t.ctrlKey||t.altKey||t.metaKey||t.shiftKey||t.key.length>1||t.key===" ")){const n=[];t.ctrlKey&&n.push("ctrl"),t.altKey&&n.push("alt"),t.metaKey&&n.push("meta"),t.shiftKey&&n.push("shift");let r=t.code.replace("Key","").toLocaleLowerCase();t.key===" "&&(r="space"),n.push(r);const s=n.join("+");for(let l=Od.length-1;l>=0;l--){const u=Od[l],f=u.store.get(s)||u.store.get(r);f&&u.node.contains(t.target)&&f(t,{key:s,evKey:r})}}}))}const sj={tab:!0,"shift+tab":!0,arrowup:!0,arrowdown:!0,arrowright:!0,arrowleft:!0,enter:!0,escape:!0,f2:!0,home:!0,end:!0,"ctrl+home":!0,"ctrl+end":!0,"ctrl+z":!0,"ctrl+y":!0};function ij(t,{keys:n,exec:r}){if(!n)return;function s(f){const h=f.target;return h.tagName==="INPUT"||h.tagName==="TEXTAREA"||tj(h,"data-header-id")?.classList.contains("wx-filter")||!!h.closest(".wx-cell.wx-editor")}const l={};for(const f in n){const h=n[f];typeof h<"u"&&(typeof h=="function"?l[f]=h:h&&(l[f]=g=>{const y=s(g);r({key:f,event:g,isInput:y})}))}const u=aj.subscribe(f=>{f.configure(l,t)});return{destroy:()=>{u()}}}function oj(t,n){let r=null;n.scroll.subscribe(s=>{if(!s||s===r)return;r=s;const{left:l,top:u,height:f,width:h}=s,g=n.getHeight(),y=n.getWidth(),w=n.getScrollMargin();if(u>=0){const b=t.scrollTop;u<b?t.scrollTop=u:u+f>b+g&&(t.scrollTop=u-g+f)}if(l>=0){const b=t.scrollLeft;l<b?t.scrollLeft=l:l+h>b+y-w&&(t.scrollLeft=l-y+h+w)}}),n.scrollLeft?.subscribe?.(s=>{requestAnimationFrame(()=>{Math.abs(t.scrollLeft-s)>1&&(t.scrollLeft=s)})}),n.scrollTop?.subscribe?.(s=>{requestAnimationFrame(()=>{Math.abs(t.scrollTop-s)>1&&(t.scrollTop=s)})})}const Ps=d.createContext(null);function lj(t,n){const r=new ResizeObserver(s=>{requestAnimationFrame(()=>n(s[0].contentRect))});return r.observe(t.parentNode),{destroy(){r.disconnect()}}}const mx=5,cj=700;function eh(t){const n=t.getBoundingClientRect(),r=document.body,s=n.top+r.scrollTop-r.clientTop||0,l=n.left+r.scrollLeft-r.clientLeft||0;return{y:Math.round(s),x:Math.round(l),width:t.offsetWidth,height:t.offsetHeight}}function Ov(t,n){const r=eh(n);return{x:t.clientX-r.x,y:t.clientY-r.y}}function uj(t,n){const r=n.current;let s=null,l,u,f=!1,h=!1;const g=document.createElement("DIV");g.className="wx-drag-zone",g.setAttribute("tabindex",-1);function y(){clearTimeout(l),l=null}function w(D){const K=Hd(D);K&&(s={container:g,sourceNode:D.target,from:Rh(K),pos:Ov(D,t)},u=s.pos,b(D))}function b(D){if(!s)return;const K=s.pos=Ov(D,t);if(!f){if(!h&&!D?.target?.getAttribute("draggable-data")&&Math.abs(u.x-K.x)<mx&&Math.abs(u.y-K.y)<mx)return;if(F(D)===!1)return $()}if(h){const z=window.scrollX||document.documentElement.scrollLeft||document.body.scrollLeft,q=window.scrollY||document.documentElement.scrollTop||document.body.scrollTop;s.targetNode=document.elementFromPoint(D.pageX-z,D.pageY-q)}else s.targetNode=D.target;r.move&&r.move(D,s),g.style.left=-(s.offset?s.offset.x:0)+"px",g.style.top=s.pos.y+(s.offset?s.offset.y:0)+"px"}function S(D){g.parentNode&&g.parentNode.removeChild(g),g.innerHTML="",f&&r.end&&r.end(D,s),s=u=null,$()}function k(D){r.getReorder&&!r.getReorder()||D.button===0&&(H(D),window.addEventListener("mousemove",A),window.addEventListener("mouseup",T),w(D))}function A(D){b(D)}function T(D){S(D)}function j(D){if(r.getReorder&&!r.getReorder())return;l=setTimeout(()=>{h=!0,w(D.touches[0])},cj),H(D);function K(){l&&y(),D.target.removeEventListener("touchmove",I),D.target.removeEventListener("touchend",K),S(D)}D.target.addEventListener("touchmove",I),D.target.addEventListener("touchend",K),t.addEventListener("contextmenu",N)}function I(D){f?(D.preventDefault(),b(D.touches[0])):l&&y()}function N(D){if(f||l)return D.preventDefault(),!1}function P(D){D.preventDefault()}function H(D){if(!r.getDraggableInfo)return;const{hasDraggable:K}=r.getDraggableInfo();(!K||D.target.getAttribute("draggable-data"))&&(document.body.style.userSelect="none",document.body.style.webkitUserSelect="none")}function F(D){if(f=!0,r.start){if(r.start(D,s)===!1)return!1;t.appendChild(g),document.body.style.cursor="move"}}function $(D){f=h=!1,document.body.style.cursor="",document.body.style.userSelect="",document.body.style.webkitUserSelect="",window.removeEventListener("mousemove",A),window.removeEventListener("mouseup",T),D&&(t.removeEventListener("mousedown",k),t.removeEventListener("touchstart",j),t.removeEventListener("dragstart",P))}return t.addEventListener("mousedown",k),t.addEventListener("touchstart",j),t.addEventListener("dragstart",P),{destroy(){$(!0)}}}const dj=.004;function fj(){return{dirX:0,dirY:0,scrollSpeedFactor:1}}function mj(t,n,r,s){const{node:l,left:u,top:f,bottom:h,sense:g,xScroll:y,yScroll:w}=s,b=Ov(t,l);r.scrollState||(r.scrollState=fj());let S=0,k=0;b.x<u+g?S=-1:b.x>n.width-g&&(S=1),b.y<f+Math.round(g/2)?k=-1:b.y>n.height-h-Math.round(g/2)&&(k=1),(r.scrollState.dirX!==S||r.scrollState.dirY!==k)&&(tC(r),r.scrollState.dirX=S,r.scrollState.dirY=k),(y&&r.scrollState.dirX!==0||w&&r.scrollState.dirY!==0)&&pj(r,s,{x:r.scrollState.dirX,y:r.scrollState.dirY})}function pj(t,n,r){t.autoScrollTimer||(t.autoScrollTimer=setTimeout(()=>{t.activeAutoScroll=setInterval(hj,15,t,n,r)},250))}function tC(t){t.scrollSpeedFactor=1,t.autoScrollTimer&&(t.autoScrollTimer=clearTimeout(t.autoScrollTimer),t.activeAutoScroll=clearInterval(t.activeAutoScroll))}function hj(t,n,r){const{x:s,y:l}=r;t.scrollSpeedFactor+=dj,s!==0&&vj(t,n,s),l!==0&&gj(t,n,l)}function gj(t,n,r){const s=n.node.scrollTop;nC(s+Math.round(n.sense/3)*t.scrollSpeedFactor*r,"scrollTop",n)}function vj(t,n,r){const s=n.node.scrollLeft;nC(s+Math.round(n.sense/3)*t.scrollSpeedFactor*r,"scrollLeft",n)}function nC(t,n,r){r.node[n]=t}function Ih(t,n,r,s,l,u){const f={};return t&&(f.width=`${t}px`,f.minWidth=`${t}px`),n&&(f.flexGrow=n),u&&(f.height=`${u}px`),r&&(f.position="sticky",r.left&&(f.left=`${s}px`),r.right&&(f.right=`${l}px`)),f}function aC(t,n,r){let s="";if(t.fixed)for(const l in t.fixed){let u=t.fixed[l]===-1;!u&&t.fixed.leftSize&&n.colspan&&(u=n.colspan+t._colindex-1===t.fixed.leftSize),s+=u?"wx-shadow ":"wx-fixed "}return s+=n.rowspan>1?"wx-rowspan ":"",s+=n.colspan>1?"wx-colspan ":"",s+=n.vertical?"wx-vertical ":"",s+=r?r(t)+" ":"",s}function yj(t){const{row:n,column:r,cellStyle:s=null,columnStyle:l=null,children:u,focusable:f}=t,h=d.useContext(Ps),g=Bt(h,"focusCell"),y=Bt(h,"search"),w=Bt(h,"reorder"),b=d.useMemo(()=>y?.rows[n.id]&&y.rows[n.id][r.id],[y,n.id,r.id]),S=d.useMemo(()=>Ih(r.width,r.flexgrow,r.fixed,r.left,r.right),[r.width,r.flexgrow,r.fixed,r.left,r.right]);function k(F,$){let D="wx-cell";return D+=r.fixed?" "+(r.fixed===-1?"wx-shadow":"wx-fixed"):"",D+=F?" "+F(r):"",D+=$?" "+$(n,r):"",D+=r.treetoggle?" wx-tree-cell":"",D}const A=d.useMemo(()=>k(l,s),[l,s,r,n]),T=d.useMemo(()=>typeof r.draggable=="function"?r.draggable(n,r)!==!1:r.draggable,[r,n]),j=d.useRef(null);d.useEffect(()=>{j.current&&f&&g?.row===n.id&&g?.column===r.id&&j.current.focus()},[g,f,n.id,r.id]);const I=d.useCallback(()=>{f&&!g&&h.exec("focus-cell",{row:n.id,column:r.id,eventSource:"focus"})},[h,f,g,n.id,r.id]);function N(F){const $=new RegExp(`(${y.value.trim()})`,"gi");return String(F).split($).map(D=>({text:D,highlight:$.test(D)}))}const P=d.useMemo(()=>{const F=r.fixed&&r.fixed.left===-1||r.fixed.right===-1,$=r.fixed&&r.fixed.right;return[A,F?"wx-shadow":"",$?"wx-fixed-right":""].filter(Boolean).join(" ")},[A,r]),H=r.cell;return o.jsxs("div",{className:"wx-TSCaXsGV "+P,ref:j,onFocus:I,style:S,"data-row-id":ar(n.id),"data-col-id":ar(r.id),tabIndex:f?"0":"-1",role:"gridcell","aria-colindex":r._colindex,"aria-readonly":r.editor?void 0:!0,children:[w&&r.draggable?T?o.jsx("i",{"draggable-data":"true",className:"wx-TSCaXsGV wx-draggable wxi-drag"}):o.jsx("i",{className:"wx-TSCaXsGV wx-draggable-stub"}):null,r.treetoggle?o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{marginLeft:`${n.$level*28}px`}}),n.$count?o.jsx("i",{"data-action":"toggle-row",className:`wx-TSCaXsGV wx-table-tree-toggle wxi-menu-${n.open!==!1?"down":"right"}`}):null]}):null,H?o.jsx(H,{api:h,row:n,column:r,onAction:({action:F,data:$})=>h.exec(F,$)}):u?u():b?o.jsx("span",{children:N(cc(n,r)).map(({highlight:F,text:$},D)=>F?o.jsx("mark",{className:"wx-TSCaXsGV wx-search",children:$},D):o.jsx("span",{children:$},D))}):cc(n,r)]})}function px(t,n){let r,s;function l(h){r=h.clientX,t.style.opacity=1,document.body.style.cursor="ew-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",u),window.addEventListener("mouseup",f),n&&n.down&&n.down(t)}function u(h){s=h.clientX-r,n&&n.move&&n.move(s)}function f(){t.style.opacity="",document.body.style.cursor="",document.body.style.userSelect="",n&&n.up&&n.up(s),window.removeEventListener("mousemove",u),window.removeEventListener("mouseup",f)}return t.addEventListener("mousedown",l),{destroy(){t.removeEventListener("mousedown",l)}}}function bj({filter:t,column:n,action:r,filterValue:s}){function l({value:u}){r({value:u,key:n.id})}return o.jsx(cy,{...t.config??{},value:s,onChange:l})}function wj({filter:t,column:n,action:r,filterValue:s}){const l=d.useContext(Ps),u=Bt(l,"flatData"),f=d.useMemo(()=>t?.config?.options||n?.options||g(),[t,n,u]),h=d.useMemo(()=>t?.config?.template,[t]);function g(){const b=[];return u.forEach(S=>{const k=pc(S,n);b.includes(k)||b.push(k)}),b.map(S=>({id:S,label:S}))}function y({value:b}){r({value:b,key:n.id})}function w(b){b.key!=="Tab"&&b.preventDefault()}return o.jsx("div",{style:{width:"100%"},onKeyDown:w,children:o.jsx(LR,{placeholder:"",clear:!0,...t?.config??{},options:f,value:s,onChange:y,children:b=>h?h(b):b.label})})}function xj({filter:t,column:n,action:r,filterValue:s}){function l({value:u}){r({value:u,key:n.id})}return o.jsx("div",{className:"wx-aaaK5VYO",style:{width:"100%"},children:o.jsx(IR,{placeholder:"",clear:!0,...t?.config??{},value:s,onChange:l})})}function rC(t){const{value:n,options:r=[],placeholder:s="",clear:l=!1,text:u=null,template:f=null,cell:h=null,dropdown:g={},autoOpen:y=!1,onChange:w,onAction:b}=t,[S,k]=$S(n||[]),A=d.useMemo(()=>(S||[]).map(q=>r.find(W=>W.id===q)).filter(Boolean),[S,r]),T=d.useRef(null),j=d.useRef(null),[I,N]=d.useState(null),P=()=>{const q=S||[];if(!q.length)return 0;const W=r.find(Y=>q.includes(Y.id));return W?r.indexOf(W):0};function H(q){j.current=q.navigate,N(()=>q.keydown),y&&q.navigate(P())}d.useEffect(()=>{y&&(T.current?.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges())},[]);function F({id:q}){k(q),w&&w({value:q})}function $(q){q.stopPropagation(),k([]),w&&w({value:[]})}function D(){j.current?.(P())}function K(){j.current?.(null)}function z(q){I?.(q,P())}return o.jsxs("div",{ref:T,className:"wx-multiselect wx-aadNNOwy",onClick:D,onKeyDown:z,tabIndex:0,children:[o.jsx("div",{className:"wx-label wx-aadNNOwy",children:f?f(A):h?o.jsx(h,{data:A,onAction:b}):u?o.jsx("span",{className:"wx-text wx-aadNNOwy",children:u}):A.length?o.jsx("span",{className:"wx-text wx-aadNNOwy",children:A.map(q=>q.label).join(", ")}):s?o.jsx("span",{className:"wx-placeholder wx-aadNNOwy",children:s}):" "}),l&&S?.length?o.jsx("i",{className:"wx-icon wxi-close wx-aadNNOwy",onClick:$}):o.jsx("i",{className:"wx-icon wxi-angle-down wx-aadNNOwy"}),o.jsx(jh,{items:r,onReady:H,onSelect:F,multiselect:!0,checkboxes:!0,value:S||[],onCancel:K,...g,children:({option:q})=>o.jsx("div",{className:"wx-option wx-aadNNOwy",children:f?f(q):h?o.jsx(h,{data:q,onAction:b}):q.label})})]})}function Sj({filter:t,column:n,action:r,filterValue:s}){const l=d.useContext(sr.i18n)?.getGroup("grid")||Sm(fy).getGroup("grid"),u=d.useMemo(()=>({clear:!0,...t?.config||{}}),[t]),f=d.useMemo(()=>u.options||n.options,[u,n]),h=d.useMemo(()=>{const w=s?.length;return w?w<3?s.map(b=>n.optionsMap.get(b)).join(", "):w+" "+l("selected"):""},[s,n,l]);function g({value:w}){r({value:w,key:n.id})}function y(w){w.key!=="Tab"&&w.preventDefault()}return o.jsx("div",{style:{width:"100%"},onKeyDown:y,children:o.jsx(rC,{placeholder:"",...u,options:f,value:s||[],text:h,onChange:g})})}const Cj={text:bj,richselect:wj,datepicker:xj,multiselect:Sj};function kj({filter:t,column:n}){const r=d.useContext(Ps),s=Bt(r,"filterValues");function l(f){r.exec("filter-rows",f)}const u=d.useMemo(()=>Cj[t.type],[t.type]);return o.jsx(u,{filter:t,column:n,action:l,filterValue:s[n.id]})}function Mj(t){const{cell:n,column:r,row:s,lastRow:l,sortRow:u,columnStyle:f,bodyHeight:h,hasSplit:g}=t,y=d.useContext(Ps),w=Bt(y,"sortMarks"),b=d.useMemo(()=>w?w[r.id]:void 0,[w,r.id]),S=d.useRef(),k=d.useCallback(he=>{S.current=n.flexgrow?he.parentNode.clientWidth:n.width},[n.flexgrow,n.width]),A=d.useCallback((he,ee)=>{y.exec("resize-column",{id:n.id,width:Math.max(1,(S.current||0)+he),inProgress:ee})},[y,n.id]),T=d.useCallback(he=>A(he,!0),[A]),j=d.useCallback(he=>A(he,!1),[A]),I=d.useCallback(he=>{if(!r.sort||n.filter)return;let ee=b?.order;ee&&(ee=ee==="asc"?"desc":"asc"),y.exec("sort-rows",{key:n.id,add:he.ctrlKey||he.metaKey,order:ee})},[y,n.id,n.filter,r.sort,b?.order]),N=d.useCallback(he=>{he&&he.stopPropagation(),y.exec("collapse-column",{id:n.id,row:s})},[y,n.id,s]),P=d.useCallback(he=>{he.key==="Enter"&&N()},[N]),H=d.useCallback(he=>{he.key==="Enter"&&!n.filter&&I(he)},[I,n.filter]),F=d.useMemo(()=>n.collapsed&&r.collapsed,[n.collapsed,r.collapsed]),$=d.useMemo(()=>F&&!g&&n.collapsible!=="header",[F,g,n.collapsible]),D=d.useMemo(()=>$?{top:-h/2,position:"absolute"}:{},[$,h]),K=d.useMemo(()=>Ih(n.width,n.flexgrow,r.fixed,r.left,n.right??r.right,n.height+(F&&$?h:0)),[n.width,n.flexgrow,r.fixed,r.left,n.right,r.right,n.height,F,$,h]),z=d.useMemo(()=>aC(r,n,f),[r,n,f]),q=d.useCallback(()=>Object.fromEntries(Object.entries(n).filter(([he])=>he!=="cell")),[n]),W=`wx-cell ${z} ${n.css||""} wx-collapsed`,Y=["wx-cell",z,n.css||"",n.filter?"wx-filter":"",r.fixed&&r.fixed.right?"wx-fixed-right":""].filter(Boolean).join(" "),V=d.useRef(null);return d.useEffect(()=>{const he=V.current;if(!he)return;const ee=px(he,{down:k,move:T,up:j});return()=>{typeof ee=="function"&&ee()}},[k,T,j,px]),F?o.jsx("div",{className:"wx-RsQD74qC "+W,style:K,role:"button","aria-label":`Expand column ${n.text||""}`,"aria-expanded":!n.collapsed,tabIndex:0,onKeyDown:P,onClick:N,"data-header-id":ar(r.id),children:o.jsx("div",{className:"wx-RsQD74qC wx-text",style:D,children:n.text||""})}):o.jsxs("div",{className:"wx-RsQD74qC "+Y,style:K,onClick:I,"data-header-id":ar(r.id),tabIndex:!n._hidden&&r.sort&&!n.filter?0:void 0,role:"columnheader","aria-colindex":r._colindex,"aria-colspan":n.colspan>1?n.colspan:void 0,"aria-rowspan":n.rowspan>1?n.rowspan:void 0,"aria-sort":!b?.order||n.filter?"none":b?.order==="asc"?"ascending":"descending",onKeyDown:H,children:[n.collapsible?o.jsx("div",{className:"wx-RsQD74qC wx-collapse",role:"button","aria-label":n.collapsed?"Expand column":"Collapse column","aria-expanded":!n.collapsed,tabIndex:0,onKeyDown:P,onClick:N,children:o.jsx("i",{className:`wx-RsQD74qC wxi-angle-${n.collapsed?"down":"right"}`})}):null,n.cell?(()=>{const he=n.cell;return o.jsx(he,{api:y,cell:q(),column:r,row:s,onAction:({action:ee,data:U})=>y.exec(ee,U)})})():n.filter?o.jsx(kj,{filter:n.filter,column:r}):o.jsx("div",{className:"wx-RsQD74qC wx-text",children:n.text||""}),r.resize&&l&&!n._hidden?o.jsx("div",{className:"wx-RsQD74qC wx-grip",role:"presentation","aria-label":"Resize column",ref:V,onClick:he=>he.stopPropagation(),children:o.jsx("div",{})}):null,u?o.jsx("div",{className:"wx-RsQD74qC wx-sort",children:b?o.jsxs(o.Fragment,{children:[typeof b.index<"u"?o.jsx("div",{className:"wx-RsQD74qC wx-order",children:b.index+1}):null,o.jsx("i",{className:`wx-RsQD74qC wxi-arrow-${b.order==="asc"?"up":"down"}`})]}):null}):null]})}function Aj({cell:t,column:n,row:r,columnStyle:s}){const l=d.useContext(Ps),u=d.useMemo(()=>Ih(t?.width,t?.flexgrow,n?.fixed,n?.left,t?.right??n?.right,t?.height),[t?.width,t?.flexgrow,n?.fixed,n?.left,t?.right,n?.right,t?.height]),f=d.useMemo(()=>aC(n,t,s),[n,t,s]),h=d.useCallback(()=>Object.fromEntries(Object.entries(t||{}).filter(([y])=>y!=="cell")),[t]),g=`wx-6Sdi3Dfd wx-cell ${f||""} ${t?.css||""}`+(n?.fixed&&n?.fixed.right?" wx-fixed-right":"");return o.jsx("div",{className:g,style:u,children:!n?.collapsed&&!t?.collapsed?t?.cell?$v.createElement(t.cell,{api:l,cell:h(),column:n,row:r,onAction:({action:y,data:w})=>l.exec(y,w)}):o.jsx("div",{className:"wx-6Sdi3Dfd wx-text",children:t?.text||""}):null})}function hx({deltaLeft:t,contentWidth:n,columns:r,type:s="header",columnStyle:l,bodyHeight:u}){const f=d.useContext(Ps),h=Bt(f,"_sizes"),g=Bt(f,"split"),y=d.useMemo(()=>h?.[`${s}RowHeights`],[h,s]),w=d.useMemo(()=>{let T=[];if(r&&r.length){const j=r[0][s].length;for(let I=0;I<j;I++){let N=0;T.push([]),r.forEach((P,H)=>{const F={...P[s][I]};N||T[I].push(F),F.colspan>1?N=F.colspan-1:N&&N--})}}return T},[r,s]),b=d.useMemo(()=>g?.left||g?.right,[g]);function S(T){return r.find(j=>j.id===T)}function k(T,j){let I=j;return T.rowspan&&(I+=T.rowspan-1),I===w.length-1}function A(T,j,I){if(!I.sort)return!1;for(let N=w.length-1;N>=0;N--){const P=I.header[N];if(!P.filter&&!P._hidden)return j===N}return k(T,j)}return o.jsx("div",{className:`wx-sAsPVaUK wx-${s}`,style:{paddingLeft:`${t}px`,width:`${n}px`},role:"rowgroup",children:w.map((T,j)=>o.jsx("div",{className:s==="header"?"wx-sAsPVaUK wx-h-row":"wx-sAsPVaUK wx-f-row",style:{height:`${y?.[j]}px`,display:"flex"},role:"row",children:T.map(I=>{const N=S(I.id);return s==="header"?o.jsx(Mj,{cell:I,columnStyle:l,column:N,row:j,lastRow:k(I,j),bodyHeight:u,sortRow:A(I,j,N),hasSplit:b},I.id):o.jsx(Aj,{cell:I,columnStyle:l,column:S(I.id),row:j},I.id)})},j))})}function Tj({overlay:t}){const n=d.useContext(Ps);function r(l){return typeof l=="function"}const s=t;return o.jsx("div",{className:"wx-1ty666CQ wx-overlay",children:r(t)?o.jsx(s,{onAction:({action:l,data:u})=>n.exec(l,u)}):t})}function Nj(t){const{editor:n,onSave:r,onApply:s}=t,[l,u]=d.useState(n?.value||""),{type:f="text"}=d.useMemo(()=>n?.config||{},[n]),h=d.useRef(null);d.useEffect(()=>{h.current&&h.current.focus()},[]),d.useEffect(()=>{if(!h.current)return;const w=ho(h.current,()=>r(!0));return()=>w.destroy()},[r]);function g(){h.current&&(u(h.current.value),s(h.current.value))}function y({key:w}){w==="Enter"&&r()}return o.jsx("input",{className:"wx-e7Ao5ejY wx-text",onInput:g,onKeyDown:y,ref:h,type:f,value:l})}function Rj({editor:t,onAction:n,onSave:r,onApply:s,onCancel:l}){const[u,f]=d.useState(t?.value),[h,g]=d.useState(t?.renderedValue),[y,w]=d.useState(t?.options||[]),b=d.useMemo(()=>t?.config?.template,[t]),S=d.useMemo(()=>t?.config?.cell,[t]),k=d.useMemo(()=>t?.config?.dropdown||{},[t]),A=d.useMemo(()=>({trackScroll:!0,...k}),[k]),T=d.useMemo(()=>(y||[]).findIndex(D=>D.id===u),[y,u]),j=d.useRef(null),I=d.useRef(null),N=d.useCallback(D=>{j.current=D.navigate,I.current=D.keydown,j.current(T)},[T,j]),P=d.useCallback(D=>{const K=D?.target?.value??"";g(K);const z=K?(t?.options||[]).filter(q=>(q.label||"").toLowerCase().includes(K.toLowerCase())):t?.options||[];w(z),z.length?j.current(-1/0):j.current(null)},[t]),H=d.useRef(null);d.useEffect(()=>{H.current&&H.current.focus()},[]);const F=d.useRef(r);d.useEffect(()=>{F.current=r},[r]),d.useEffect(()=>{if(!H.current)return;const D=ho(H.current,()=>F.current(!0));return()=>D.destroy()},[]),d.useEffect(()=>{f(t?.value),g(t?.renderedValue),w(t?.options||[])},[t]);const $=d.useCallback(({id:D})=>{s(D),r()},[s,r]);return o.jsxs(o.Fragment,{children:[o.jsx("input",{className:"wx-0UYfSd1x wx-input",ref:H,value:h??"",onChange:P,onKeyDown:D=>I.current?I.current(D,T):void 0}),o.jsx(jh,{items:y,onReady:N,onSelect:$,...A,onCancel:l,children:({option:D})=>b?b(D):S?o.jsx(S,{data:D,onAction:n}):D.label})]})}function Ej({editor:t,onAction:n,onSave:r,onApply:s,onCancel:l}){const[u]=d.useState(()=>t.value||new Date),{template:f,cell:h,dropdown:g={}}=t?.config||{},y=d.useMemo(()=>({trackScroll:!0,width:"auto",...g}),[g]);function w({value:A}){s(A),r()}const b=d.useRef(null),[S,k]=d.useState(null);return d.useEffect(()=>{b.current&&b.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),d.useEffect(()=>{if(!S)return;const A=ho(S,()=>r(!0));return()=>A.destroy()},[S,r]),o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"wx-lNWNYUb6 wx-value",ref:b,tabIndex:0,onClick:l,onKeyDown:A=>A.preventDefault(),children:f?f(u):h?o.jsx(h,{data:t.value,onAction:n}):o.jsx("span",{className:"wx-lNWNYUb6 wx-text",children:t.renderedValue})}),o.jsx(ly,{...y,onCancel:l,children:o.jsx("div",{ref:k,className:"wx-lNWNYUb6",children:o.jsx(OS,{value:u,onChange:w,buttons:t.config?.buttons})})})]})}function jj(t){const{editor:n}=t,r=t.onAction??t.onaction,s=t.onSave??t.onsave,l=t.onApply??t.onapply,u=t.onCancel??t.oncancel,f=n.config||{},{dropdown:h={}}=f,g=d.useMemo(()=>({trackScroll:!0,...h}),[h]),[y]=d.useState(n.options.find(P=>P.id===n.value)),[w]=d.useState(n.value),[b]=d.useState(n.options),S=d.useMemo(()=>b.findIndex(P=>P.id===w),[b,w]);function k({id:P}){l(P),s()}let A;const[T,j]=d.useState();function I(P){A=P.navigate,j(()=>P.keydown),A(S)}const N=d.useRef(null);return d.useEffect(()=>{N.current&&N.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),d.useEffect(()=>{if(!N.current)return;const P=ho(N.current,()=>s(!0));return()=>P.destroy()},[s]),o.jsxs(o.Fragment,{children:[o.jsx("div",{ref:N,className:"wx-ywGRk611 wx-value",tabIndex:0,onClick:u,onKeyDown:P=>{T(P,S),P.preventDefault()},children:f.template?f.template(y):f.cell?(()=>{const P=f.cell;return o.jsx(P,{data:y,onAction:r})})():o.jsx("span",{className:"wx-ywGRk611 wx-text",children:n.renderedValue})}),o.jsx(jh,{items:b,onReady:I,onSelect:k,...g,onCancel:u,children:({option:P})=>f.template?f.template(P):f.cell?(()=>{const H=f.cell;return o.jsx(H,{data:P,onAction:r})})():P.label})]})}function Dj(t){const{editor:n,onAction:r,onSave:s,onApply:l}=t,u=n?.config||{},f=n?.options??[],h=n?.value||[],g=n?.renderedValue,y=d.useMemo(()=>({trackScroll:!0,...u.dropdown||{}}),[u]);function w({value:S}){l(S)}const b=d.useRef(null);return d.useEffect(()=>{if(!b.current)return;const S=ho(b.current,()=>s(!0));return()=>S.destroy()},[s]),o.jsx("div",{ref:b,className:"wx-value wx-aacZ4gNU",onClick:()=>s(!0),children:o.jsx(rC,{value:h,options:f,text:g,template:u.template,cell:u.cell,clear:u.clear,dropdown:y,autoOpen:!0,onChange:w,onAction:r})})}const Ij={text:Nj,combo:Rj,datepicker:Ej,richselect:jj,multiselect:Dj};function Lj({column:t,row:n}){const r=d.useContext(Ps),s=Bt(r,"editor"),l=d.useCallback((A,T)=>{r.exec("close-editor",{ignore:A}),T&&r.exec("focus-cell",{...T,eventSource:"click"})},[r]),u=d.useCallback(A=>{const T=A?null:{row:s?.id,column:s?.column};l(!1,T)},[s,l]),f=d.useCallback(()=>{l(!0,{row:s?.id,column:s?.column})},[s,l]),h=d.useCallback(A=>{r.exec("editor",{value:A})},[r]),g=d.useCallback(A=>{A.key==="Enter"&&s&&(t.editor.type==="multiselect"?h(s.value):f())},[s,t.editor,f,h]),y=d.useMemo(()=>Ih(t.width,t.flexgrow,t.fixed,t.left,t.right),[t.width,t.flexgrow,t.fixed,t.left,t.right]),w=d.useMemo(()=>{let A=t.editor;if(typeof A=="function"&&(A=A(n,t)),!A)return null;let T=typeof A=="string"?A:A.type;return Ij[T]},[t,n]),b=d.useRef(null);d.useEffect(()=>{b.current&&typeof y=="string"&&b.current.setAttribute("style",y)},[y]);const S=typeof n.$parent<"u"?"gridcell":"cell",k=typeof n.$parent<"u"?!t.editor:void 0;return o.jsx("div",{className:"wx-8l724t2g wx-cell wx-editor",ref:b,style:typeof y=="object"&&y!==null?y:void 0,role:S,"aria-readonly":k,tabIndex:-1,onClick:A=>A.stopPropagation(),onDoubleClick:A=>A.stopPropagation(),onKeyDown:g,children:w?o.jsx(w,{editor:s,onSave:u,onApply:h,onCancel:f,onAction:({action:A,data:T})=>r.exec(A,T)}):null})}function gx(t){const{columns:n,type:r,columnStyle:s}=t,l=d.useContext(Ps),{filterValues:u,_columns:f,_sizes:h}=l.getState();function g(y){return s?" "+s(y):""}return o.jsx(o.Fragment,{children:n.map((y,w)=>o.jsx("tr",{children:y.map(b=>{const S=f.find(T=>T.id===b.id),k=`wx-print-cell-${r}${g(S)}${b.filter?" wx-print-cell-filter":""}${b.vertical?" wx-vertical":""}`,A=b.cell;return o.jsx("th",{style:US(ZS(b,h.columnWidth)),className:"wx-Gy81xq2u "+k,rowSpan:b.rowspan,colSpan:b.colspan,children:A?o.jsx(A,{api:l,cell:Object.fromEntries(Object.entries(b).filter(([T])=>T!=="cell")),column:S,row:w}):b.filter?o.jsx("div",{className:"wx-Gy81xq2u wx-print-filter",children:FE(u,f,b)}):o.jsx("div",{className:"wx-Gy81xq2u wx-text",children:b.text??""})},b.id)})},w))})}function Pj(t){const{columns:n,rowStyle:r,columnStyle:s,cellStyle:l,header:u,footer:f,reorder:h}=t,g=d.useContext(Ps),{flatData:y,_sizes:w}=g.getState(),b=u&&cx(n,"header",w.headerRowHeights),S=f&&cx(n,"footer",w.footerRowHeights);function k(T,j){let I="";return I+=s?" "+s(j):"",I+=l?" "+l(T,j):"",I}function A(T,j){return typeof j.draggable=="function"?j.draggable(T,j)!==!1:j.draggable}return o.jsxs("table",{className:`wx-8NTMLH0z wx-print-grid ${n.some(T=>T.flexgrow)?"wx-flex-columns":""}`,children:[u?o.jsx("thead",{children:o.jsx(gx,{columns:b,type:"header",columnStyle:s})}):null,o.jsx("tbody",{children:y.map((T,j)=>o.jsx("tr",{className:"wx-8NTMLH0z wx-row"+(r?" "+r(T):""),style:{height:`${T.rowHeight||w.rowHeight}px`},children:n.map(I=>I.collapsed?null:o.jsxs("td",{className:`wx-8NTMLH0z wx-print-cell wx-cell ${k(T,I)}`,style:US(ZS(I,w.columnWidth)),children:[h&&I.draggable?o.jsx("span",{className:"wx-8NTMLH0z wx-print-draggable",children:A(T,I)?o.jsx("i",{className:"wx-8NTMLH0z wxi-drag"}):null}):null,I.treetoggle?o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{marginLeft:T.$level*28+"px"}}),T.$count?o.jsx("i",{className:`wx-8NTMLH0z wx-print-grid-tree-toggle wxi-menu-${T.open!==!1?"down":"right"}`}):null]}):null,I.cell?(()=>{const N=I.cell;return o.jsx(N,{api:g,row:T,column:I})})():o.jsx("span",{children:cc(T,I)})]},I.id))},j))}),f?o.jsx("tfoot",{children:o.jsx(gx,{columns:S,type:"footer",columnStyle:s})}):null]})}function _j(t){const{config:n,...r}=t,s=d.useContext(Ps),{_skin:l,_columns:u}=s.getState(),f=d.useMemo(()=>LE(u,n),[]),h=d.useRef(null);return d.useEffect(()=>{const g=document.body;g.classList.add("wx-print");const y=h.current;if(!y)return;const w=y.cloneNode(!0);g.appendChild(w);const b=`@media print { @page { size: ${n.paper} ${n.mode}; }`,S=document.createElement("style");S.setAttribute("type","text/css"),S.setAttribute("media","print"),document.getElementsByTagName("head")[0].appendChild(S),S.appendChild(document.createTextNode(b)),window.print(),S.remove(),g.classList.remove("wx-print"),w.remove()},[]),o.jsx("div",{className:`wx-4zwCKA7C wx-${l}-theme wx-print-container`,ref:h,children:f.map((g,y)=>o.jsx("div",{className:"wx-4zwCKA7C wx-print-grid-wrapper",children:o.jsx(Pj,{columns:g,...r})},y))})}function Oj(t){const{header:n,footer:r,overlay:s,multiselect:l,onreorder:u,rowStyle:f,columnStyle:h,cellStyle:g,autoRowHeight:y,resize:w,clientWidth:b,clientHeight:S,responsiveLevel:k,hotkeys:A}=t,T=d.useContext(Ps),j=Bt(T,"dynamic"),I=Bt(T,"_columns"),N=Bt(T,"flatData"),P=Bt(T,"split"),H=Bt(T,"_sizes"),[F,$]=ai(T,"selectedRows"),D=Bt(T,"select"),K=Bt(T,"editor"),z=Bt(T,"scrollLeft"),q=Bt(T,"scrollTop"),W=Bt(T,"tree"),Y=Bt(T,"focusCell"),V=Bt(T,"_print"),he=Bt(T,"undo"),ee=Bt(T,"reorder"),U=Bt(T,"_rowHeightFromData"),[L,le]=d.useState(0);d.useEffect(()=>{le(ha())},[]);const[ve,J]=d.useState(0),Ae=d.useMemo(()=>(I||[]).some(se=>!se.hidden&&se.flexgrow),[I]),ce=d.useMemo(()=>H?.rowHeight||0,[H]),Te=d.useRef(null),[Fe,$e]=d.useState(null),[Ze,de]=d.useState(null),Be=d.useMemo(()=>{let se=[],ze=0;return P&&P.left&&(se=(I||[]).slice(0,P.left).filter(st=>!st.hidden).map(st=>({...st})),se.forEach(st=>{st.fixed={left:1,leftSize:P.left},st.left=ze,ze+=st.width}),se.length&&(se[se.length-1].fixed.left=-1)),{columns:se,width:ze}},[P,I]),Ve=d.useMemo(()=>{let se=[],ze=0;if(P&&P.right){se=(I||[]).slice(P.right*-1).filter(st=>!st.hidden).map(st=>({...st}));for(let st=se.length-1;st>=0;st--){const Lt=se[st];Lt.fixed={right:1},Lt.right=ze,ze+=Lt.width}se.length&&(se[0].fixed={right:-1})}return{columns:se,width:ze}},[P,I]),Je=d.useMemo(()=>{const se=(I||[]).slice(P?.left||0,(I||[]).length-(P?.right??0)).filter(ze=>!ze.hidden);return se.forEach(ze=>{ze.fixed=0}),se},[I,P]),Qe=d.useMemo(()=>(I||[]).reduce((se,ze)=>(ze.hidden||(se+=ze.width),se),0),[I]),yt=1;function ne(se,ze,st){let Lt=ze,Sn=se;if(Je.length){let on=Je.length;for(let xt=se;xt>=0;xt--)Je[xt][st].forEach(Jt=>{Jt.colspan>1&&xt>se-Jt.colspan&&xt<on&&(on=xt)});if(on!==Je.length&&on<se){for(let xt=on;xt<se;xt++)Lt-=Je[xt].width;Sn=on}}return{index:Sn,delta:Lt}}const me=d.useMemo(()=>{let se,ze,st;const Lt=z||0,Sn=(z||0)+(b||0);let on=0,xt=0,Jt=0,In=0;Je.forEach(($n,Un)=>{Lt>Jt&&(on=Un,In=Jt),Jt=Jt+$n.width,Sn>Jt&&(xt=Un+yt)});const zn={header:0,footer:0};for(let $n=xt;$n>=on;$n--)["header","footer"].forEach(Un=>{Je[$n]&&Je[$n][Un].forEach(go=>{const jn=go.colspan;if(jn&&jn>1){const ri=jn-(xt-$n+1);ri>0&&(zn[Un]=Math.max(zn[Un],ri))}})});const Cn=ne(on,In,"header"),bn=ne(on,In,"footer"),kn=Cn.delta,Ce=Cn.index,Ln=bn.delta,En=bn.index;return Ae&&Qe>(b||0)?se=ze=st=[...Be.columns,...Je,...Ve.columns]:(se=[...Be.columns,...Je.slice(on,xt+1),...Ve.columns],ze=[...Be.columns,...Je.slice(Ce,xt+zn.header+1),...Ve.columns],st=[...Be.columns,...Je.slice(En,xt+zn.footer+1),...Ve.columns]),{data:se||[],header:ze||[],footer:st||[],d:In,df:Ln,dh:kn}},[Je,Be,Ve,z,b,Ae,Qe]),Ge=d.useMemo(()=>n&&H?.headerHeight||0,[n,H]),Se=d.useMemo(()=>r&&H?.footerHeight||0,[r,H]),ge=d.useMemo(()=>b&&S?Qe>=b:!1,[b,S,Qe]),[Ue,Me]=d.useState(!1),rt=d.useMemo(()=>(S||0)-Ge-Se-(ge?L:0),[S,Ge,Se,ge,L]),At=d.useMemo(()=>Math.ceil((rt||0)/(ce||1))+1,[rt,ce]),O=d.useRef([]),[qe,B]=d.useState(0),[Oe,We]=d.useState(void 0),et=d.useMemo(()=>{let se=0,ze=0;const st=2,Lt=q||0;if(y){let xt=Lt;for(;xt>0;)xt-=O.current[se]||ce,se++;ze=Lt-xt;for(let Jt=Math.max(0,se-st-1);Jt<se;Jt++)ze-=O.current[se-Jt]||ce;se=Math.max(0,se-st)}else{if(U){let xt=0,Jt=0;for(let bn=0;bn<(N||[]).length;bn++){const kn=N[bn].rowHeight||ce;if(Jt+kn>Lt){xt=bn;break}Jt+=kn}se=Math.max(0,xt-st);for(let bn=0;bn<se;bn++)ze+=N[bn].rowHeight||ce;let In=0,zn=0;for(let bn=xt+1;bn<(N||[]).length;bn++){const kn=N[bn].rowHeight||ce;if(In++,zn+kn>rt)break;zn+=kn}const Cn=Math.min(j?j.rowCount:(N||[]).length,xt+In+st);return{d:ze,start:se,end:Cn}}se=Math.floor(Lt/(ce||1)),se=Math.max(0,se-st),ze=se*(ce||0)}const Sn=j?j.rowCount:(N||[]).length,on=Math.min(Sn,se+(At||0)+st);return{d:ze,start:se,end:on}},[y,U,q,ce,j,N,At,rt]),it=d.useMemo(()=>{const se=j?j.rowCount:(N||[]).length;if(y)return qe+et.d+(se-(Oe||0))*(ce||0);if(!U)return se*(ce||0);let ze=0;for(let st=0;st<se;st++)ze+=N[st]?.rowHeight||ce;return ze},[j,N,ce,y,U,qe,et.d,Oe]),ye=d.useRef({});ye.current={clientWidth:b,clientHeight:S,fullHeight:it,headerHeight:Ge,footerHeight:Se,fullWidth:Qe,SCROLLSIZE:L};const Ne=d.useCallback(()=>{const se=ye.current;Me(se.clientWidth&&se.clientHeight?se.fullHeight+se.headerHeight+se.footerHeight>=se.clientHeight-(se.fullWidth>=se.clientWidth?se.SCROLLSIZE:0):!1)},[]);d.useEffect(()=>{const se=requestAnimationFrame(Ne);return()=>window.cancelAnimationFrame(se)},[ve,Ne]),d.useEffect(()=>{Ne()},[S,Ne]);const He=d.useMemo(()=>Ae&&Qe<=(b||0)?(b||0)-0-(Ue?L:0):Qe,[Ae,Qe,b,Ue,L,ge]),pe=d.useMemo(()=>Ae&&Qe<=(b||0)?b||0:He<(b||0)?Qe+(Ue?L:0):-1,[Ae,Qe,b,He,Ue,L]),ae=d.useRef({});d.useEffect(()=>{if(j&&(ae.current.start!==et.start||ae.current.end!==et.end)){const{start:se,end:ze}=et;ae.current={start:se,end:ze},T&&T.exec&&T.exec("request-data",{row:{start:se,end:ze}})}},[j,et,T]);const fe=d.useMemo(()=>j?N||[]:(N||[]).slice(et.start,et.end),[j,N,et]),Ee=d.useMemo(()=>(F||[]).filter(se=>(fe||[]).some(ze=>ze.id===se)),[$,fe]),je=d.useMemo(()=>et.start,[et.start]),De=d.useRef({top:q,left:z});De.current={top:q,left:z};const Et=d.useCallback(se=>{const ze=se.target.scrollTop,st=se.target.scrollLeft,Lt=De.current;(ze!==Lt.top||st!==Lt.left)&&T.exec("scroll-to",{top:ze,left:st})},[T]),at=d.useCallback(se=>{se.shiftKey&&se.preventDefault(),Te.current&&Te.current.focus&&Te.current.focus()},[]),ft=d.useCallback(()=>!!(I||[]).find(se=>!!se.draggable),[I]),jt=d.useRef(null),Ut=d.useRef(null),wt=d.useRef({dblclick:(se,ze)=>{const st={id:se,column:vm(ze,"data-col-id")};T.exec("open-editor",st)},click:(se,ze)=>{if(ze.target.closest("input")||jt.current)return;const st=vm(ze,"data-col-id");if(Y?.id!==se&&T.exec("focus-cell",{row:se,column:st,eventSource:"click"}),D===!1)return;const Lt=l&&(ze.ctrlKey||ze.metaKey),Sn=l&&ze.shiftKey;(Lt||F.length>1||!F.includes(se))&&T.exec("select-row",{id:se,toggle:Lt,range:Sn})},"toggle-row":se=>{const ze=T.getRow(se);T.exec(ze.open!==!1?"close-row":"open-row",{id:se})},"ignore-click":()=>!1}),Wt=d.useMemo(()=>({top:Ge,bottom:Se,left:Be.width,xScroll:ge,yScroll:Ue,sense:y&&Ze?Ze.offsetHeight:Math.max(H?.rowHeight||0,40),node:Te.current&&Te.current.firstElementChild}),[Ge,Se,Be.width,ge,Ue,y,Ze,H]);function gt(se,ze){const{container:st,sourceNode:Lt,from:Sn}=ze;if(ft()&&!Lt.getAttribute("draggable-data"))return!1;$e(Sn),W&&T.getRow(Sn).open&&T.exec("close-row",{id:Sn,nested:!0});const on=Hd(Lt),xt=on.cloneNode(!0);xt.classList.remove("wx-selected"),xt.querySelectorAll("[tabindex]").forEach(Cn=>Cn.setAttribute("tabindex","-1")),st.appendChild(xt),de(xt);const Jt=(z||0)-me.d,In=Ue?L:0;st.style.width=Math.min((b||0)-In,Ae&&Qe<=(b||0)?He:He-In)+Jt+"px";const zn=eh(on);ze.offset={x:Jt,y:-Math.round(zn.height/2)},Ut.current||(Ut.current=se.clientY)}function yn(se,ze){const{from:st}=ze,Lt=ze.pos,Sn=eh(Te.current);Lt.x=Sn.x;const on=Wt.top;if(Lt.y<on)Lt.y=on;else{const xt=Sn.height-(ge&&L>0?L:Math.round(Wt.sense/2))-Wt.bottom;Lt.y>xt&&(Lt.y=xt)}if(Te.current.contains(ze.targetNode)){const xt=Hd(ze.targetNode),Jt=xt&&Rh(xt);if(Jt&&Jt!==st){ze.to=Jt;const In=y?Ze?.offsetHeight:H?.rowHeight;if(Ze&&((q||0)===0||Lt.y>on+In-1)){const zn=xt.getBoundingClientRect(),Cn=eh(Ze).y,bn=zn.y,kn=Cn>bn?-1:1,Ce=kn===1?"after":"before",Ln=T.getState().flatData,En=Math.abs(Ln.findIndex(Un=>Un.id===st)-Ln.findIndex(Un=>Un.id===Jt)),$n=En!==1?Ce==="before"?"after":"before":Ce;if(En===1&&(kn===-1&&se.clientY>Ut.current||kn===1&&se.clientY<Ut.current))return;Ut.current=se.clientY,T.exec("move-item",{id:st,target:Jt,mode:$n,inProgress:!0})}}u&&u({event:se,context:ze})}mj(se,Sn,ze,Wt)}function mt(se,ze){const{from:st,to:Lt}=ze;T.exec("move-item",{id:st,target:Lt,inProgress:!1}),jt.current=setTimeout(()=>{jt.current=0},1),$e(null),de(null),Ut.current=null,tC(ze)}function ha(){const se=document.createElement("div");se.style.cssText="position:absolute;left:-1000px;width:100px;padding:0px;margin:0px;min-height:100px;overflow-y:scroll;",document.body.appendChild(se);const ze=se.offsetWidth-se.clientWidth;return document.body.removeChild(se),ze}const hn=d.useMemo(()=>pe>0?{width:`${pe}px`}:void 0,[pe]),na=d.useRef(null);function za(){Promise.resolve().then(()=>{let se=0,ze=je;const st=na.current;st&&(Array.from(st.children).forEach((Lt,Sn)=>{O.current[je+Sn]=Lt.offsetHeight,se+=Lt.offsetHeight,ze++}),B(se),We(ze))})}d.useEffect(()=>{fe&&y&&za()},[fe,y,je]);let[G,ot]=d.useState();d.useEffect(()=>{if(Y&&(!D||!Ee.length||Ee.includes(Y.row)))ot({...Y});else if(fe.length&&me.data.length){if(!G||Ee.length&&!Ee.includes(G.row)||fe.findIndex(se=>se.id===G.row)===-1||me.data.findIndex(se=>se.id===G.column&&!se.collapsed)===-1){const se=Ee[0]||fe[0].id,ze=me.data.findIndex(st=>!st.collapsed);ot(ze!==-1?{row:se,column:me.data[ze].id}:null)}}else ot(null)},[Y]);const Pt=d.useRef(null);d.useEffect(()=>{const se=Te.current;if(!se)return;const ze=lj(se,w);return()=>{typeof ze=="function"&&ze()}},[w]);const an=d.useRef({});Object.assign(an.current,{start:gt,move:yn,end:mt,getReorder:()=>ee,getDraggableInfo:()=>({hasDraggable:ft()})}),d.useEffect(()=>{const se=Te.current;return se?uj(se,an).destroy:void 0},[ee,Te.current]),d.useEffect(()=>{const se=Te.current;return se?ij(se,{keys:A!==!1&&{...sj,"ctrl+z":he,"ctrl+y":he,...A},exec:ze=>T.exec("hotkey",ze)}).destroy:void 0},[T,he,A]);const Dr=d.useRef({scroll:T.getReactiveState().scroll,scrollLeft:T.getReactiveState().scrollLeft,scrollTop:T.getReactiveState().scrollTop});Dr.current.getWidth=()=>(b||0)-(Ue?L:0),Dr.current.getHeight=()=>rt,Dr.current.getScrollMargin=()=>Be.width+Ve.width,d.useEffect(()=>{oj(Pt.current,Dr.current)},[]);const _t=d.useRef(null);d.useEffect(()=>{const se=_t.current;if(!se)return;const ze=[];ze.push(ho(se,()=>Y&&T.exec("focus-cell",{eventSource:"click"})).destroy),ze.push(uE(se,wt.current)),J(se.clientHeight);const st=new ResizeObserver(()=>{J(se.clientHeight)});return st.observe(se),ze.push(()=>st.disconnect()),()=>ze.forEach(Lt=>Lt())},[]);const vn=`wx-grid ${k?`wx-responsive-${k}`:""}`;return d.useEffect(()=>{Y&&(fe.some(se=>se.id===Y.row)&&me.data.some(se=>se.id===Y.column&&!se.collapsed)||T.exec("focus-cell",{eventSource:"destroy"}))},[Y,fe,me.data,T]),o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"wx-4VuBwK2D "+vn,style:{"--header-height":`${Ge}px`,"--footer-height":`${Se}px`,"--split-left-width":`${Be.width}px`,"--split-right-width":`${Ve.width}px`},children:o.jsx("div",{ref:Te,className:"wx-4VuBwK2D wx-table-box",style:hn,role:W?"treegrid":"grid","aria-colcount":me.data.length,"aria-rowcount":fe.length,"aria-multiselectable":W&&l?!0:void 0,tabIndex:-1,children:o.jsxs("div",{ref:Pt,className:"wx-4VuBwK2D wx-scroll",style:{overflowX:ge?"scroll":"hidden",overflowY:Ue?"scroll":"hidden"},onScroll:Et,children:[n?o.jsx("div",{className:"wx-4VuBwK2D wx-header-wrapper",children:o.jsx(hx,{contentWidth:He,deltaLeft:me.dh,columns:me.header,columnStyle:h,bodyHeight:rt-+r})}):null,o.jsxs("div",{ref:_t,className:"wx-4VuBwK2D wx-body",style:{width:`${He}px`,height:`${it}px`},onMouseDown:se=>at(se),children:[s?o.jsx(Tj,{overlay:s}):null,o.jsx("div",{ref:na,className:"wx-4VuBwK2D wx-data",style:{paddingTop:`${et.d}px`,paddingLeft:`${me.d}px`},children:fe.map((se,ze)=>{const st=F.indexOf(se.id)!==-1,Lt=Fe===se.id,Sn="wx-row"+(y?" wx-autoheight":"")+(f?" "+f(se):"")+(st?" wx-selected":"")+(Lt?" wx-inactive":""),on=y?{minHeight:`${se.rowHeight||ce}px`}:{height:`${se.rowHeight||ce}px`};return o.jsx("div",{className:"wx-4VuBwK2D "+Sn,"data-id":ar(se.id),"data-context-id":ar(se.id),style:on,role:"row","aria-rowindex":ze,"aria-expanded":se.open,"aria-level":W?se.$level+1:void 0,"aria-selected":W?st:void 0,tabIndex:-1,children:me.data.map(xt=>xt.collapsed?o.jsx("div",{className:"wx-4VuBwK2D wx-cell wx-collapsed"},xt.id):K?.id===se.id&&K.column===xt.id?o.jsx(Lj,{row:se,column:xt},xt.id):o.jsx(yj,{row:se,column:xt,columnStyle:h,cellStyle:g,reorder:ee,focusable:G?.row===se.id&&G?.column===xt.id},xt.id))},se.id)})})]}),r&&(N||[]).length?o.jsx(hx,{type:"footer",contentWidth:He,deltaLeft:me.df,columns:me.footer,columnStyle:h}):null]})})}),V?o.jsx(_j,{config:V,rowStyle:f,columnStyle:h,cellStyle:g,header:n,footer:r,reorder:ee}):null]})}const Fj=t=>t.split("-").map(n=>n?n.charAt(0).toUpperCase()+n.slice(1):"").join(""),Bj=d.forwardRef(function({data:t=[],columns:n=[],rowStyle:r=null,columnStyle:s=null,cellStyle:l=null,selectedRows:u,select:f=!0,multiselect:h=!1,header:g=!0,footer:y=!1,dynamic:w=null,overlay:b=null,reorder:S=!1,onReorder:k=null,autoRowHeight:A=!1,sizes:T,split:j,tree:I=!1,autoConfig:N=!1,init:P=null,responsive:H=null,sortMarks:F,undo:$=!1,hotkeys:D=null,filterValues:K,...z},q){const W=d.useRef();W.current=z;const Y=d.useMemo(()=>new JE(qS),[]),V=d.useMemo(()=>Y.in,[Y]),he=d.useRef(null);he.current===null&&(he.current=new FS((Ve,Je)=>{const Qe="on"+Fj(Ve);W.current&&W.current[Qe]&&W.current[Qe](Je)}),V.setNext(he.current));const ee=d.useMemo(()=>({getState:Y.getState.bind(Y),getReactiveState:Y.getReactive.bind(Y),getStores:()=>({data:Y}),exec:V.exec,setNext:Ve=>(he.current=he.current.setNext(Ve),he.current),intercept:V.intercept.bind(V),on:V.on.bind(V),detach:V.detach.bind(V),getRow:Y.getRow.bind(Y),getColumn:Y.getColumn.bind(Y)}),[Y,V]),[U,L]=d.useState(0),[le,ve]=d.useState(0),[J,Ae]=d.useState(null),[ce,Te]=d.useState(null),Fe=d.useMemo(()=>{if(N&&!n.length&&t.length){const Ve=t[0],Je=[];for(let Qe in Ve)if(Qe!=="id"&&Qe[0]!=="$"){let yt={id:Qe,header:Qe[0].toUpperCase()+Qe.slice(1)};typeof N=="object"&&(yt={...yt,...N}),Je.push(yt)}return Je}return(ce&&ce.columns)??n},[N,n,t,ce]),$e=d.useMemo(()=>(ce&&ce.sizes)??T,[ce,T]),Ze=d.useCallback(Ve=>{if(L(Ve.width),ve(Ve.height),H){const Je=Object.keys(H).map(Number).sort((Qe,yt)=>Qe-yt).find(Qe=>Ve.width<=Qe)??null;Je!==J&&(Te(H[Je]),Ae(Je))}},[H,J]),de=d.useContext(sr.theme),Be=d.useRef(0);return d.useEffect(()=>{if(!Be.current)P&&P(ee);else{const Ve=Y.getState();Y.init({data:t,columns:Fe,split:j||Ve.split,sizes:$e||Ve.sizes,selectedRows:u||Ve.selectedRows,dynamic:w,tree:I,sortMarks:F||Ve.sortMarks,filterValues:K||Ve.filterValues,undo:$,reorder:S,_skin:de,_select:f})}Be.current++},[Y,t,Fe,j,$e,u,w,I,F,K,$,S,de,f,P,ee]),Be.current===0&&Y.init({data:t,columns:Fe,split:j||{left:0},sizes:$e||{},selectedRows:u||[],dynamic:w,tree:I,sortMarks:F||{},filterValues:K||{},undo:$,reorder:S,_skin:de,select:f}),d.useImperativeHandle(q,()=>({...ee}),[ee]),o.jsx(Ps.Provider,{value:ee,children:o.jsx(dy,{words:fy,optional:!0,children:o.jsx(Oj,{header:g,footer:y,overlay:b,rowStyle:r,columnStyle:s,cellStyle:l,onReorder:k,multiselect:h,autoRowHeight:A,clientWidth:U,clientHeight:le,responsiveLevel:J,resize:Ze,hotkeys:D})})})});ry(gs);const rr=d.createContext(null),hy=d.createContext(null),gy=d.createContext(null);function Hj({children:t}){const n=d.useContext(sr.i18n),r=d.useMemo(()=>n.getGroup("filemanager"),[n]),s=d.useContext(rr),[l]=ai(s,"panels"),u=Bt(s,"activePanel"),f=l[u].path,[h,g]=d.useState(null),[y,w]=d.useState(null),[b,S]=d.useState(""),[k,A]=d.useState(""),[T,j]=d.useState(!1);function I(){const F=b.trim();if(!F){j(!0);return}h.add?s.exec("create-file",{file:{...h.item,name:F},parent:f}):k!==F&&s.exec("rename-file",{id:h.item.id,name:F}),N()}function N(){g(null),j(null),A(""),S("")}function P(){s.exec("delete-files",{ids:y.selected}),w(null)}const H=d.useMemo(()=>({showPrompt(F){const $=F.item.name||(F.item.type==="folder"?r("New folder"):`${r("New file")}.txt`);A($),S($),g({...F})},showConfirm(F){w({...F})}}),[r]);return o.jsxs(hy.Provider,{value:H,children:[o.jsx(HR,{children:t}),h?o.jsx(Pv,{title:r(`Enter ${h.item.type} name`),onConfirm:I,onCancel:N,children:o.jsx(cy,{error:T,select:!0,focus:!0,value:b,onChange:({value:F})=>S(F)})}):null,y?o.jsx(Pv,{title:r("Are you sure you want to delete these items:"),onConfirm:P,onCancel:()=>w(null),children:y.selected?o.jsx("ul",{className:"wx-gq7BMzEP wx-list",children:y.selected.map((F,$)=>o.jsx("li",{children:F},$))}):null}):null]})}let vx={"7z":!0,rar:!0,zip:!0,css:!0,html:!0,js:!0,php:!0,md:!0,xml:!0,sql:!0,aif:!0,mid:!0,mp3:!0,waw:!0,wma:!0,doc:!0,docx:!0,txt:!0,avi:!0,mov:!0,mp4:!0,mpeg:!0,mpg:!0,pdf:!0,xls:!0,xlsx:!0,gif:!0,jpg:!0,jpeg:!0,png:!0,psd:!0,tiff:!0,svg:!0,folder:!0,file:!0,multiple:!0,search:!0,none:!0};function zj(t){const n=t.lastIndexOf("."),r=n>0&&n<t.length-1?Math.min(10,t.length-n):Math.min(5,t.length),s=t.slice(0,-r),l=t.slice(-r);return[s,l]}function $j({item:t}){const n=d.useContext(rr),r=d.useContext(sr.i18n).getGroup("filemanager"),s=d.useContext(rr).templates,[l]=ai(n,"panels"),u=Bt(n,"activePanel"),f=Bt(n,"mode"),h=l[u].selected,g=d.useMemo(()=>s.preview(t,214,163),[s,t]),y=d.useMemo(()=>s.icon(t,"big"),[s,t]),[w,b]=d.useMemo(()=>zj(t.name),[t.name]);return o.jsx(o.Fragment,{children:t.id==="/wx-filemanager-parent-link"?f!=="search"?o.jsx("div",{className:"wx-GAOa4kDV wx-back-item",children:o.jsxs("div",{className:`wx-GAOa4kDV wx-back ${t.navigation?"wx-selected":""}`,"data-id":ar("/wx-filemanager-parent-link"),children:[o.jsx("i",{className:"wx-GAOa4kDV wxi-arrow-left"}),o.jsx("span",{children:r("Back to parent folder")})]})}):null:o.jsxs("div",{className:`wx-GAOa4kDV wx-item ${h?.length&&h.indexOf(t.id)>=0?"wx-selected":""}`,"data-id":ar(t.id),children:[g?o.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-preview",children:o.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:r("A miniature file preview"),src:g})}):y?o.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-icon",children:o.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:"",src:y})}):o.jsx("div",{className:"wx-GAOa4kDV wx-preview",children:o.jsx("i",{className:`wx-GAOa4kDV wxi-${t.type}`})}),t.type==="folder"?o.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[o.jsxs("div",{className:"wx-GAOa4kDV wx-folder-name",children:[o.jsx("span",{className:"wx-GAOa4kDV wx-type",children:r("Folder")}),o.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[o.jsx("span",{children:w}),o.jsx("span",{children:b})]})]}),o.jsx("div",{"data-action-id":ar(t.id),className:"wx-GAOa4kDV wx-more",children:o.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]}):o.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[o.jsx("div",{className:"wx-GAOa4kDV wx-file-name",children:o.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[o.jsx("span",{children:w}),o.jsx("span",{children:b})]})}),o.jsx("div",{"data-action-id":ar(t.id),className:"wx-GAOa4kDV wx-more",children:o.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]})]})})}function sC(){const t=d.useContext(rr),n=d.useContext(sr.i18n),r=d.useMemo(()=>n.getGroup("filemanager"),[n]),[s]=ai(t,"panels"),l=Bt(t,"activePanel"),u=Bt(t,"mode"),f=s[l]._files,h=s[l].selected,g=s[l].path,y=s[l]._crumbs,w=s[l]._selectNavigation,b=d.useCallback((N,P)=>{const H=P&&(P.ctrlKey||P.metaKey),F=P&&P.shiftKey;if(N==="/wx-filemanager-parent-link"){if(h.length&&(H||F))return;t.exec("select-file",{type:"navigation"});return}let $=N==="body"&&P?null:N;const D=P.target.className.indexOf("wx-more")!==-1||P.target.className.indexOf("wxi-dots-v")!==-1;setTimeout(()=>{t.exec("select-file",{id:$,toggle:H&&!D,range:F&&!D,panel:l})},1)},[t,h,l]),S=d.useCallback(()=>{y.length>1&&t.exec("set-path",{id:y[y.length-2].id,panel:l,selected:[y[y.length-1].id]})},[t,y,l]),k=d.useCallback(N=>{if(N==="/wx-filemanager-parent-link")return S();u==="search"&&t.exec("filter-files",{text:""});const P=f.find(H=>H.id===N);P&&(P.type=="folder"?t.exec("set-path",{id:P.id,panel:l}):t.exec("open-file",{id:P.id}))},[t,S,u,f,l]),A=d.useCallback((N,P)=>{(!h?.length||!h.filter(H=>H?.id===N).length>0)&&b(N,P)},[h,b]),T=d.useMemo(()=>g!=="/"?[{id:"/wx-filemanager-parent-link",name:r("Back to parent folder"),navigation:w},...f]:f,[g,r,w,f]),j=d.useRef(null),I=d.useRef();return d.useEffect(()=>{j.current&&(I.current?(I.current.click=b,I.current._dblclick=k,I.current.context=A):(I.current={click:b,dblclick:N=>I.current._dblclick(N),_dblclick:k,context:A},zd(j.current,I.current)))},[b,k,A]),u=="search"&&!T.length?o.jsx("div",{className:"wx-iyjASZCY wx-not-found",children:o.jsx("div",{className:"wx-iyjASZCY wx-not-found-text",children:r("Looks like nothing is here")})}):o.jsx("div",{tabIndex:0,className:"wx-iyjASZCY "+("wx-cards"+(g!=="/"&&u!=="search"?" wx-has-back-link":"")),"data-id":ar("body"),ref:j,children:T.map(N=>o.jsx($j,{item:N},N.id))})}function gu({name:t="",spin:n=!1,onClick:r}){return o.jsx("i",{"data-menu-ignore":"true",className:`wx-uwcvNSAG wx-icon wxi-${t} ${n?"wx-spin":""} ${r?"wx-clickable":""}`,onClick:()=>{r&&r()}})}function Uj(){const t=d.useContext(sr.i18n).getGroup("filemanager"),n=d.useContext(rr),r=Bt(n,"activePanel"),[s]=ai(n,"panels"),l=d.useMemo(()=>s[r]._crumbs,[s,r]);function u(){n.exec("filter-files",{text:""})}return o.jsxs("div",{className:"wx-GDJvtROw wx-search",children:[o.jsxs("div",{className:"wx-GDJvtROw wx-toolbar",children:[o.jsx("div",{className:"wx-GDJvtROw wx-back-icon",children:o.jsx(gu,{name:"angle-left",onClick:u})}),o.jsxs("div",{className:"wx-GDJvtROw wx-text",children:[t("Search results in")," ",Array.isArray(l)&&l.map((f,h)=>o.jsxs(d.Fragment,{children:[h?"/":null,f.id=="/"?t(f.name):f.name]},h))]})]}),o.jsx(sC,{})]})}function Gg({narrowMode:t,extraInfo:n}){const r=d.useContext(rr),{preview:s,icon:l}=r.templates,u=d.useContext(sr.i18n),f=d.useMemo(()=>u.getGroup("filemanager"),[u]),h=d.useMemo(()=>_d("%D, %d %F %Y, %H:%i",u.getRaw().calendar),[u]),[g,y]=ai(r,"panels"),w=Bt(r,"activePanel"),b=Bt(r,"preview"),S=Bt(r,"search"),k=d.useMemo(()=>{const D=g&&w!=null&&g[w]?._selected?.length||0;return S&&!D},[S,y,w]),A=d.useMemo(()=>{const D=g&&w!=null?g[w]:null;return D?k?D._files:D._selected:[]},[k,y,w]),T=d.useCallback((D,K)=>(D?`${D} ${f(D>1?"folders":"folder")} `:"")+(K?`${K} ${f(K>1?"files":"file")}`:""),[f]),j=d.useCallback(()=>{r.exec("show-preview",{mode:!b})},[r,b]),I=d.useCallback(D=>D.type==="folder"?f("Folder"):D.ext||f("Unknown file"),[f]),N=d.useMemo(()=>{let D,K,z,q,W,Y,V,he;if(A.length===1&&!k){K=A[0],D=K.name;const ee=s(K,400,500);ee?(z=ee,q=""):(q=l(K,"big"),z=""),W=K.type!=="folder"}else{if(K=W=null,D="",A.length){let ee=0,U=0,L=0,le=[],ve;A.forEach(Ae=>{typeof Ae.size>"u"&&(ve=!0,ee=void 0),ve||(ee+=Ae.size),le.push(I(Ae)),Ae.type==="folder"?U++:L++});const J=new Set(le);Y=J.size>1?f("multiple"):[...J][0],V=T(U,L),he=ee,k||(D=f("Multiple files"))}q=l({type:k?"search":A.length?"multiple":"none"},"big"),z=""}return{name:D,item:K,previewSrc:z,iconSrc:q,showDownloadIcon:W,type:Y,totalCount:V,totalSize:he}},[A,k,s,l,f,I,T]),P=d.useCallback(()=>{r.exec("download-file",{id:A[0].id})},[r,A]),H=d.useCallback(async D=>{if(!n||!D)return null;try{return await n(D)}catch(K){return console.log(K),null}},[n]),[F,$]=d.useState(null);return d.useEffect(()=>{let D=!1;return $(null),Promise.resolve(H(N.item)).then(K=>{D||$(K)}).catch(()=>{D||$(null)}),()=>{D=!0}},[H,N.item]),o.jsx("div",{className:"wx-O0BTtRrH wx-wrapper",children:A&&A.length?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"wx-O0BTtRrH wx-preview",children:[o.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[o.jsx("div",{className:"wx-O0BTtRrH wx-name",children:N.name}),o.jsxs("div",{className:"wx-O0BTtRrH wx-icons",children:[N.showDownloadIcon?o.jsx(gu,{name:"download",onClick:P}):null,t?o.jsx(gu,{name:"close",onClick:j}):null]})]}),N.previewSrc?o.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:o.jsx("img",{src:N.previewSrc,alt:f("A miniature file preview")})}):N.iconSrc?o.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:o.jsx("img",{src:N.iconSrc,alt:f("A miniature file preview")})}):o.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:N.item?o.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${N.item.type}`}):o.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${k?"search":"file-multiple-outline"}`})})]}),o.jsxs("div",{className:"wx-O0BTtRrH wx-info-panel",children:[o.jsx("div",{className:"wx-O0BTtRrH wx-title",children:f(k?"Found":"Information")}),o.jsxs("div",{className:"wx-O0BTtRrH wx-list",children:[N.item?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Type")}),o.jsx("span",{className:"wx-O0BTtRrH wx-value",children:I(N.item)}),typeof N.item.size<"u"?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Size")}),o.jsx("span",{className:"wx-O0BTtRrH wx-value",children:ym(N.item.size)})]}):null,o.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Date")}),o.jsxs("span",{className:"wx-O0BTtRrH wx-value",children:[h(N.item.date)," "]})]}):o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Count")}),o.jsx("span",{className:"wx-O0BTtRrH wx-value",children:N.totalCount}),o.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Type")}),o.jsx("span",{className:"wx-O0BTtRrH wx-value",children:N.type}),typeof N.totalSize<"u"?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Size")}),o.jsx("span",{className:"wx-O0BTtRrH wx-value",children:ym(N.totalSize)})]}):null]}),F?Object.entries(F).map(([D,K])=>o.jsxs($v.Fragment,{children:[o.jsx("span",{className:"wx-O0BTtRrH wx-name",children:D}),o.jsx("span",{className:"wx-O0BTtRrH wx-value",children:K})]},D)):null]})]})]}):o.jsxs("div",{className:"wx-O0BTtRrH wx-no-info-panel",children:[o.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[o.jsx("div",{className:"wx-O0BTtRrH wx-name",children:N.name}),o.jsx("div",{className:"wx-O0BTtRrH wx-icons",children:t?o.jsx(gu,{name:"close",onClick:j}):null})]}),o.jsx("div",{className:"wx-O0BTtRrH wx-no-info-wrapper",children:o.jsxs("div",{className:"wx-O0BTtRrH wx-no-info",children:[N.previewSrc?o.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:o.jsx("img",{src:N.previewSrc,alt:f("A miniature file preview")})}):N.iconSrc?o.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:o.jsx("img",{src:N.iconSrc,alt:f("A miniature file preview")})}):o.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:o.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${k?"search":"message-question-outline"}`})}),o.jsx("span",{className:"wx-O0BTtRrH wx-text",children:k?"":f("Select file or folder to view details")})]})})]})})}function iC({panel:t}){const n=d.useContext(rr),r=d.useContext(sr.i18n),s=d.useMemo(()=>r.getGroup("filemanager"),[r]),[l,u]=ai(n,"panels"),f=d.useMemo(()=>l[t]._files,[u,t]),h=d.useMemo(()=>l[t]._crumbs||[],[u,t]);function g(A){const T=my(A,h);n.exec("set-path",{id:A,panel:t,...T&&{selected:[T]}})}const[y,w]=d.useState(null);d.useEffect(()=>{f&&w(null)},[f]);function b(){w(!0),n.exec("request-data",{id:h[h.length-1].id}),setTimeout(()=>{w(null)},5e3)}const S=d.useRef(null),k=d.useRef();return d.useEffect(()=>{k.current?k.current.click=g:(k.current={click:g},zd(S.current,k.current))},[g]),o.jsxs("div",{className:"wx-SNY5LTYx wx-breadcrumbs","data-menu-ignore":"true",ref:S,children:[o.jsx("div",{className:"wx-SNY5LTYx wx-refresh-icon",children:o.jsx(gu,{name:"refresh",spin:!!y,onClick:b})}),h.map((A,T)=>o.jsxs($v.Fragment,{children:[T?o.jsx(gu,{name:"angle-right"}):null,o.jsx("div",{className:"wx-SNY5LTYx wx-item","data-id":ar(A.id),"data-menu-ignore":"true",children:A.id=="/"?s(A.name):A.name})]},T))]})}function qj({row:t}){const n=d.useContext(sr.i18n),[r]=d.useState(()=>n.getGroup("filemanager")),s=d.useContext(rr).templates,[l]=d.useState(()=>s.icon(t,"small"));return o.jsx("div",{className:"wx-qgAqG6sL wx-name-cell",children:t.id==="/wx-filemanager-parent-link"?o.jsxs(o.Fragment,{children:[o.jsx("i",{className:"wx-qgAqG6sL wxi-arrow-left"}),o.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",r("Back to parent folder")]})]}):o.jsxs(o.Fragment,{children:[l?o.jsx("img",{className:"wx-qgAqG6sL wx-icon",alt:"",src:l,height:"24px",width:"24px"}):o.jsx("i",{className:`wx-qgAqG6sL wxi-${t.type}`}),o.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",t.name," "]})]})})}function oC({children:t}){const n=d.useContext(rr),r=Bt(n,"activePanel"),s=d.useContext(gy),l=d.useRef(null);let u=d.useRef({});return u.current.drop=()=>{const f=l.current,h=VN(f,"data-panel");h&&h!=r&&n.exec("set-active-panel",{panel:h*1})},u.current.dragEnter=()=>{const f=l.current;f&&f.classList.toggle("wx-active")},u.current.dragLeave=()=>{const f=l.current;f&&f.classList.toggle("wx-active")},d.useEffect(()=>{const f=l.current;return s.droparea(f,u.current)},[]),o.jsx("div",{className:"wx-LT9X7tb7 wx-upload-area",ref:l,children:t})}function Fv({panel:t,active:n=!1,onClick:r,onContextMenu:s}){const l=d.useContext(rr),u=d.useContext(sr.i18n),f=d.useMemo(()=>u.getGroup("filemanager"),[u]),h=d.useMemo(()=>_d("%d %M %Y",u.getRaw().calendar),[u]),[g]=ai(l,"panels"),y=g[t].selected,w=g[t].path,b=g[t]._crumbs,S=g[t]._sorts,k=g[t]._selectNavigation,A=g[t]._files,T=d.useMemo(()=>[{id:"name",header:f("Name"),flexgrow:3,sort:!0,resize:!0,cell:qj},{id:"size",header:f("Size"),width:100,sort:!0,resize:!0,template:Y=>typeof Y=="number"?ym(Y):""},{id:"date",header:f("Date"),width:120,sort:!0,resize:!0,template:Y=>Y?h(Y):""}],[f,h]),j=d.useRef(null),I=d.useRef(null),N=d.useMemo(()=>k?["/wx-filemanager-parent-link"]:[...y],[k,y]);function P(Y,V){if(V&&V.target&&V.target.className&&V.target.className.indexOf("wx-grip")!==-1)return;const he=V&&(V.ctrlKey||V.metaKey),ee=V&&V.shiftKey;if(Y==="/wx-filemanager-parent-link"){if(y.length&&(he||ee))return;l.exec("select-file",{type:"navigation"});return}let U=Y==="body"&&V?null:Y;!j.current&&!I.current?l.exec("select-file",{id:U,toggle:he,range:ee,panel:t}):(j.current=null,I.current=null)}function H(){b.length>1&&l.exec("set-path",{id:b[b.length-2].id,panel:t,selected:[b[b.length-1].id]})}function F(Y){if(Y==="/wx-filemanager-parent-link")return H();const V=A.find(he=>he.id===Y);V&&(V.type==="folder"?l.exec("set-path",{id:V.id,panel:t}):l.exec("open-file",{id:V.id}))}function $(Y){const V=Y.key,he=S[w];let ee=he?"asc":"desc";he&&he.key===V&&(ee=he.order==="asc"?"desc":"asc"),l.exec("sort-files",{key:V,order:ee,panel:t,path:w})}function D(Y){Y.intercept("sort-rows",V=>(j.current=!0,$(V),!1)),Y.intercept("select-row",()=>!1),Y.on("resize-column",()=>I.current=!0),Y.intercept("hotkey",()=>!1)}const K=d.useMemo(()=>w!=="/"?[{id:"/wx-filemanager-parent-link",name:f("Back to parent folder")},...A]:A,[w,A,f]),z=d.useMemo(()=>{if(K&&S&&S[w]){const{key:Y,order:V}=S[w];return{[Y]:{order:V}}}},[K,S,w]),q=d.useRef(null),W=d.useRef();return d.useEffect(()=>{W.current?(W.current.click=P,W.current._dblclick=F):(W.current={click:P,dblclick:Y=>W.current._dblclick(Y),_dblclick:F},zd(q.current,W.current))},[P,F]),o.jsxs("div",{onClick:r,onContextMenu:s,className:"wx-SSaVhET7 wx-wrapper",children:[o.jsx(iC,{panel:t}),o.jsx("div",{"data-id":ar("body"),className:`wx-SSaVhET7 wx-list ${n?"wx-active":""}`,ref:q,children:o.jsx(oC,{children:o.jsx(Bj,{init:D,data:K,columns:T,selectedRows:N,columnStyle:()=>"wx-SSaVhET7 wx-each-cell",sizes:{rowHeight:42,headerHeight:42},sortMarks:z})})})]})}function Wj(){const t=d.useContext(rr),n=Bt(t,"activePanel");function r(s){t.exec("set-active-panel",{panel:s})}return o.jsxs("div",{className:"wx-L55BfJa2 wx-panels","data-id":ar("body"),children:[o.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":0,children:o.jsx(Fv,{panel:0,active:n==0,onClick:()=>r(0),onContextMenu:()=>r(0)})}),o.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":1,children:o.jsx(Fv,{panel:1,active:n==1,onClick:()=>r(1),onContextMenu:()=>r(1)})})]})}function lC({folderIcon:t=!1,folder:n={}}){const r=d.useContext(rr),[s,l]=ai(r,"panels"),u=Bt(r,"activePanel"),f=d.useMemo(()=>s[u].path,[l,u]),h=d.useContext(sr.i18n),g=d.useMemo(()=>h.getGroup("filemanager"),[h]),y=d.useMemo(()=>!!n.data?.find(k=>k.type==="folder"),[n]),w=d.useMemo(()=>n.id=="/"?g(n.name):n.name,[n,g]),b=d.useMemo(()=>n.$level>1?(n.$level-1)*20:0,[n]),S=n.open;return o.jsxs(o.Fragment,{children:[o.jsxs("li",{"data-id":ar(n.id),className:`wx-NYfhvGIt wx-folder${f===n.id?" wx-selected":""}`,style:{paddingLeft:`${b}px`},children:[y?o.jsx("i",{className:`wx-NYfhvGIt wx-toggle wxi-${S?"angle-down":"angle-right"}`,"data-action":"toggle"}):o.jsx("span",{className:"wx-NYfhvGIt wx-toggle-placeholder"}),o.jsx("i",{className:"wx-NYfhvGIt "+(t||"wxi-folder")}),o.jsxs("span",{className:"wx-NYfhvGIt wx-name",children:[" ",w," "]})]}),S&&n.data&&n.data.length&&y?o.jsx(o.Fragment,{children:n.data.map(k=>k.type==="folder"?o.jsx(lC,{folder:k},k.id):null)}):null]})}function Gj(){const t=d.useContext(rr),[n,r]=ai(t,"data"),[s,l]=ai(t,"panels"),u=Bt(t,"activePanel"),f=d.useMemo(()=>s[u]._crumbs,[l,u]),h=d.useCallback(k=>{t.exec("open-tree-folder",{id:k,mode:!n.byId(k).open})},[t,r]),g=d.useCallback(k=>{const A=my(k,f);t.exec("set-path",{id:k,panel:u,...A&&{selected:[A]}})},[t,f,u]),[y,w]=d.useState([]);d.useEffect(()=>{w(n.byId(0).data)},[r]);const b=d.useRef(null),S=d.useRef();return d.useEffect(()=>{S.current?(S.current.click=g,S.current.toggle=h):(S.current={click:g,toggle:h},zd(b.current,S.current))},[g,h]),o.jsx("ul",{ref:b,className:"wx-LyHJ6R6A",children:y.map(k=>k.type==="folder"?o.jsx(lC,{folder:k},k.id):null)})}function Vj(){const t=d.useContext(rr),n=d.useContext(sr.i18n),r=d.useMemo(()=>n.getGroup("filemanager"),[n]),s=Bt(t,"drive"),l=s?s.used:"",u=s?s.total:"";return l&&u?o.jsxs("div",{className:"wx-DetSyKGG wx-drive",children:[o.jsx("progress",{value:l,max:u,className:"wx-DetSyKGG wx-progress"}),o.jsxs("p",{children:[ym(l)," ",r("of")," ",ym(u)," ",r("used")]})]}):null}function Kj({option:t}){const n=d.useContext(sr.i18n).getGroup("filemanager"),r=d.useContext(gy),s=d.useCallback(()=>{r.open({})},[r]);return o.jsx("div",{className:"wx-9XiKcxq5 wx-upload-button",onClick:s,children:o.jsx("span",{children:n(t.text)})})}function Qj({readonly:t,menuOptions:n}){const r=d.useContext(sr.i18n).getGroup("filemanager"),{showPrompt:s}=d.useContext(hy);d.useEffect(()=>{mE("upload",Kj)},[]);function l({action:f}){f&&(f.id==="add-file"?s({item:{type:"file",size:0,date:new Date},add:!0}):f.id==="add-folder"&&s({item:{type:"folder",date:new Date},add:!0}))}const u=d.useMemo(()=>n("add").map(f=>(f.text=r(f.text),f)),[n,r]);return o.jsxs("div",{className:"wx-FlucfALM wx-wrapper",children:[!t&&o.jsx("div",{className:"wx-FlucfALM wx-button",children:o.jsx(hE,{options:u,at:"bottom-fit",onClick:l,children:o.jsx(um,{type:"primary block",children:r("Add New")})})}),o.jsx("div",{className:"wx-FlucfALM wx-tree",children:o.jsx(Gj,{})}),o.jsx(Vj,{})]})}function Yj({value:t="",onSearch:n}){const[r,s]=$S(t),l=d.useContext(sr.i18n).getGroup("filemanager"),u=d.useRef(null),f=d.useMemo(()=>r!==""?"wxi-close":"wxi-search",[r]);function h(y){const w=y.target.value;s(w),n&&n({value:w})}function g(){s(""),u.current&&u.current.focus(),n&&n({value:""})}return o.jsxs("div",{className:"wx-lUZMtgT1 wx-search-input",children:[o.jsx("i",{className:`wx-lUZMtgT1 wx-icon ${f}`,onClick:g}),o.jsx("input",{type:"text",className:"wx-lUZMtgT1 wx-text",ref:u,value:r,onInput:h,placeholder:l("Search")})]})}function Xj({narrowMode:t=!1,onShowTree:n}){const r=d.useContext(rr),s=d.useContext(sr.i18n).getGroup("filemanager"),l=Bt(r,"mode"),u=Bt(r,"preview"),f=Bt(r,"search"),h=[{icon:"wxi-view-sequential",id:"table"},{icon:"wxi-view-grid",id:"cards"},{icon:"wxi-view-column",id:"panels"}];function g({value:b}){r.exec("set-mode",{mode:b})}function y(b){b.preventDefault(),r.exec("show-preview",{mode:!u})}function w(b){r.exec("filter-files",{text:b.value})}return o.jsxs("div",{className:"wx-5PZQQztG wx-toolbar",children:[o.jsxs("div",{className:"wx-5PZQQztG wx-left "+(t?"wx-left-narrow":""),children:[t?l==="panels"||l==="search"?null:o.jsx("div",{className:"wx-5PZQQztG wx-sidebar-icon","data-id":ar("toggle-tree"),children:o.jsx(gu,{onClick:()=>n&&n(),name:"subtask"})}):o.jsx("div",{className:"wx-5PZQQztG wx-name",children:s("Files")}),o.jsx(Yj,{onSearch:w,value:f})]}),o.jsxs("div",{className:"wx-5PZQQztG wx-right",children:[t?null:o.jsx("div",{className:"wx-5PZQQztG wx-preview-icon",children:o.jsx(zR,{onClick:y,value:u,children:o.jsx("i",{className:"wx-5PZQQztG wxi-eye"})})}),o.jsx("div",{className:"wx-5PZQQztG wx-modes",children:o.jsx(PR,{value:l,options:h,onChange:g})})]})]})}function Zj(){const t=d.useContext(rr),n=Bt(t,"activePanel");return o.jsxs("div",{className:"wx-NwohNJzN wx-wrapper",children:[o.jsx(iC,{panel:n}),o.jsx(oC,{children:o.jsx(sC,{})})]})}function Jj({readonly:t=!1,menuOptions:n,extraInfo:r}){const s=d.useRef(null),l=d.useRef(null),[u,f]=d.useState(void 0),[h,g]=d.useState(void 0),[y,w]=d.useState(!1),b=QS(),S=d.useContext(rr),{showPrompt:k,showConfirm:A}=d.useContext(hy),T=d.useContext(sr.i18n),j=d.useMemo(()=>T.getGroup("filemanager"),[T]),I=Bt(S,"mode"),N=Bt(S,"preview"),P=Bt(S,"activePanel"),[H,F]=ai(S,"panels"),$=d.useMemo(()=>(H&&P!=null?H[P]:null)?.selected??[],[F,P]),D=d.useMemo(()=>(H&&P!=null?H[P]:null)?.path,[F,P]),[K,z]=d.useState([]);d.useEffect(()=>{const J=s.current;if(!J)return;const Ae=new ResizeObserver(ce=>{const Te=ce[0]?.borderBoxSize?.[0]?.inlineSize;typeof Te=="number"&&g(Te<768)});return Ae.observe(J),()=>{Ae.disconnect()}},[]);const q=d.useCallback(()=>{w(J=>!J)},[]),W=d.useCallback(J=>{h&&vm(J)!=="toggle-tree"&&w(!1)},[h]);d.useEffect(()=>{const J=l.current;if(J)return ho(J,W).destroy},[W]),d.useEffect(()=>{const J=l.current;if(!J)return;const Ae=new ResizeObserver(()=>{J&&f(J.clientWidth)});return Ae.observe(J),J&&f(J.clientWidth),()=>{Ae.disconnect()}},[]);const Y=d.useMemo(()=>({icon:"wxi-eye",text:"Preview",id:"preview"}),[]),V=d.useCallback(J=>{let Ae=h?[Y]:[];return J==="file"&&(Ae=[...Ae,...n().filter(ce=>ce.id==="download")]),Ae},[h,Y,n]),he=d.useRef(null),ee=d.useCallback((J,Ae,ce)=>{const Te=ce?[Ae.id]:$;switch(J){case"download":S.exec("download-file",{id:Ae.id});break;case"copy":case"move":he.current={action:J,ids:Te};break;case"paste":he.current&&S.exec(he.current.action==="copy"?"copy-files":"move-files",{ids:he.current.ids,target:Ae?.type==="folder"?Ae.id:D});break;case"rename":k({item:Ae});break;case"delete":A({selected:Te});break;case"preview":S.exec("show-preview",{mode:!N});break}},[S,$,D,k,A,N]),U=d.useCallback(()=>H?.[P],[H,P]);d.useEffect(()=>{const J=s.current;if(!J)return;const Ae=nE(J,{api:S,menuOptions:t?V:n,performAction:ee,getPanel:U});return()=>{typeof Ae=="function"?Ae():Ae&&typeof Ae.destroy=="function"&&Ae.destroy()}},[S,t,V,n,ee,U]);const L=d.useCallback((J,Ae)=>{const ce=J?S.getFile(J):null,Te=Ae.target.closest(".tree-item.folder");let Fe;if(t)Fe=V(ce?.type);else{switch(J){case"body":Fe=n(J);break;default:if(ce)if(!Te&&$.length>1)Fe=h?[Y,...n("multiselect")]:n("multiselect");else if(J==="/")Fe=n("folder",ce).filter($e=>$e.id==="paste");else{const $e=n(ce.type,ce);$e&&(Fe=h?[Y,...$e]:$e)}}I==="search"&&(Fe=Fe?.filter($e=>$e.id!=="paste"))}if(ce?.id&&(!$.length||!$.some($e=>$e===ce.id))&&!Te&&S.exec("select-file",{id:ce.id}),Fe?.length)return Fe.forEach($e=>{Te&&($e.hotkey=""),$e.text&&($e.text=j($e.text)),$e.hotkey&&($e.subtext=$e.hotkey)}),z(Fe),ce||{}},[S,t,V,n,$,h,Y,I,j]),le=d.useCallback(J=>{const{action:Ae,context:ce}=J;Ae&&ee(Ae.id,ce,!Ae.hotkey)},[ee]);async function ve(J){await Promise.resolve();const{name:Ae,size:ce}=J.file;S.exec("create-file",{file:{name:Ae,size:ce,date:new Date,file:J.file},parent:D})}return o.jsx("div",{className:"wx-RJbNonjJ wx-filemanager wx-flex",ref:s,"data-menu-ignore":"false",children:h&&N?o.jsx("div",{className:"wx-RJbNonjJ wx-info-narrow",children:o.jsx(Gg,{narrowMode:h,extraInfo:r})}):o.jsxs(o.Fragment,{children:[o.jsx(Xj,{narrowMode:h,onShowTree:q}),o.jsx(gE,{dataKey:"id",at:"point",options:K,resolver:L,onClick:le,children:o.jsxs(KS,{dataKey:"actionId",options:K,resolver:L,onClick:le,children:[o.jsx(xE,{data:b,apiOnly:!0,uploadURL:ve}),o.jsx(gy.Provider,{value:b,children:o.jsx("div",{className:"wx-RJbNonjJ wx-content-wrapper wx-flex",children:I!=="panels"&&I!=="search"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"wx-RJbNonjJ "+["wx-sidebar",h?"wx-sidebar-narrow":"",y?"wx-sidebar-visible":""].filter(Boolean).join(" "),ref:l,children:o.jsx(Qj,{readonly:t,menuOptions:n})}),o.jsxs("div",{className:"wx-RJbNonjJ wx-content",style:{width:`calc(100% - ${u||0}px - 10px)`},children:[o.jsx("div",{className:`wx-RJbNonjJ wx-content-item${N?"":"-fit"}`,"data-id":ar("body"),children:I==="table"?o.jsx(Fv,{panel:P}):o.jsx(Zj,{})}),N?o.jsx("div",{className:"wx-RJbNonjJ wx-info",children:o.jsx(Gg,{extraInfo:r})}):null]})]}):o.jsxs(o.Fragment,{children:[o.jsx("div",{className:`wx-RJbNonjJ wx-content-item${N?"":"-fit"}`,children:I==="panels"?o.jsx(Wj,{}):o.jsx(Uj,{})}),N?o.jsx("div",{className:"wx-RJbNonjJ wx-info",children:o.jsx(Gg,{extraInfo:r})}):null]})})})]})})]})})}const eD=t=>t.split("-").map(n=>n?n.charAt(0).toUpperCase()+n.slice(1):"").join("");function tD(t,n){const{type:r,ext:s}=t;if(r==="folder")return!1;let l;return r&&r!=="file"&&vx[r]?l=r:s?l=vx[s]?s:"file":l="unknown",`https://cdn.svar.dev/icons/filemanager/vivid/${n}/${l}.svg`}const nD=d.forwardRef(function(t,n){const{data:r=[],mode:s="cards",drive:l=null,preview:u=!1,panels:f=null,activePanel:h=0,readonly:g=!1,menuOptions:y=JR,extraInfo:w=null,init:b=null,icons:S=tD,previews:k=null,...A}=t,T=d.useRef();T.current=A;const j=d.useMemo(()=>new ZR(qS),[]),I=d.useMemo(()=>j.in,[j]),N=d.useRef(null);N.current===null&&(N.current=new FS((F,$)=>{const D="on"+eD(F);T.current&&T.current[D]&&T.current[D]($)}),I.setNext(N.current));const P=d.useMemo(()=>({getState:j.getState.bind(j),getReactiveState:j.getReactive.bind(j),getStores:()=>({data:j}),exec:I.exec,setNext:F=>(N.current=N.current.setNext(F),N.current),intercept:I.intercept.bind(I),on:I.on.bind(I),detach:I.detach.bind(I),getFile:j.getFile.bind(j),serialize:j.serialize.bind(j),templates:{preview:k||(()=>null),icon:S==="simple"?(()=>null):S}}),[j,I]),H=d.useRef(0);return d.useEffect(()=>{if(!H.current)b&&b(P);else{const F=j.getState();j.init({data:r,mode:s,drive:l,preview:u,panels:f||F.panels||[],activePanel:h})}H.current++},[j,r,s,l,u,f,h,b,P]),H.current===0&&j.init({data:r,mode:s,drive:l,preview:u,panels:f||[],activePanel:h}),d.useImperativeHandle(n,()=>({...P}),[P]),o.jsx(rr.Provider,{value:P,children:o.jsx(dy,{words:fy,optional:!0,children:o.jsx(Hj,{children:o.jsx(Jj,{readonly:g,menuOptions:y,extraInfo:w})})})})});function aD({fonts:t=!0,children:n}){return n?o.jsx(nx,{fonts:t,children:n}):o.jsx(nx,{fonts:t})}ry(gs);function vy(t,n){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid Hub ${n} response.`);return t}function Cm(t,n,r){const s=vy(t,r);if(!Array.isArray(s[n]))throw new Error(`Invalid Hub ${r} response: ${n} must be an array.`);return s[n]}function rD(t,n,r){const s=vy(t,r);if(!s[n]||typeof s[n]!="object"||Array.isArray(s[n]))throw new Error(`Invalid Hub ${r} response: ${n} must be an object.`);return s[n]}async function sD(t,n=!1){return Cm(await lt(`/api/remote/filesystem/roots${n?"?refresh=1":""}`,void 0,t),"roots","filesystem roots")}async function Vg(t,n){const r=await lt(`/api/remote/filesystem/entries?id=${encodeURIComponent(t)}`,void 0,n);return{folder:rD(r,"folder","filesystem entries"),entries:Cm(r,"entries","filesystem entries")}}async function iD(t,n){return lt("/api/remote/filesystem/selection/scan",{method:"POST",body:JSON.stringify({itemIds:t})},n)}async function oD(t,n,r,s){return lt("/api/remote/files/from-hub",{method:"POST",body:JSON.stringify({itemIds:t,deviceIds:n,remoteDirectory:r})},s)}async function lD(t,n=!1){const r=await lt(`/api/remote/files/jobs?active=${n?"1":"0"}`,void 0,t);return{jobs:Cm(r,"jobs","file transfer jobs")}}async function cD(t,n){return lt(`/api/remote/files/jobs/${encodeURIComponent(t)}`,void 0,n)}async function uD(t,n){return lt(`/api/remote/files/jobs/${encodeURIComponent(t)}/cancel`,{method:"POST"},n)}async function yx(t){return Cm(await lt("/api/remote/filesystem/shared-folders",void 0,t),"folders","shared folders")}async function dD(t,n){return lt("/api/remote/filesystem/shared-folders",{method:"POST",body:JSON.stringify({sourceId:t})},n)}async function fD(t,n,r){return lt(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)},r)}async function mD(t,n){return lt(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}`,{method:"DELETE"},n)}async function pD(t,n,r,s){const l=await lt(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}/sync`,{method:"POST",body:JSON.stringify({deviceIds:n,remoteDirectory:r})},s),u=vy(l,"shared folder sync");return{ok:u.ok===!0,jobs:Cm(l,"jobs","shared folder sync"),files:Number(u.files||0),totalBytes:Number(u.totalBytes||0)}}function hD(t){return{id:String(t.id),parentId:t.parent,name:t.name,type:t.type==="file"?"file":"folder",size:Number(t.size||0),modifiedAt:t.date?.toISOString()||null,displayPath:String(t.displayPath||t.name),hasChildren:t.lazy===!0||!!t.data?.length,locked:t.locked===!0}}function bx(t){if(!Number.isFinite(t)||t<=0)return"0 B";const n=["B","KB","MB","GB","TB"];let r=t,s=0;for(;r>=1024&&s<n.length-1;)r/=1024,s+=1;return`${r.toFixed(s===0||r>=100?0:1)} ${n[s]}`}function th(t){return t.driveType==="network"?"network":t.driveType==="removable"?"removable":"local"}function gD(t){const n=t.filter(r=>th(r)==="local");return n.find(r=>/\bC:/i.test(`${r.name} ${r.displayPath||""}`))||n[0]||t[0]||null}function vD(t){const n=String(t.displayPath||"").trim();if(n)return n;const r=String(t.name||"").match(/\(([A-Za-z]:)\)/)?.[1];return r?`${r}\\`:t.name}function yD({hubUrl:t,roots:n,loading:r,error:s,onRefreshRoots:l,onImportFiles:u,onImportFolder:f,onSelectionChange:h,onShareItem:g,onAddSyncFolder:y,onNotice:w}){const b=d.useRef(null),S=d.useRef("/"),k=d.useRef(0),A=d.useRef([]),T=d.useRef(new Map),[j,I]=d.useState(null),[N,P]=d.useState([]),[H,F]=d.useState([]),[$,D]=d.useState(0),[K,z]=d.useState(null),[q,W]=d.useState(!1),[Y,V]=d.useState(""),[he,ee]=d.useState(new Set),U=n.find(ne=>ne.id===j)||null,L=N[N.length-1]||null,le=U?L?.svarPath||`/${U.name}`:null,ve=le;d.useEffect(()=>{A.current=N,S.current=ve||"/"},[ve,N]);const J=d.useMemo(()=>(T.current.clear(),!U||!ve||N.length===0?[]:(N.forEach(ne=>T.current.set(ne.svarPath,ne.hubId)),[...N.map((ne,me)=>({id:ne.svarPath,parent:me===0?"/":N[me-1].svarPath,type:"folder",name:ne.name,date:ne.modifiedAt?new Date(ne.modifiedAt):void 0,lazy:!1})),...H.map(ne=>{const me=`${ve}/${ne.name}`;return T.current.set(me,ne.id),{id:me,parent:ve,name:ne.name,type:ne.type==="file"?"file":"folder",...ne.type==="file"?{size:ne.size}:{},date:ne.modifiedAt?new Date(ne.modifiedAt):void 0,lazy:ne.type!=="file"&&ne.hasChildren===!0,displayPath:ne.displayPath,locked:ne.locked,driveType:ne.driveType,totalBytes:ne.totalBytes,freeBytes:ne.freeBytes}})])),[U,H,ve,N]),Ae=ne=>T.current.get(String(ne))||String(ne),ce=ne=>hD({...ne,id:Ae(String(ne.id)),parent:Ae(String(ne.parent))}),Te=async(ne,me)=>{const Ge=ne[ne.length-1];if(!Ge)return;const Se=++k.current;W(!0),V("");try{const ge=await Vg(Ge.hubId,t);if(Se!==k.current)return;if(!Array.isArray(ge.entries))throw new Error("Invalid Hub filesystem entries response.");const Ue={...Ge,displayPath:ge.folder.displayPath||Ge.displayPath,modifiedAt:ge.folder.modifiedAt||Ge.modifiedAt},Me=[...ne.slice(0,-1),Ue];A.current=Me,P(Me),F(ge.entries),D(rt=>rt+1)}catch(ge){if(Se!==k.current)return;console.error("[LiveDesk FS] folder navigation failed",{folderId:Ge.hubId,error:ge}),V(ge instanceof Error?`${me}: ${ge.message}`:`${me}: Unable to read this folder.`)}finally{Se===k.current&&W(!1)}},Fe=async ne=>{const me={svarPath:`/${ne.name}`,hubId:ne.id,name:ne.name,pathLabel:vD(ne),displayPath:ne.displayPath,modifiedAt:ne.modifiedAt},Ge=++k.current;I(ne.id),A.current=[me],P([me]),S.current=me.svarPath,F([]),V(""),W(!0),z(ne.id),ee(Se=>{const ge=new Set(Se);return ge.delete(ne.id),ge});try{const Se=await Vg(ne.id,t);if(Ge!==k.current)return;if(!Array.isArray(Se.entries))throw new Error("Invalid Hub filesystem entries response.");const ge={...me,pathLabel:Se.folder.displayPath||me.pathLabel,displayPath:Se.folder.displayPath||me.displayPath,modifiedAt:Se.folder.modifiedAt||me.modifiedAt};A.current=[ge],P([ge]),F(Se.entries),D(Ue=>Ue+1)}catch(Se){if(Ge!==k.current)return;console.error("[LiveDesk FS] getEntries failed",{rootId:ne.id,error:Se}),ee(ge=>new Set(ge).add(ne.id)),V(Se instanceof Error?`${ne.name}: ${Se.message}`:`${ne.name}: Unable to read this drive.`),w(Se instanceof Error?`${ne.name}: ${Se.message}`:`${ne.name}: Unable to read this drive.`)}finally{Ge===k.current&&(z(null),W(!1))}},$e=ne=>{const me=A.current;ne<0||ne>=me.length||ne===me.length-1||Te(me.slice(0,ne+1),me[ne].name)},Ze=(ne,me)=>{if(ne.type!=="folder")return;const Ge=A.current,Se=Ge.findIndex(Ue=>Ue.svarPath===me);if(Se<0)return;const ge={svarPath:`${me}/${ne.name}`,hubId:ne.id,name:ne.name,pathLabel:ne.name,displayPath:ne.displayPath,modifiedAt:ne.modifiedAt};Te([...Ge.slice(0,Se+1),ge],ne.name)},de=()=>$e(A.current.length-2),Be=ne=>{if(ne.key!=="Enter"&&ne.code!=="Enter"&&ne.code!=="NumpadEnter"||ne.target?.closest('button, input, textarea, [contenteditable="true"]'))return;const Ge=b.current;if(!Ge)return;const Se=Ge.getState().panels?.flatMap(Ue=>Ue.selected||[])||[];if(Se.length!==1)return;const ge=Ge.getFile(String(Se[0]));ge?.type==="folder"&&(ne.preventDefault(),ne.stopPropagation(),Ze(ce(ge),String(ge.parent||S.current)))};d.useEffect(()=>{const ne=n.find(me=>me.id===j)||gD(n);if(ee(me=>new Set([...me].filter(Ge=>n.some(Se=>Se.id===Ge)))),!ne){I(null),A.current=[],P([]),F([]);return}Fe(ne)},[n]);const Ve=ne=>{b.current=ne,ne.on("request-data",async({id:me})=>{const Ge=String(me),Se=Ae(Ge);try{const ge=await Vg(Se,t);if(!Array.isArray(ge.entries))throw new Error("Invalid Hub filesystem entries response.");const Ue=ge.entries.map(Me=>{const rt=`${Ge}/${Me.name}`;return T.current.set(rt,Me.id),{id:rt,parent:Ge,name:Me.name,type:Me.type==="file"?"file":"folder",...Me.type==="file"?{size:Me.size}:{},date:Me.modifiedAt?new Date(Me.modifiedAt):void 0,lazy:Me.type!=="file"&&Me.hasChildren===!0,displayPath:Me.displayPath,locked:Me.locked,driveType:Me.driveType,totalBytes:Me.totalBytes,freeBytes:Me.freeBytes}});await ne.exec("provide-data",{id:Ge,data:Ue})}catch(ge){console.error("[LiveDesk FS] nested getEntries failed",{id:Se,error:ge}),w(ge instanceof Error?ge.message:"Unable to read this folder.")}}),ne.intercept("set-path",({id:me})=>{const Ge=String(me),Se=A.current.findIndex(Ue=>Ue.svarPath===Ge);if(Se>=0)return $e(Se),!1;const ge=ne.getFile(Ge);if(ge?.type==="folder")return Ze(ce(ge),String(ge.parent||S.current)),!1}),ne.intercept("open-file",()=>!1),ne.on("select-file",()=>{window.setTimeout(()=>{const Se=(ne.getState().panels?.flatMap(ge=>ge.selected||[])||[]).map(ge=>ne.getFile(ge)).filter(Boolean).map(ge=>ce(ge));h(Se.map(ge=>ge.id),Se)},0)})},Je=(ne,me)=>{const Ge=me?ce(me):null,Se=()=>{const ge=Ge?.type==="file"?String(me?.parent||S.current):String(me?.id||S.current);b.current?.exec("request-data",{id:ge})};return ne==="body"?[{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Se},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>w("Select a file or folder to view its properties.")}]:ne==="multiselect"?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>{(b.current?.getState().panels?.flatMap(Ue=>Ue.selected||[])||[]).forEach(Ue=>{const Me=b.current?.getFile(Ue);Me&&g(ce(Me))})}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Se}]:Ge?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>g(Ge)},...Ge.type==="folder"?[{id:"sync",text:"Add folder to Sync",icon:"mdi mdi-folder-sync-outline",handler:()=>y(Ge)}]:[],{id:"copy-path",text:"Copy path",icon:"mdi mdi-content-copy",handler:()=>{Yp(Ge.displayPath||Ge.name)}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Se},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>w(`${Ge.name}
179
- ${Ge.displayPath||""}`)}]:[]},Qe=async()=>{try{await l()}catch(ne){w(ne instanceof Error?ne.message:"Unable to refresh Hub drives.")}},yt=[{id:"local",label:"Local drives",icon:fu,roots:n.filter(ne=>th(ne)==="local")},{id:"removable",label:"Removable drives",icon:Qk,roots:n.filter(ne=>th(ne)==="removable")},{id:"network",label:"Network drives",icon:Uv,roots:n.filter(ne=>th(ne)==="network")}];return o.jsxs("section",{className:"hub-file-explorer-panel","aria-label":"Hub file explorer",children:[o.jsxs("div",{className:"hub-file-explorer-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Hub file explorer"}),o.jsxs("strong",{children:[o.jsx(fu,{size:16})," Browse files on this Hub"]})]}),o.jsxs("div",{className:"hub-file-explorer-heading-actions",children:[o.jsx("button",{className:"icon-button",onClick:u,title:"Import files from this browser",type:"button",children:o.jsx(y0,{size:16})}),o.jsx("button",{className:"icon-button",onClick:f,title:"Import folder from this browser",type:"button",children:o.jsx(Yk,{size:16})}),o.jsx("button",{className:"icon-button",onClick:()=>{Qe()},title:"Refresh drives",type:"button",children:o.jsx(vu,{size:16})})]})]}),r?o.jsxs("div",{className:"hub-file-explorer-state",children:[o.jsx(fu,{size:24}),o.jsx("strong",{children:"Connecting to LiveDesk Hub file system..."})]}):s?o.jsxs("div",{className:"hub-file-explorer-state error",role:"alert",children:[o.jsx(el,{size:24}),o.jsx("strong",{children:s})]}):o.jsxs("div",{className:"hub-file-explorer-content",children:[o.jsxs("aside",{className:"hub-file-explorer-drive-sidebar","aria-label":"Hub drives",children:[o.jsxs("div",{className:"hub-drive-sidebar-title",children:[o.jsx(fu,{size:15}),o.jsx("strong",{children:"This PC"})]}),yt.map(ne=>ne.roots.length>0&&o.jsxs("section",{className:"hub-drive-group",children:[o.jsxs("h3",{children:[o.jsx(ne.icon,{size:13}),ne.label]}),o.jsx("div",{className:"hub-drive-list",children:ne.roots.map(me=>{const Ge=ne.icon,Se=he.has(me.id)||me.locked===!0;return o.jsxs("button",{className:`hub-drive-item ${j===me.id?"active":""} ${Se?"unavailable":""}`,onClick:()=>{Fe(me)},"aria-pressed":j===me.id,type:"button",children:[o.jsx("span",{className:"hub-drive-item-icon",children:o.jsx(Ge,{size:16})}),o.jsxs("span",{className:"hub-drive-item-copy",children:[o.jsx("strong",{children:me.name}),o.jsx("small",{children:me.displayPath||me.name}),o.jsxs("em",{children:[bx(me.freeBytes||0)," free / ",bx(me.totalBytes||0)]})]}),K===me.id?o.jsx(ps,{className:"hub-drive-item-status spin",size:15}):Se?o.jsx(Pb,{className:"hub-drive-item-status",size:15}):null]},me.id)})})]},ne.id)),n.length===0&&o.jsxs("div",{className:"hub-drive-sidebar-empty",children:[o.jsx(el,{size:17}),o.jsx("span",{children:"No drives available."})]})]}),o.jsxs("div",{className:"hub-file-explorer-browser",children:[o.jsxs("div",{className:"hub-file-explorer-navigation",children:[o.jsx("nav",{className:"hub-file-explorer-breadcrumbs","aria-label":"Current Hub folder",children:N.map((ne,me)=>o.jsxs("span",{className:"hub-file-explorer-breadcrumb-item",children:[me>0&&o.jsx(qv,{size:13,"aria-hidden":"true"}),o.jsx("button",{className:`hub-file-explorer-breadcrumb ${me===N.length-1?"current":""}`,onClick:()=>$e(me),title:ne.displayPath||ne.pathLabel,"data-hub-folder-id":ne.hubId,"aria-current":me===N.length-1?"location":void 0,type:"button",children:ne.pathLabel})]},ne.svarPath))}),o.jsxs("div",{className:"hub-file-explorer-navigation-actions",children:[q&&o.jsx(ps,{className:"hub-file-explorer-loading-icon spin",size:15,"aria-label":"Loading folder"}),o.jsx("button",{className:"icon-button",onClick:de,disabled:N.length<=1||q,title:"Back to parent folder",type:"button",children:o.jsx(d0,{size:16})})]})]}),Y&&o.jsxs("div",{className:"hub-file-explorer-folder-error",role:"alert",children:[o.jsx(Pb,{size:15}),o.jsx("span",{children:Y})]}),o.jsx("div",{className:"hub-file-explorer-svar",onKeyDownCapture:Be,children:o.jsx(aD,{fonts:!1,children:o.jsx(nD,{data:J,panels:le?[{path:le,selected:[]}]:void 0,readonly:!0,mode:"table",preview:!1,init:Ve,icons:"simple",menuOptions:Je},`${U?.id||"no-root"}:${$}`)})})]})]})]})}class bD extends d.Component{state={error:null};static getDerivedStateFromError(n){return{error:n}}componentDidCatch(n,r){console.error("[LiveDesk] Share Files runtime error",n,r.componentStack)}render(){return this.state.error?o.jsxs("section",{className:"file-share-error-boundary",role:"alert",children:[o.jsx(wh,{size:24}),o.jsx("strong",{children:"Share Files could not be opened."}),o.jsx("span",{children:this.state.error.message||"An unexpected file explorer error occurred."}),o.jsxs("button",{className:"text-button",onClick:this.props.onRetry,type:"button",children:[o.jsx(vu,{size:15})," Retry"]})]}):this.props.children}}function wD(t){return t.deviceName||t.hostname||t.deviceId}function xD({devices:t,mode:n,selectedIds:r,onModeChange:s,onToggle:l}){const u=new Set(r);return o.jsxs("section",{className:"distribution-targets",children:[o.jsxs("div",{className:"file-share-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Target"}),o.jsx("strong",{children:n==="all"?`${t.length} connected`:`${r.length} selected`})]}),o.jsxs("div",{className:"file-share-tabs compact","aria-label":"File transfer targets",children:[o.jsxs("button",{className:n==="all"?"active":"",onClick:()=>s("all"),type:"button",children:[o.jsx(pm,{size:14})," All connected"]}),o.jsxs("button",{className:n==="selected"?"active":"",onClick:()=>s("selected"),type:"button",children:[o.jsx(nr,{size:14})," Selected"]})]})]}),o.jsx("div",{className:"file-share-device-list","aria-label":"Connected Client targets",children:t.length===0?o.jsx("div",{className:"file-share-empty-inline",children:"No connected Clients."}):t.map(f=>{const h=n==="all"||u.has(f.deviceId);return o.jsxs("label",{className:`file-share-device-option ${h?"selected":""}`,children:[o.jsx("input",{type:"checkbox",checked:h,disabled:n==="all",onChange:()=>l(f.deviceId)}),o.jsx(nr,{size:20,"aria-hidden":"true"}),o.jsxs("span",{children:[o.jsx("strong",{children:wD(f)}),o.jsxs("small",{children:["Slot ",f.slotNumber?String(f.slotNumber).padStart(3,"0"):"-"," / ",f.platform||"unknown OS"]})]}),o.jsx(tr,{size:17,"aria-hidden":"true"})]},f.deviceId)})})]})}function SD(t){if(!Number.isFinite(t)||t<=0)return"0 B";const n=["B","KB","MB","GB","TB"];let r=t,s=0;for(;r>=1024&&s<n.length-1;)r/=1024,s+=1;return`${r.toFixed(s===0||r>=100?0:1)} ${n[s]}`}function CD({folders:t,loading:n,busy:r,canSync:s,onSyncAll:l,onSync:u,onToggleAuto:f,onRemove:h,onAdd:g}){return o.jsxs("section",{className:"file-share-sync-panel",children:[o.jsxs("div",{className:"file-share-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Hub folders"}),o.jsx("strong",{children:"Continuous sync"})]}),o.jsxs("button",{className:"text-button compact",onClick:l,disabled:r||!s||t.length===0,type:"button",children:[o.jsx(sm,{size:15})," ",r?"Syncing":"Sync all"]})]}),n?o.jsx("div",{className:"file-share-empty-state",children:"Loading Hub sync folders..."}):t.length===0?o.jsxs("button",{className:"file-share-empty-state interactive",onClick:g,type:"button",children:[o.jsx(sm,{size:28}),o.jsx("strong",{children:"Add a selected Hub folder"}),o.jsx("span",{children:"Hub keeps the manifest and can sync while this browser is closed."})]}):o.jsx("div",{className:"file-share-sync-list",children:t.map(y=>o.jsxs("article",{className:`file-share-sync-row state-${y.status}`,children:[o.jsx("div",{className:"file-share-sync-icon",children:o.jsx(sm,{size:19})}),o.jsxs("div",{className:"file-share-sync-info",children:[o.jsx("strong",{children:y.name}),o.jsx("span",{children:y.displayPath}),o.jsxs("small",{children:[y.fileCount," files / ",SD(y.totalBytes)," · ",y.lastSyncedAt?`Last sync ${L0(y.lastSyncedAt)} ago`:y.message||"Not synced yet"]})]}),o.jsxs("label",{className:"file-share-auto-sync",children:[o.jsx("input",{type:"checkbox",checked:y.autoSync,onChange:()=>f(y)}),o.jsx("span",{children:"Auto"})]}),o.jsxs("button",{className:"text-button compact",onClick:()=>u(y),disabled:r||!s||y.status==="syncing",type:"button",children:[o.jsx(vu,{size:14})," Sync now"]}),o.jsx("button",{className:"icon-button",onClick:()=>h(y),title:"Remove sync folder",type:"button",children:o.jsx(b0,{size:15})})]},y.id))})]})}function kD(t){const r=(t.targetMode==="all"?t.devices.map(s=>s.deviceId):t.selectedTargetIds).length>0;return o.jsxs("aside",{className:"file-share-distribution-panel",children:[o.jsxs("div",{className:"file-share-distribution-head",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Distribution"}),o.jsx("strong",{children:"Hub → Clients"})]}),o.jsx(fm,{size:18})]}),o.jsxs("div",{className:"file-share-tabs",role:"tablist","aria-label":"Distribution mode",children:[o.jsx("button",{className:t.tab==="send"?"active":"",onClick:()=>t.onTabChange("send"),role:"tab","aria-selected":t.tab==="send",type:"button",children:"Send"}),o.jsx("button",{className:t.tab==="sync"?"active":"",onClick:()=>t.onTabChange("sync"),role:"tab","aria-selected":t.tab==="sync",type:"button",children:"Sync"})]}),t.tab==="send"?o.jsxs(o.Fragment,{children:[o.jsx(xD,{devices:t.devices,mode:t.targetMode,selectedIds:t.selectedTargetIds,onModeChange:t.onTargetModeChange,onToggle:t.onTargetToggle}),o.jsxs("label",{className:"file-share-destination",children:[o.jsx("span",{children:"Destination folder"}),o.jsxs("div",{children:[o.jsx(Id,{size:15}),o.jsx("input",{value:t.remoteDirectory,onChange:s=>t.onRemoteDirectoryChange(s.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),o.jsx("small",{children:"Blank uses Desktop/LiveDeskFiles."})]}),o.jsxs("div",{className:"file-share-selection-summary",children:[o.jsx("span",{children:"Selected"}),o.jsx("strong",{children:t.selectedSummary})]}),o.jsxs("button",{className:"file-share-share-button",onClick:t.onShare,disabled:!t.canShare,type:"button",children:[o.jsx(fm,{size:17})," Share selected"]}),o.jsxs("button",{className:"file-share-secondary-button",onClick:t.onAddSync,disabled:!t.canAddSync,type:"button",children:[o.jsx(Id,{size:16})," Add selected folder to Sync"]})]}):o.jsx(CD,{folders:t.folders,loading:t.foldersLoading,busy:t.syncBusy,canSync:r,onSyncAll:t.onSyncAll,onSync:t.onSync,onToggleAuto:t.onToggleAuto,onRemove:t.onRemove,onAdd:t.onAddFolder})]})}function MD(t){if(!Number.isFinite(t)||t<=0)return"0 B";const n=["B","KB","MB","GB","TB"];let r=t,s=0;for(;r>=1024&&s<n.length-1;)r/=1024,s+=1;return`${r.toFixed(s===0||r>=100?0:1)} ${n[s]}`}function wx(t){if(t.state==="completed")return 100;const n=t.totalBytes>0?Math.round(t.sentBytes/t.totalBytes*100):t.totalFiles>0?Math.round(t.completedFiles/t.totalFiles*100):0;return Math.max(0,Math.min(Bv(t.state)?100:99,n))}function xx(t){return t.state==="scanning"?"Scanning selected Hub items":t.state==="queued"?"Preparing transfer":t.state==="sending"?`${t.completedFiles}/${t.totalFiles} · ${t.currentPath||"sending"}`:t.state==="completed"?`Sent ${t.totalFiles} file${t.totalFiles===1?"":"s"} to ${t.targetCount} Client${t.targetCount===1?"":"s"}`:t.state==="partially-failed"?`${t.failedTargets.length} Client${t.failedTargets.length===1?"":"s"} failed`:t.state==="cancelled"?"Transfer cancelled":t.error||"Transfer failed"}function Bv(t){return["completed","partially-failed","failed","cancelled"].includes(t)}function AD({hubUrl:t,devices:n,localFeatureAccess:r,upgradeNotice:s,remoteDirectory:l,onRemoteDirectoryChange:u,targetMode:f,selectedTargetIds:h,onTargetModeChange:g,onTargetToggle:y,filePickerRef:w,folderPickerRef:b,onBrowserFileImport:S,onBrowserFolderImport:k,onNotice:A,onTransferChange:T}){const j=Array.isArray(n)?n:[],[I,N]=d.useState([]),[P,H]=d.useState(!0),[F,$]=d.useState(""),[D,K]=d.useState([]),[z,q]=d.useState([]),[W,Y]=d.useState(null),[V,he]=d.useState(!1),[ee,U]=d.useState([]),[L,le]=d.useState(!0),[ve,J]=d.useState(!1),[Ae,ce]=d.useState("send"),[Te,Fe]=d.useState([]),$e=d.useRef(new Set),Ze=d.useRef(!1),de=d.useMemo(()=>f==="all"?j.map(O=>O.deviceId):h.filter(O=>j.some(qe=>qe.deviceId===O)),[j,h,f]),Be=Te.find(O=>!Bv(O.state)),Ve=z.length===1&&z[0].type==="folder"?z[0]:null,Je=z.length===0?"Select files or folders from the Hub explorer.":V?"Calculating selection size...":W?`${W.files} files, ${W.folders} folders · ${MD(W.totalBytes)}`:`${z.length} item${z.length===1?"":"s"} selected`,Qe=O=>{T({id:O.jobId,state:O.state,progress:wx(O),message:xx(O)})},yt=d.useCallback(async()=>{const O=await sD(t,!0);return N(O),$(""),O},[t]),ne=async()=>{if(!Ze.current){Ze.current=!0;try{const qe=(await lD(t,!0)).jobs||[],B=await Promise.all([...$e.current].map(async et=>{try{return await cD(et,t)}catch{return null}})),Oe=[...qe,...B.filter(Boolean)],We=[...new Map(Oe.map(et=>[et.jobId,et])).values()];Fe(We),We.forEach(Qe),We.filter(et=>Bv(et.state)).forEach(et=>$e.current.delete(et.jobId))}catch{}finally{Ze.current=!1}}};d.useEffect(()=>{let O=!0;H(!0),$(""),Promise.all([yt(),yx(t).then(B=>{O&&U(B)})]).catch(B=>{O&&($(B instanceof Error?"Hub file system is unavailable. Make sure LiveDesk Hub is running on this computer.":"Hub file system is unavailable."),A(B instanceof Error?B.message:"Hub file system is unavailable."))}).finally(()=>{O&&(H(!1),le(!1))}),ne();const qe=window.setInterval(()=>{ne()},800);return()=>{O=!1,window.clearInterval(qe)}},[t,yt]),d.useEffect(()=>{if(D.length===0){Y(null);return}let O=!1;return he(!0),iD(D,t).then(qe=>{O||Y(qe)}).catch(qe=>{O||A(qe instanceof Error?qe.message:"Unable to calculate selected size.")}).finally(()=>{O||he(!1)}),()=>{O=!0}},[t,D.join("|")]);const me=(O,qe)=>{K(O),q(qe)},Ge=O=>{O.forEach(qe=>$e.current.add(qe.jobId)),Fe(qe=>[...new Map([...qe,...O].map(B=>[B.jobId,B])).values()]),O.forEach(Qe)},Se=async()=>{if(!r){A(s);return}if(D.length===0){A("Select files or folders from the Hub explorer.");return}if(de.length===0){A("Choose at least one connected Client.");return}if(Be){A("A Hub transfer is already running.");return}try{const O=await oD(D,de,l.trim(),t);$e.current.add(O.jobId),A("Hub transfer queued."),await ne()}catch(O){A(O instanceof Error?O.message:"Unable to start Hub transfer.")}},ge=async O=>{const qe=O||Ve;if(!qe||qe.type!=="folder"){A("Select one folder to add it to Sync.");return}try{const B=await dD(qe.id,t);U(Oe=>[...Oe.filter(We=>We.id!==B.folder.id),B.folder]),ce("sync"),A(`${qe.name} is ready for Hub sync.`)}catch(B){A(B instanceof Error?B.message:"Unable to add the Hub folder to Sync.")}},Ue=async O=>{if(de.length===0){A("Choose at least one connected Client.");return}J(!0),U(qe=>qe.map(B=>B.id===O.id?{...B,status:"syncing"}:B));try{const qe=await pD(O.id,de,l.trim(),t);Ge(qe.jobs||[]),A(qe.jobs?.length?"Hub sync queued.":"No changed files to sync.");const B=await yx(t);U(B)}catch(qe){A(qe instanceof Error?qe.message:"Unable to sync the Hub folder."),U(B=>B.map(Oe=>Oe.id===O.id?{...Oe,status:"error",message:"Sync failed"}:Oe))}finally{J(!1)}},Me=async()=>{J(!0);try{for(const O of ee)await Ue(O)}finally{J(!1)}},rt=async O=>{try{const qe=await fD(O.id,{autoSync:!O.autoSync},t);U(B=>B.map(Oe=>Oe.id===O.id?qe.folder:Oe))}catch(qe){A(qe instanceof Error?qe.message:"Unable to update auto sync.")}},At=async O=>{try{await mD(O.id,t),U(qe=>qe.filter(B=>B.id!==O.id))}catch(qe){A(qe instanceof Error?qe.message:"Unable to remove the sync folder.")}};return o.jsxs("section",{className:"livedesk-file-explorer",children:[o.jsx("input",{ref:w,className:"hidden-file-input",type:"file",multiple:!0,onChange:O=>{O.currentTarget.files&&S(O.currentTarget.files),O.currentTarget.value=""}}),o.jsx("input",{ref:b,className:"hidden-file-input",type:"file",multiple:!0,webkitdirectory:"",directory:"",onChange:O=>{O.currentTarget.files&&k(O.currentTarget.files),O.currentTarget.value=""}}),o.jsx("div",{className:"file-share-workspace",children:o.jsxs(bD,{onRetry:()=>window.location.reload(),children:[o.jsx(yD,{hubUrl:t,roots:I,loading:P,error:F,onRefreshRoots:yt,onImportFiles:()=>w.current?.click(),onImportFolder:()=>b.current?.click(),onSelectionChange:me,onShareItem:O=>{K([O.id]),q([O]),ce("send")},onAddSyncFolder:O=>{K([O.id]),q([O]),ge(O)},onNotice:A}),o.jsx(kD,{devices:j,targetMode:f,selectedTargetIds:h,onTargetModeChange:g,onTargetToggle:y,remoteDirectory:l,onRemoteDirectoryChange:u,selectedEntries:z,selectedSummary:Je,canShare:r&&!Be&&D.length>0&&de.length>0&&!V,onShare:()=>{Se()},canAddSync:!!Ve,onAddSync:()=>{ge()},tab:Ae,onTabChange:ce,folders:ee,foldersLoading:L,syncBusy:ve,onSyncAll:()=>{Me()},onSync:O=>{Ue(O)},onToggleAuto:O=>{rt(O)},onRemove:O=>{At(O)},onAddFolder:()=>{ge()}})]})}),Be&&o.jsx("footer",{className:"file-share-workspace-footer",children:o.jsxs("span",{children:[xx(Be)," · ",wx(Be),"% ",o.jsx("button",{className:"icon-button",onClick:()=>{uD(Be.jobId,t).then(O=>{Fe(qe=>qe.map(B=>B.jobId===O.jobId?O:B)),Qe(O)})},title:"Cancel transfer",type:"button",children:o.jsx(vr,{size:14})})]})})]})}const TD=d.forwardRef(function({value:n,onChange:r,onSubmit:s,onOpenSuggestedTasks:l,suggestedOpen:u=!1,suggestedTaskCount:f,disabled:h=!1,placeholder:g="Ask LiveDesk to work across your machines...",compact:y=!1},w){return o.jsxs("form",{className:"agents-composer",onSubmit:b=>{b.preventDefault(),s()},children:[o.jsx("button",{className:`agents-suggested-trigger ${u?"active":""}`,type:"button","aria-label":f===void 0?"Open Suggested tasks":`Open Suggested tasks (${f} available)`,"aria-expanded":u,onClick:l,disabled:h,children:o.jsx(Xk,{size:17})}),o.jsx("textarea",{ref:w,value:n,onChange:b=>r(b.target.value.slice(0,4e3)),placeholder:g,"aria-label":"Ask LiveDesk",rows:y?1:2,disabled:h}),o.jsxs("button",{className:"agents-run-button",type:"submit",disabled:h||!n.trim(),children:[h?o.jsx(ps,{className:"spin",size:16}):o.jsx(fm,{size:16}),h?"Running":"Run"]})]})}),ND=["read","processControl","serviceControl","applicationControl","fileRead","fileWrite","fileDelete","shell","script","softwareInstall","network","systemPower","systemConfiguration","userAccount"];function gh(t){return t.deviceName?.trim()||t.hostname?.trim()||t.deviceId}function vh(t){return t.connected!==!0?!1:t.synthetic===!0?!0:!t.channels||t.channels.control===!0}function RD(t){return t==="running"||t==="completed"||t==="failed"||t==="cancelled"?t:"queued"}function ED(t){switch(t){case"process.list":return"Process list";case"system.health":return"System health";case"gpu.status":return"GPU status";case"disk.status":return"Disk status";case"service.status":return"Service status";case"diagnostics.collect":return"Diagnostics";case"process.control":return"Process control";case"service.control":return"Service control";case"application.launch":return"Launch application";case"application.close":return"Close application";case"file.read":return"Read file";case"file.write":return"Write file";case"file.delete":return"Delete file";case"file.list":return"List directory";case"command.run":return"Run command";case"script.run":return"Run script";case"software.install":return"Install software";case"network.status":return"Network status";case"system.power":return"Power action";case"system.configure":return"System configuration";case"logs.collect":return"Collect logs"}}function jD(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function ms(t){return typeof t=="number"&&Number.isFinite(t)?t:null}function Bp(t){const n=ms(t);return n===null?"":n<1024**2?`${Math.round(n/1024)}K`:n<1024**3?`${(n/1024**2).toFixed(0)}M`:`${(n/1024**3).toFixed(1)}G`}function Sx(t){const n=ms(t);return n===null?"":`${Math.round((n<=1?n:n/100)*100)}%`}function DD(t){return!t||/^(?:[\w .-]+ )?collected(?:\.)?$/i.test(t.trim())?"":t.trim()}function yh(t,n){if(n.error)return n.error;const r=jD(n.data),s=DD(n.result||"");if(!r)return s||n.stage||n.status;if(t==="system.health"){const l=typeof r.machine=="string"?r.machine:"",u=Sx(r.cpuUsageRatio),f=ms(r.cores),h=Bp(r.freeMemoryBytes),g=Bp(r.totalMemoryBytes),y=ms(r.totalMemoryBytes)&&ms(r.freeMemoryBytes)!==null?`${Math.round(ms(r.freeMemoryBytes)/ms(r.totalMemoryBytes)*100)}% RAM free`:"";return[l,u&&`CPU ${u}`,f!==null&&`${Math.round(f)} cores`,h&&g?`RAM ${h}/${g}`:"",y,typeof r.platform=="string"?r.platform:""].filter(Boolean).join(" · ")||s||n.status}if(t==="disk.status"){const l=typeof r.root=="string"?r.root:"",u=Bp(r.freeBytes),f=ms(r.totalBytes)&&ms(r.freeBytes)!==null?`${Math.round(ms(r.freeBytes)/ms(r.totalBytes)*100)}% free`:"";return[l,u&&`${u} free`,f].filter(Boolean).join(" · ")||s||n.status}if(t==="gpu.status"){const l=typeof r.name=="string"&&r.name?r.name:"No GPU detected",u=Sx(r.usageRatio),f=ms(r.temperatureC)!==null?`${Math.round(ms(r.temperatureC))}°C`:"",h=Bp(r.freeMemoryBytes);return[l,u&&`GPU ${u}`,f,h&&`${h} free`].filter(Boolean).join(" · ")||s||n.status}if(t==="process.list"){const l=ms(r.count);return l!==null?`${l} matching process${l===1?"":"es"}`:s||n.status}if(t==="network.status"){const l=Array.isArray(r.adapters)?r.adapters.length:null;return l!==null?`${l} active adapter${l===1?"":"s"}`:s||n.status}return s||n.stage||n.status}function Cx(t,n){const r=yh(t,n);return n.status==="failed"||n.status==="cancelled"||/\b(?:warning|failed|error|offline|not running|low|timeout|timed out)\b/i.test(`${n.result||""} ${r}`)}function ID({state:t,operation:n}){const r=t.status==="completed"?tl:t.status==="failed"||t.status==="cancelled"?vr:t.status==="running"?ps:w0,s=t.status==="running"?t.stage||"Working":t.status==="completed"?n?yh(n,t):t.result||"Completed":t.status==="failed"?t.error||"Failed":t.status==="cancelled"?"Cancelled":"Queued";return o.jsxs("div",{className:`agent-target-row status-${t.status}`,"data-agent-target-id":t.deviceId,children:[o.jsx("span",{className:"agent-target-status","aria-hidden":"true",children:o.jsx(r,{size:15})}),o.jsx("strong",{children:t.deviceName}),o.jsx("span",{className:"agent-target-state",children:t.status[0].toUpperCase()+t.status.slice(1)}),o.jsx("small",{children:s})]})}function LD({operation:t,states:n,status:r,onCancel:s,onRetry:l,busy:u=!1}){const f=["running","queued"].includes(r),[h,g]=d.useState(!1),[y,w]=d.useState("all"),b=d.useMemo(()=>({total:n.length,completed:n.filter(P=>P.status==="completed").length,failed:n.filter(P=>P.status==="failed").length,running:n.filter(P=>P.status==="running").length,queued:n.filter(P=>P.status==="queued").length,cancelled:n.filter(P=>P.status==="cancelled").length}),[n]),S=n.filter(P=>Cx(t,P)),k=S.filter(P=>P.status==="completed").length,A=b.failed>0,T=S.length>0,j=n.filter(P=>y==="issues"?Cx(t,P):y==="running"?P.status==="running"||P.status==="queued":y==="completed"?P.status==="completed":y==="failed"?P.status==="failed":!0),I=T&&!f||r==="completed-with-failures"?"Completed with issues":r[0]?.toUpperCase()+r.slice(1),N=n.filter(P=>P.status==="completed").map(P=>yh(t,P)).filter(Boolean).filter((P,H,F)=>F.indexOf(P)===H).slice(0,2);return o.jsxs("section",{className:"agent-task-block","aria-label":"Task execution",children:[o.jsxs("div",{className:"agent-task-head",children:[o.jsxs("div",{children:[o.jsx("span",{children:"LiveDesk Agent"}),o.jsx("strong",{children:ED(t)})]}),o.jsx("span",{className:`agent-task-status status-${T?"completed-with-failures":r}`,children:I})]}),o.jsxs("div",{className:"agent-task-summary","aria-label":"Task summary",children:[o.jsxs("strong",{children:[b.total," targets"]}),o.jsxs("span",{className:"summary-completed",children:[b.completed," completed"]}),b.running>0&&o.jsxs("span",{className:"summary-running",children:[b.running," running"]}),b.queued>0&&o.jsxs("span",{children:[b.queued," queued"]}),A&&o.jsxs("span",{className:"summary-failed",children:[b.failed," failed"]}),k>0&&o.jsxs("span",{className:"summary-cancelled",children:[k," warning"]}),b.cancelled>0&&o.jsxs("span",{className:"summary-cancelled",children:[b.cancelled," cancelled"]})]}),N.length>0&&o.jsxs("div",{className:"agent-task-result-preview",title:N.join(" · "),children:[o.jsx("span",{children:"Result"}),N.join(" · ")]}),o.jsx("div",{className:"agent-target-chips","aria-label":"Target status overview",children:n.map((P,H)=>{const F=P.status==="completed"?"✓":P.status==="failed"?"×":P.status==="cancelled"?"!":P.status==="running"?"…":"·";return o.jsxs("span",{className:`agent-target-chip status-${P.status}`,title:`${P.deviceName}: ${yh(t,P)}`,"aria-label":`${H+1}. ${P.deviceName}: ${P.status}`,children:[o.jsx("b",{children:String(H+1).padStart(2,"0")}),o.jsx("span",{children:F})]},P.deviceId)})}),n.length>0&&o.jsx("div",{className:"agent-task-details-toggle",children:o.jsxs("button",{type:"button",onClick:()=>g(P=>!P),"aria-expanded":h,children:[h?o.jsx(Zk,{size:14}):o.jsx(x0,{size:14}),h?"Hide details":"Show details"]})}),h&&o.jsxs("div",{className:"agent-task-details",children:[o.jsx("div",{className:"agent-task-filters",role:"tablist","aria-label":"Task result filter",children:["all","issues","running","completed","failed"].map(P=>o.jsx("button",{className:y===P?"active":"",onClick:()=>w(P),role:"tab","aria-selected":y===P,type:"button",children:P==="all"?"All":P==="issues"?"Issues only":P[0].toUpperCase()+P.slice(1)},P))}),o.jsx("div",{className:"agent-task-rows",children:j.length>0?j.map(P=>o.jsx(ID,{operation:t,state:P},P.deviceId)):o.jsx("small",{className:"agent-task-no-results",children:"No targets match this filter."})})]}),(f||A)&&o.jsxs("div",{className:"agent-task-actions",children:[f&&s&&o.jsxs("button",{onClick:s,disabled:u,type:"button",children:[o.jsx(Jk,{size:14})," Cancel"]}),!f&&A&&l&&o.jsxs("button",{onClick:l,disabled:u,type:"button",children:[o.jsx(dv,{size:14})," Retry failed"]})]})]})}function PD(t){try{return JSON.stringify(t,null,2).slice(0,6e3)}catch{return"{}"}}function _D({approval:t,busy:n=!1,onApprove:r,onReject:s}){return o.jsxs("article",{className:"agent-approval-card","aria-label":"Agent approval required",children:[o.jsxs("div",{className:"agent-approval-head",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Approval required"}),o.jsx("strong",{children:t.toolName})]}),o.jsx("span",{className:`agent-approval-risk risk-${t.risk}`,children:t.risk})]}),o.jsx("p",{children:t.description}),o.jsx("pre",{children:PD(t.arguments)}),o.jsxs("small",{children:["Permission: ",t.permissionMode," · Scope: selected devices only · Expires in 5 minutes"]}),o.jsxs("div",{className:"agent-approval-actions",children:[o.jsxs("button",{className:"reject",disabled:n,onClick:s,type:"button",children:[o.jsx(vr,{size:14})," Reject"]}),o.jsxs("button",{disabled:n,onClick:()=>r("once"),type:"button",children:[o.jsx(tl,{size:14})," Once"]}),o.jsx("button",{disabled:n,onClick:()=>r("same-action-this-run"),type:"button",children:"Allow same action"}),o.jsx("button",{disabled:n,onClick:()=>r("category-this-run"),type:"button",children:"Allow category"})]}),o.jsxs("div",{className:"agent-approval-scope",children:[o.jsx(wh,{size:13})," Approval is bound to this run, tool, arguments, selected devices, and policy hash."]})]})}function OD(t){return t==="queued"?"Request queued":t==="checking-codex"?"Checking Codex":t==="preparing-tools"?"Preparing tools":t==="thinking"?"Preparing answer":t==="tool-running"?"Working on computers":t==="recovering"?"Retrying safely":t==="waiting-approval"?"Waiting for approval":"Working"}function FD({items:t,onCancel:n,onRetry:r,busyBatchId:s,approvals:l,onApprove:u,onReject:f,busyApprovalId:h,progress:g,emptyTitle:y="Ask LiveDesk to work across your machines.",emptyBody:w="Start with a read-only request such as “현재 대상에서 CPU와 메모리 상태를 확인해줘”."}){const b=d.useRef(null),S=d.useRef(!0),k=d.useRef(""),A=t[t.length-1];return d.useLayoutEffect(()=>{const T=b.current;T&&(A?.type==="user"&&A.id!==k.current&&(S.current=!0),k.current=A?.id||"",S.current&&(T.scrollTop=T.scrollHeight))},[l,t,A?.id,A?.type,g?.message,g?.stage]),o.jsxs("section",{className:"agents-conversation","aria-live":"polite",ref:b,onScroll:T=>{const j=T.currentTarget;S.current=j.scrollHeight-j.scrollTop-j.clientHeight<72},children:[l.filter(T=>T.status==="pending").map(T=>o.jsx(_D,{approval:T,busy:h===T.approvalId,onApprove:j=>u(T,j),onReject:()=>f(T)},T.approvalId)),t.length===0&&o.jsxs("div",{className:"agents-empty-conversation",children:[o.jsx("strong",{children:y}),o.jsx("span",{children:w})]}),t.map(T=>{if(T.type==="task"){const j=T;return o.jsx(LD,{operation:j.operation,states:j.states,status:j.status,onCancel:()=>n(j.batchId,j.agentRunId),onRetry:()=>r(j.batchId),busy:s===j.batchId},j.id)}return o.jsxs("article",{className:`agents-message ${T.type}`,children:[o.jsx("span",{children:T.type==="user"?"You":"LiveDesk Agent"}),o.jsx("p",{children:T.text})]},T.id)}),g&&o.jsxs("article",{className:"agents-message agent agents-progress-message",role:"status",children:[o.jsxs("span",{children:[o.jsx(ps,{"aria-hidden":"true",size:15}),OD(g.stage)]}),o.jsx("p",{children:g.message})]})]})}const kx=["Recommended","Health & capacity","Processes & services","Files & configuration","Software & automation","Network & connectivity","Power & maintenance","Troubleshooting & recovery"],pa=["windows","macos","linux"],ic={"system.health":{label:"system health",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:pa},"gpu.status":{label:"GPU status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:pa},"disk.status":{label:"disk status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:pa},"process.list":{label:"process inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:pa},"service.status":{label:"service inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:pa},"diagnostics.collect":{label:"diagnostics collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:pa},"process.control":{label:"process control",permissionCategory:"processControl",readOnly:!1,risk:"high",supportedPlatforms:pa},"service.control":{label:"service control",permissionCategory:"serviceControl",readOnly:!1,risk:"high",supportedPlatforms:["windows","linux"]},"application.launch":{label:"application launch",permissionCategory:"applicationControl",readOnly:!1,risk:"medium",supportedPlatforms:pa},"application.close":{label:"application close",permissionCategory:"applicationControl",readOnly:!1,risk:"medium",supportedPlatforms:pa},"file.read":{label:"file reading",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:pa},"file.write":{label:"file writing",permissionCategory:"fileWrite",readOnly:!1,risk:"high",supportedPlatforms:pa},"file.delete":{label:"file deletion",permissionCategory:"fileDelete",readOnly:!1,risk:"critical",supportedPlatforms:pa},"file.list":{label:"directory listing",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:pa},"command.run":{label:"command execution",permissionCategory:"shell",readOnly:!1,risk:"critical",supportedPlatforms:pa},"script.run":{label:"script execution",permissionCategory:"script",readOnly:!1,risk:"high",supportedPlatforms:pa},"software.install":{label:"software installation",permissionCategory:"softwareInstall",readOnly:!1,risk:"high",supportedPlatforms:pa},"network.status":{label:"network inspection",permissionCategory:"network",readOnly:!0,risk:"low",supportedPlatforms:pa},"system.power":{label:"power control",permissionCategory:"systemPower",readOnly:!1,risk:"critical",supportedPlatforms:pa},"system.configure":{label:"system configuration",permissionCategory:"systemConfiguration",readOnly:!1,risk:"critical",supportedPlatforms:pa},"logs.collect":{label:"log collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:pa}};new Set(Object.keys(ic));const BD={Recommended:["recommended","overview","fleet","요약","추천"],"Health & capacity":["health","capacity","performance","상태","성능","용량"],"Processes & services":["process","service","application","프로세스","서비스","앱"],"Files & configuration":["file","config","directory","파일","설정","폴더"],"Software & automation":["software","install","automation","프로그램","설치","자동화"],"Network & connectivity":["network","connection","adapter","네트워크","연결","어댑터"],"Power & maintenance":["power","maintenance","restart","전원","유지보수","재시작"],"Troubleshooting & recovery":["troubleshooting","recovery","incident","문제해결","복구","장애"]},Mx=["low","medium","high","critical"];function HD(t){return t.reduce((n,r)=>{const s=ic[r].risk;return Mx.indexOf(s)>Mx.indexOf(n)?s:n},"low")}function zD(t){return pa.filter(n=>t.every(r=>ic[r].supportedPlatforms.includes(n)))}function ht(t,n,r,s,l,u,f={}){const h=f.description||s,g=l.flatMap(w=>w.split(".")),y=[...new Set([...BD[n],...u,...g])];return{id:t,category:n,title:r,prompt:s,description:h,requiredOperations:l,risk:f.risk||HD(l),targetSupport:f.targetSupport||"single-or-multiple",supportedPlatforms:f.supportedPlatforms||zD(l),keywords:y,recommended:f.recommended??!1,enabled:!0}}const cC=[ht("recommended-fleet-health","Recommended","Summarize current target health","Summarize system health, GPU, and disk capacity for the current target Clients.",["system.health","gpu.status","disk.status"],["summary","overview"],{recommended:!0}),ht("recommended-attention","Recommended","Find targets needing attention","Identify current targets with high resource use, low disk space, or service warnings.",["system.health","disk.status","service.status"],["attention","warning","monitor"],{recommended:!0}),ht("recommended-performance-compare","Recommended","Compare selected performance","Compare CPU, memory, disk, and GPU capacity across the current targets.",["system.health","disk.status","gpu.status"],["compare","benchmark"],{recommended:!0}),ht("recommended-gpu-vram","Recommended","Review GPU and VRAM availability","Show GPU temperature, utilization, and VRAM availability for the current targets.",["gpu.status"],["graphics","temperature","utilization"],{recommended:!0}),ht("recommended-low-disk","Recommended","Locate low disk capacity","Find current targets with low free disk capacity and report the affected volumes.",["disk.status"],["storage","free space","capacity"],{recommended:!0}),ht("recommended-process-services","Recommended","Review processes and services","Review running processes and service state for warnings on the current targets.",["process.list","service.status"],["process","service","warning"],{recommended:!0}),ht("recommended-recover-application","Recommended","Recover a stopped application","Check a named application or service, relaunch its registered entry when stopped, and verify the result.",["process.list","application.launch","service.status"],["recover","start","application"],{targetSupport:"single",recommended:!0}),ht("recommended-incident-diagnostics","Recommended","Collect an incident diagnostic bundle","Collect health, service, network, and recent log diagnostics for the current targets.",["diagnostics.collect","logs.collect","system.health","network.status"],["incident","report","evidence"],{recommended:!0}),ht("health-cpu-memory","Health & capacity","Check high CPU and memory use","Find current targets with unusually high CPU or memory usage.",["system.health"],["cpu","memory","load","높은 사용량"]),ht("health-uptime","Health & capacity","Review Client uptime","Show uptime, boot time, and current system health for the target Clients.",["system.health"],["uptime","boot","가동시간"]),ht("health-gpu-temperature","Health & capacity","Check GPU temperature","Check GPU temperature and thermal warnings on the current targets.",["gpu.status"],["thermal","temperature","발열"]),ht("health-vram-usage","Health & capacity","Check VRAM usage","Report GPU memory usage and remaining VRAM on the current targets.",["gpu.status"],["vram","gpu memory","video memory"]),ht("health-low-disk","Health & capacity","Find low disk space","Find volumes below a safe free-space threshold on the current targets.",["disk.status"],["disk","storage","free space","디스크"]),ht("health-gpu-compare","Health & capacity","Compare GPU capacity","Compare GPU model, memory, temperature, and utilization across the current targets.",["gpu.status"],["compare","graphics","capacity"]),ht("health-system-warnings","Health & capacity","Collect system warnings","Review health, disk, and network status for warnings that need attention.",["system.health","disk.status","network.status"],["warnings","alerts","경고"]),ht("health-capacity-report","Health & capacity","Build a capacity report","Create a concise capacity report covering CPU, memory, GPU, disk, and network status.",["system.health","gpu.status","disk.status","network.status"],["report","capacity","inventory"]),ht("process-find-name","Processes & services","Find a running process by name","Find process named [process name] on the current targets.",["process.list"],["find","running","name","실행 중"]),ht("process-resource-heavy","Processes & services","Find resource-heavy processes","List the processes using the most CPU or memory on the current targets.",["process.list","system.health"],["top","cpu","memory","resource"]),ht("process-stop-named","Processes & services","Stop a named process","Stop process named [process name] on the target Client after checking its current state.",["process.list","process.control"],["stop","terminate","종료"],{targetSupport:"single"}),ht("process-restart-named","Processes & services","Restart a named process","Check process named [process name] and restart it with its registered launch details when available.",["process.list","process.control"],["restart","relaunch","재시작"],{targetSupport:"single"}),ht("process-launch-app","Processes & services","Launch a registered application","Launch the registered application [application] on the target Client with [arguments].",["application.launch"],["launch","open","실행"],{targetSupport:"single"}),ht("process-close-app","Processes & services","Close an application","Close application [application] on the target Client and report whether it exited cleanly.",["application.close","process.list"],["close","exit","앱 종료"],{targetSupport:"single"}),ht("service-status-name","Processes & services","Check a service status","Check service [service name] and report its state on the current targets.",["service.status"],["service","status","서비스 상태"]),ht("service-restart-name","Processes & services","Restart a service safely","Check service [service name], stop it, wait for it to stop, then start it and verify the result.",["service.status","service.control"],["restart","start","stop","서비스 재시작"],{targetSupport:"single"}),ht("files-list-directory","Files & configuration","List a directory","List files and folders under [path] on the target Client.",["file.list"],["directory","folder","list","목록"],{targetSupport:"single"}),ht("files-read-config","Files & configuration","Read a configuration file","Read the relevant settings from configuration file [path] on the target Client.",["file.read"],["config","settings","read","구성"]),ht("files-recent-logs","Files & configuration","Find recent log files","List recent log files under [path] and summarize the latest entries.",["file.list","file.read"],["logs","recent","tail"]),ht("files-update-config","Files & configuration","Update a configuration value","Read configuration file [path], update [change], and report the exact change made.",["file.read","file.write"],["edit","update","설정 변경"],{targetSupport:"single"}),ht("files-delete-temp","Files & configuration","Delete temporary files","Find temporary files under [path], delete only the requested matches, and report the freed space.",["file.list","file.delete","disk.status"],["cleanup","temp","delete","정리"],{targetSupport:"single"}),ht("files-compare-config","Files & configuration","Compare configuration files","Read configuration file [path] on the target Client and compare it with [reference path].",["file.read"],["compare","diff","configuration"]),ht("files-set-environment","Files & configuration","Set an environment variable","Set environment variable [name] to [value] for the target Client and verify the resulting configuration.",["system.configure","file.read"],["environment","variable","env","환경변수"],{targetSupport:"single"}),ht("files-archive-diagnostics","Files & configuration","Write a diagnostic manifest","Collect selected diagnostics and write a manifest file to [path] on the target Client.",["diagnostics.collect","file.write"],["manifest","export","diagnostic file"],{targetSupport:"single"}),ht("software-winget-install","Software & automation","Install software with winget","Install package [package name] with winget on the Windows target Client, then verify it.",["software.install","process.list"],["winget","windows","install","설치"],{targetSupport:"single",supportedPlatforms:["windows"]}),ht("software-apt-install","Software & automation","Install software with apt","Install package [package name] with apt on the Linux target Client, then verify it.",["software.install","process.list"],["apt","linux","package","설치"],{targetSupport:"single",supportedPlatforms:["linux"]}),ht("software-brew-install","Software & automation","Install software with Homebrew","Install package [package name] with brew on the macOS target Client, then verify it.",["software.install","process.list"],["brew","homebrew","macos","설치"],{targetSupport:"single",supportedPlatforms:["macos"]}),ht("software-npm-install","Software & automation","Install an npm package","Install npm package [package name] on the target Client and verify the installed version.",["software.install","command.run"],["npm","node","package"],{targetSupport:"single"}),ht("software-run-script","Software & automation","Run a registered script","Run the registered script [script path] on the target Client and report its result.",["script.run"],["script","automation","registered"],{targetSupport:"single"}),ht("software-run-command","Software & automation","Run a command on one target","Run command [command] on the target Client and return its exit status and output.",["command.run"],["command","shell","terminal"],{targetSupport:"single"}),ht("software-verify-install","Software & automation","Verify an installed tool","Check whether [application] is installed, running, and available on the PATH of the current targets.",["process.list","system.health"],["verify","installed","path"]),ht("software-toolchain-setup","Software & automation","Set up a toolchain","Install the requested package [package name], configure [change], and verify the toolchain on the target Client.",["software.install","system.configure","process.list"],["toolchain","setup","developer"],{targetSupport:"single"}),ht("network-adapter-status","Network & connectivity","Check network adapters","Show adapter state, address, and link information for the current targets.",["network.status"],["adapter","ethernet","wifi","네트워크 상태"]),ht("network-disconnected","Network & connectivity","Find disconnected targets","Find current targets with disconnected or degraded network adapters.",["network.status"],["disconnected","offline","연결 끊김"]),ht("network-link-speed","Network & connectivity","Check link speed","Report network link speed and duplex information for the current targets.",["network.status"],["speed","bandwidth","duplex"]),ht("network-warnings","Network & connectivity","Review network warnings","Review network status and recent logs for connectivity warnings on the current targets.",["network.status","logs.collect"],["warning","latency","packet loss"]),ht("network-diagnostics","Network & connectivity","Collect network diagnostics","Collect network status, system diagnostics, and relevant logs for the current targets.",["network.status","diagnostics.collect","logs.collect"],["diagnostics","incident","connectivity"]),ht("network-service-failures","Network & connectivity","Find network service failures","Check network status and relevant service states on the current targets.",["network.status","service.status"],["service","failure","dns"]),ht("network-compare","Network & connectivity","Compare target connectivity","Compare adapter state, addresses, and link speed across the current targets.",["network.status"],["compare","inventory","connectivity"]),ht("network-intermittent","Network & connectivity","Investigate intermittent connectivity","Investigate intermittent connectivity using network status, service state, and diagnostics evidence.",["network.status","service.status","diagnostics.collect"],["intermittent","unstable","recovery"]),ht("power-lock","Power & maintenance","Lock the Client","Lock the target Client and report the resulting power action status.",["system.power"],["lock","security","잠금"],{targetSupport:"single",risk:"critical"}),ht("power-logoff","Power & maintenance","Log off the Client","Log off the target Client after warning that interactive sessions will close.",["system.power"],["logoff","session","로그오프"],{targetSupport:"single",risk:"critical"}),ht("power-sleep","Power & maintenance","Put the Client to sleep","Put the target Client to sleep after confirming the requested delay of [delay].",["system.power"],["sleep","suspend","절전"],{targetSupport:"single",risk:"critical"}),ht("power-restart","Power & maintenance","Restart the Client","Restart the target Client after confirming that active work may be interrupted.",["system.power"],["restart","reboot","재부팅"],{targetSupport:"single",risk:"critical"}),ht("power-shutdown","Power & maintenance","Shut down the Client","Shut down the target Client after confirming that active work may be interrupted.",["system.power"],["shutdown","power off","종료"],{targetSupport:"single",risk:"critical"}),ht("power-maintenance-restart","Power & maintenance","Restart after maintenance","Check the target Client, restart it after maintenance, and verify that it returns online.",["system.health","system.power","network.status"],["maintenance","reboot","verify"],{targetSupport:"single",risk:"critical"}),ht("power-timezone","Power & maintenance","Set the Client timezone","Set the target Client timezone to [timezone] and verify the resulting system configuration.",["system.configure"],["timezone","clock","시간대"],{targetSupport:"single",risk:"critical"}),ht("power-persistent-environment","Power & maintenance","Persist an environment variable","Persist environment variable [name] with value [value] for the target Client and verify it.",["system.configure"],["environment","persistent","환경변수"],{targetSupport:"single",risk:"critical"}),ht("recovery-app-wont-start","Troubleshooting & recovery","Investigate an app that will not start","Inspect [application], review its logs, launch the registered application, and verify the process.",["process.list","application.launch","logs.collect"],["app failure","start","실행 오류"],{targetSupport:"single"}),ht("recovery-failed-service","Troubleshooting & recovery","Recover a failed service","Inspect service [service name], collect logs, restart it safely, and verify its running state.",["service.status","logs.collect","service.control"],["service failure","recover","서비스 복구"],{targetSupport:"single"}),ht("recovery-repeated-process","Troubleshooting & recovery","Investigate a repeatedly stopping process","Inspect process [process name], collect diagnostics, stop stale instances, and relaunch the registered process.",["process.list","diagnostics.collect","process.control","application.launch"],["crash loop","process","반복 종료"],{targetSupport:"single"}),ht("recovery-low-disk","Troubleshooting & recovery","Recover from low disk space","Inspect disk capacity, find temporary files, remove only the requested files, and verify free space.",["disk.status","file.list","file.delete"],["disk full","cleanup","저장공간 부족"],{targetSupport:"single"}),ht("recovery-gpu-overheating","Troubleshooting & recovery","Investigate GPU overheating","Inspect GPU temperature and processes, then close the specified workload if it is causing the thermal warning.",["gpu.status","process.list","application.close"],["overheating","thermal","GPU 발열"],{targetSupport:"single"}),ht("recovery-high-vram","Troubleshooting & recovery","Recover high VRAM usage","Inspect VRAM usage and GPU processes, then stop the specified stale workload if necessary.",["gpu.status","process.list","process.control"],["vram","memory pressure","VRAM 부족"],{targetSupport:"single"}),ht("recovery-network-instability","Troubleshooting & recovery","Recover network instability","Collect network diagnostics, inspect network services, and report the safest recovery action for the target Client.",["network.status","service.status","diagnostics.collect"],["network","unstable","네트워크 복구"],{targetSupport:"single"}),ht("recovery-incident-report","Troubleshooting & recovery","Create a full incident report","Create a full incident report from health, process, service, network, and log evidence for the current targets.",["system.health","process.list","service.status","network.status","logs.collect"],["incident","report","장애 보고서"])],Kg={read:"allow",processControl:"allow",serviceControl:"allow",applicationControl:"ask",fileRead:"allow",fileWrite:"allow",fileDelete:"ask",shell:"ask",script:"ask",softwareInstall:"ask",network:"allow",systemPower:"ask",systemConfiguration:"ask",userAccount:"deny"};function $D(t,n){return t==="safe-auto"?Kg:t==="full-access"?{...Kg,processControl:"allow",serviceControl:"allow",applicationControl:"allow",fileDelete:"allow",shell:"allow",script:"allow",softwareInstall:"allow",systemPower:"allow",systemConfiguration:"allow"}:t==="custom"&&n?n:{...Kg,processControl:"ask",serviceControl:"ask",applicationControl:"ask",fileWrite:"ask",network:"ask"}}function UD(t,n,r){const s=$D(n,r),l=t.requiredOperations.map(u=>s[ic[u].permissionCategory]);if(l.includes("deny")){const u=t.requiredOperations.find(f=>s[ic[f].permissionCategory]==="deny");return{state:"blocked",label:"Blocked",reason:`This task requires ${ic[u].label}, which is blocked by the current permission policy.`}}return l.includes("ask")?{state:"approval",label:"Approval required",reason:"This task requires approval before the requested changes can reach a Client."}:t.requiredOperations.every(u=>ic[u].readOnly)?{state:"read-only",label:"Read only"}:n==="full-access"?{state:"full-access",label:"Full Access"}:{state:"auto",label:"Auto allowed"}}function qD(t){const n=String(t||"").trim().toLowerCase();return n==="windows"||n==="win32"||n==="win32nt"?"windows":n==="macos"||n==="macosx"||n==="darwin"||n==="osx"?"macos":n==="linux"?"linux":null}function WD(t,n,r){const s=new Set(r);return t.filter(l=>l.connected&&(n==="all"||n==="auto"||s.has(l.deviceId)))}function GD(t,n){const r=qD(t.platform);if(!r||!n.supportedPlatforms.includes(r))return!1;const s=t.capabilities?.agentTools;return!Array.isArray(s)||s.length===0?n.requiredOperations.every(l=>ic[l].readOnly):n.requiredOperations.every(l=>s.includes(l))}function uC(t,n,r,s,l,u){const f=UD(t,l,u),h=WD(n,r,s),g=h.map(k=>k.deviceId),y={...f,available:!1,availableDeviceIds:[],unsupportedDeviceIds:g,risk:t.risk,supportedPlatforms:t.supportedPlatforms};if(h.length===0)return{...y,reason:"Select at least one connected Client."};if(t.targetSupport==="single"&&h.length!==1)return{...y,reason:"This task supports one Client at a time."};if(f.state==="blocked")return y;const w=h.filter(k=>GD(k,t)),b=w.map(k=>k.deviceId),S=g.filter(k=>!b.includes(k));return w.length===0?{...y,unsupportedDeviceIds:S,reason:"No current target supports the required platform and client capabilities."}:{...y,available:!0,availableDeviceIds:b,unsupportedDeviceIds:S}}function VD(t,n,r,s,l,u){return t.filter(f=>f.enabled&&uC(f,n,r,s,l,u).available).length}const Qg="livedesk.agentPromptRecent",Yg="livedesk.agentPromptFavorites",KD={Recommended:lc,"Health & capacity":Ld,"Processes & services":aM,"Files & configuration":nM,"Software & automation":g0,"Network & connectivity":Uv,"Power & maintenance":Ea,"Troubleshooting & recovery":tM};function Ax(t){if(typeof window>"u")return[];try{const n=JSON.parse(window.localStorage.getItem(t)||"[]");return Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}catch{return[]}}function Hp(t,n){try{window.localStorage.setItem(t,JSON.stringify(n))}catch{}}function Xg(t){return t==="all"?"All tasks":t==="recent"?"Recent":t==="favorites"?"Favorites":t==="read-only"?"Read only":t==="auto"?"Auto allowed":t==="approval"?"Approval required":t==="full-access"?"Full Access":t==="available"?"Available":t==="unavailable"?"Unavailable":t}function QD(t){return t==="all"?"All":t==="recent"?"Recent":t==="favorites"?"Favorites":t==="read-only"?"Read only":t==="auto"?"Auto":t==="approval"?"Approval":t==="full-access"?"Full access":t==="available"?"Available":t==="unavailable"?"Unavailable":{Recommended:"Recommended","Health & capacity":"Health","Processes & services":"Processes","Files & configuration":"Files","Software & automation":"Software","Network & connectivity":"Network","Power & maintenance":"Power","Troubleshooting & recovery":"Recovery"}[t]}function YD(t,n,r){if(!r.trim())return!0;const s=r.trim().toLowerCase();return[t.title,t.prompt,t.description,t.category,t.risk,n.label,...t.keywords,...t.requiredOperations,...t.supportedPlatforms].join(" ").toLowerCase().includes(s)}function XD(t){return`permission-${t}`}function ZD(t){return t==="low"?"Low risk":t==="medium"?"Medium risk":t==="high"?"High risk":"Critical risk"}function JD(t){return t==="windows"?"Windows":t==="macos"?"macOS":"Linux"}function eI({devices:t,targetMode:n,selectedIds:r,permissionMode:s,customCategories:l,onSelectPrompt:u,onClose:f}){const[h,g]=d.useState(""),[y,w]=d.useState("all"),[b,S]=d.useState(()=>Ax(Qg)),[k,A]=d.useState(()=>Ax(Yg)),[T,j]=d.useState(0),[I,N]=d.useState(""),P=d.useRef(null),H=d.useRef(null),F=d.useMemo(()=>cC.filter(ee=>ee.enabled),[]),$=d.useMemo(()=>new Map(F.map(ee=>[ee.id,uC(ee,t,n,r,s,l)])),[l,t,s,r,n,F]),D=d.useMemo(()=>[...$.values()].filter(ee=>ee.available).length,[$]),K=d.useMemo(()=>t.filter(ee=>ee.connected&&(n==="all"||n==="auto"||r.includes(ee.deviceId))).length,[t,r,n]),z=d.useMemo(()=>{const ee=F.filter(U=>YD(U,$.get(U.id),h));return y==="recent"?b.map(U=>ee.find(L=>L.id===U)).filter(U=>!!U):y==="favorites"?k.map(U=>ee.find(L=>L.id===U)).filter(U=>!!U):y==="all"?ee:ee.filter(U=>{const L=$.get(U.id);return y==="read-only"?L.state==="read-only":y==="auto"?L.state==="auto":y==="approval"?L.state==="approval":y==="full-access"?L.state==="full-access":y==="available"?L.available:y==="unavailable"?!L.available:U.category===y})},[$,k,y,b,h,F]),q=d.useMemo(()=>y!=="all"?[{category:Xg(y),templates:z}]:kx.map(ee=>({category:ee,templates:z.filter(U=>U.category===ee)})).filter(ee=>ee.templates.length>0),[y,z]);d.useEffect(()=>{j(ee=>Math.min(ee,Math.max(0,z.length-1)))},[z.length]),d.useEffect(()=>{Hp(Qg,b)},[b]),d.useEffect(()=>{Hp(Yg,k)},[k]),d.useEffect(()=>{H.current?.focus();const ee=L=>{L.target instanceof Node&&!P.current?.contains(L.target)&&f()},U=L=>{L.key==="Escape"&&(L.preventDefault(),f())};return document.addEventListener("pointerdown",ee),document.addEventListener("keydown",U),()=>{document.removeEventListener("pointerdown",ee),document.removeEventListener("keydown",U)}},[f]);const W=ee=>{const U=$.get(ee.id);if(!U.available){N(U.reason||"This task is not available for the current targets and permission policy.");return}const L=[ee.id,...b.filter(le=>le!==ee.id)].slice(0,10);S(L),Hp(Qg,L),u(ee.prompt),f()},Y=ee=>{A(U=>{const L=U.includes(ee)?U.filter(le=>le!==ee):[ee,...U];return Hp(Yg,L),L})},V=ee=>{ee.key==="ArrowDown"?(ee.preventDefault(),j(U=>Math.min(U+1,Math.max(0,z.length-1)))):ee.key==="ArrowUp"?(ee.preventDefault(),j(U=>Math.max(U-1,0))):ee.key==="Enter"&&z[T]&&(ee.preventDefault(),W(z[T]))};let he=-1;return o.jsxs("section",{className:"agents-suggested-tasks",ref:P,"aria-label":"Suggested tasks",children:[o.jsxs("header",{className:"agents-suggested-header",children:[o.jsxs("div",{children:[o.jsxs("span",{className:"agents-suggested-title",children:[o.jsx(lc,{size:15})," Suggested tasks"]}),o.jsxs("small",{children:[D," available · ",F.length," total. Choose a task, edit it, then run it."]})]}),o.jsx("button",{className:"agents-suggested-close",type:"button","aria-label":"Close suggested tasks",onClick:f,children:o.jsx(vr,{size:16})})]}),o.jsxs("label",{className:"agents-suggested-search",children:[o.jsx(eM,{size:15,"aria-hidden":"true"}),o.jsx("input",{ref:H,value:h,onChange:ee=>g(ee.target.value),onKeyDown:V,placeholder:"Search tasks...","aria-label":"Search suggested tasks"})]}),o.jsx("div",{className:"agents-suggested-filters","aria-label":"Task categories and availability filters",children:["all","recent","favorites","read-only","auto","approval","full-access","available","unavailable",...kx].map(ee=>{const U=ee==="recent"?h0:ee==="favorites"?fv:ee==="all"?lc:ee==="available"?tr:ee==="unavailable"?S0:ee==="read-only"||ee==="auto"||ee==="approval"||ee==="full-access"?Ea:KD[ee];return o.jsxs("button",{className:y===ee?"active":"",type:"button",title:Xg(ee),"aria-label":Xg(ee),"aria-pressed":y===ee,onClick:()=>{w(ee),j(0),N("")},children:[o.jsx(U,{size:12})," ",QD(ee)]},ee)})}),I&&o.jsx("div",{className:"agents-suggested-notice",role:"status",children:I}),o.jsxs("div",{className:"agents-suggested-list",role:"listbox","aria-label":"Suggested tasks",children:[q.map(ee=>o.jsxs("div",{className:"agents-suggested-group",children:[o.jsx("strong",{children:ee.category}),ee.templates.map(U=>{he+=1;const L=he===T,le=k.includes(U.id),ve=$.get(U.id),J=ve.availableDeviceIds.length+ve.unsupportedDeviceIds.length||K,Ae=ve.available?`Available on ${ve.availableDeviceIds.length} of ${J} target${J===1?"":"s"}`:`Unavailable: ${ve.reason||"not supported by the current targets"}`;return o.jsxs("div",{className:`agents-suggested-item ${L?"active":""} ${ve.available?"":"unavailable"}`,children:[o.jsxs("button",{className:"agents-suggested-prompt",type:"button",role:"option","aria-selected":L,"aria-disabled":!ve.available,onClick:()=>W(U),children:[o.jsx("span",{children:U.title}),o.jsx("small",{className:"agents-suggested-description",children:U.description}),o.jsxs("span",{className:"agents-suggested-meta",children:[o.jsx("em",{children:U.category}),o.jsx("em",{className:XD(ve.state),children:ve.label}),o.jsx("em",{className:`risk-${U.risk}`,children:ZD(U.risk)}),o.jsx("em",{children:U.supportedPlatforms.map(JD).join(" · ")}),o.jsx("em",{className:ve.available?"availability-ok":"availability-unavailable",children:Ae}),ve.available&&ve.unsupportedDeviceIds.length>0&&o.jsxs("em",{className:"availability-warning",children:["Unsupported on ",ve.unsupportedDeviceIds.length]})]})]}),o.jsx("button",{className:`agents-suggested-favorite ${le?"favorite":""}`,type:"button","aria-label":le?`Remove ${U.title} from favorites`:`Add ${U.title} to favorites`,"aria-pressed":le,onClick:()=>Y(U.id),children:o.jsx(fv,{size:14,fill:le?"currentColor":"none"})})]},U.id)})]},ee.category)),z.length===0&&o.jsx("p",{className:"agents-suggested-empty",children:"No tasks match this search or current filter."})]})]})}function tI({devices:t,mode:n,selectedIds:r,onModeChange:s,onToggle:l,permissionMode:u,onPermissionModeChange:f}){const h=t.filter(vh),g=r.filter(y=>h.some(w=>w.deviceId===y)).length;return o.jsxs("section",{className:"agents-target-picker","aria-label":"Agent targets",children:[o.jsxs("div",{className:"agents-target-toolbar",children:[o.jsx("span",{className:"agents-section-label",children:"Targets"}),o.jsxs("div",{className:"agents-target-modes",children:[o.jsxs("button",{className:n==="all"?"active":"",onClick:()=>s("all"),type:"button",children:[o.jsx(pm,{size:14})," All connected ",o.jsx("small",{children:h.length})]}),o.jsxs("button",{className:n==="selected"?"active":"",onClick:()=>s("selected"),type:"button",children:[o.jsx(tl,{size:14})," Selected ",g]}),o.jsxs("button",{className:n==="auto"?"active":"",onClick:()=>s("auto"),type:"button",children:[o.jsx(lc,{size:14})," Auto"]}),o.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[o.jsx(pm,{size:14})," Group ",o.jsx("small",{children:"Soon"})]})]}),o.jsxs("label",{className:`agents-permission-picker permission-${u}`,children:[o.jsx(wh,{size:14}),o.jsx("span",{children:"Permission"}),o.jsxs("select",{value:u,onChange:y=>f(y.target.value),"aria-label":"Agent permission mode",children:[o.jsx("option",{value:"ask",children:"Ask"}),o.jsx("option",{value:"safe-auto",children:"Safe Auto"}),o.jsx("option",{value:"full-access",children:"Full Access"}),o.jsx("option",{value:"custom",children:"Custom"})]}),o.jsx(x0,{size:13,"aria-hidden":"true"})]})]}),o.jsx("div",{className:"agents-target-list",children:t.length===0?o.jsx("span",{className:"agents-target-empty",children:"No Clients discovered."}):t.map(y=>{const w=vh(y),b=n==="all"||n==="auto"?w:r.includes(y.deviceId);return o.jsxs("label",{className:`agents-target-option ${b?"selected":""} ${w?"":"offline"}`,children:[o.jsx("input",{type:"checkbox",checked:b,disabled:!w||n!=="selected",onChange:()=>l(y.deviceId)}),o.jsx("span",{className:"agents-target-icon",children:o.jsx(nr,{size:15})}),o.jsxs("span",{children:[o.jsx("strong",{children:gh(y)}),o.jsx("small",{children:w?"Ready":y.connected?"Agent reconnecting":"Offline"})]}),b&&o.jsx(tl,{className:"agents-target-check",size:15,"aria-hidden":"true"})]},y.deviceId)})})]})}const nI=800,Tx=5e3;function aI(){return typeof document>"u"||document.visibilityState==="visible"}function rI(t){return typeof document>"u"?()=>{}:(document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t))}function Nx({poll:t,onResult:n,onError:r,intervalMs:s=nI,isVisible:l=aI,subscribeVisibility:u=rI,setTimeoutImpl:f=globalThis.setTimeout.bind(globalThis),clearTimeoutImpl:h=globalThis.clearTimeout.bind(globalThis),createAbortController:g=()=>new AbortController}){if(typeof t!="function")throw new TypeError("Agent polling requires a poll function.");const y={current:null};let w=!0,b=0,S=null,k=null;const A=()=>{S!==null&&(h(S),S=null)},T=()=>{!w||!l()||S!==null||y.current||(S=f(()=>{S=null,j()},s))},j=()=>{if(!w||!l()||y.current)return y.current;const H=++b,F=g();k=F;const $=yu(y,()=>t(F.signal));return $.then(D=>{w&&H===b&&!F.signal.aborted&&n?.(D)},D=>{w&&H===b&&!F.signal.aborted&&r?.(D)}).finally(()=>{k===F&&(k=null),w&&l()&&T()}).catch(()=>{}),$},I=async()=>{if(!w)throw new Error("LiveDesk Agent polling owner is closed.");A(),b+=1;const H=y.current;if(k&&!k.signal.aborted&&k.abort(new Error("LiveDesk Agent polling was superseded by an explicit refresh.")),H)try{await H}catch{}if(!(!w||!l()))return A(),j()},P=u(()=>{if(A(),!l()){b+=1,k&&!k.signal.aborted&&k.abort(new Error("LiveDesk Agent polling paused while hidden."));return}j()});return j(),{refresh:I,stop(){w&&(w=!1,b+=1,A(),P?.(),k&&!k.signal.aborted&&k.abort(new Error("LiveDesk Agent polling owner closed.")))}}}async function sI(t,n){return lt("/api/settings/agent/run",{method:"POST",body:JSON.stringify(n)},t)}async function iI(t,n,r={}){return lt(`/api/settings/agent/runs/${encodeURIComponent(n)}`,r,t)}async function oI(t,n){return lt(`/api/settings/agent/runs/${encodeURIComponent(n)}/cancel`,{method:"POST",body:JSON.stringify({})},t)}async function lI(t){return lt("/api/settings/agent/runs/cancel-all",{method:"POST",body:JSON.stringify({})},t)}async function cI(t,n,r,s){return lt(`/api/settings/agent/runs/${encodeURIComponent(n)}/approvals/${encodeURIComponent(r)}/approve`,{method:"POST",body:JSON.stringify({scope:s})},t)}async function uI(t,n,r,s="User rejected this action."){return lt(`/api/settings/agent/runs/${encodeURIComponent(n)}/approvals/${encodeURIComponent(r)}/reject`,{method:"POST",body:JSON.stringify({reason:s})},t)}async function dI(t,n,r){return lt(`/api/settings/agent/policies/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify({categories:r})},t)}async function fI(t,n,r={}){return lt(`/api/remote/tasks/${encodeURIComponent(n)}`,r,t)}async function mI(t,n){return lt(`/api/remote/tasks/${encodeURIComponent(n)}/cancel`,{method:"POST",body:JSON.stringify({})},t)}async function pI(t,n){return lt(`/api/remote/tasks/${encodeURIComponent(n)}/retry`,{method:"POST",body:JSON.stringify({failedOnly:!0})},t)}function Kf(t){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Zg(t,n){const r=new Map(n.map(s=>[s.deviceId,gh(s)]));return t.results.map(s=>({deviceId:s.deviceId,deviceName:s.deviceName||r.get(s.deviceId)||s.deviceId,status:RD(s.status),stage:s.stage||(s.status==="running"?"Checking processes":void 0),result:s.result,data:s.data,error:s.error,sequence:Number.isSafeInteger(s.sequence)?s.sequence:0}))}function hI(t,n){const r=new Map(n.map(s=>[s.deviceId,s]));return t.map(s=>{const l=r.get(s.deviceId);return!l||l.sequence<=s.sequence?s:l})}const gI={read:"allow",processControl:"ask",serviceControl:"ask",applicationControl:"ask",fileRead:"ask",fileWrite:"ask",fileDelete:"ask",shell:"ask",script:"ask",softwareInstall:"ask",network:"ask",systemPower:"ask",systemConfiguration:"ask",userAccount:"deny"};function vI(t){return t==="safe-auto"?"Safe Auto":t==="full-access"?"Full Access":t==="custom"?"Custom":"Ask"}function yI(t){return t.replace(/([A-Z])/g," $1").replace(/^./,n=>n.toUpperCase())}function bI(t){const n=t instanceof Error?t.message:String(t);return/agent-disabled/i.test(n)?"Enable Codex Agent in Settings before running commands.":/agent-no-target-devices|agent-target-not-connected|device-not-connected/i.test(n)?"The selected Client is reconnecting. Wait until its Agent status is Ready and try again.":/codex-auth-required/i.test(n)?"Codex sign-in is required on the Hub. Open Settings > Agent and test the Codex connection.":n}function Rx({hubUrl:t,devices:n,launchRequest:r,variant:s="page",selectedDeviceIds:l=[]}){const u=s==="dock",[f,h]=d.useState(u?l.length>0?"selected":"auto":"all"),[g,y]=d.useState(l),[w,b]=d.useState("auto"),[S,k]=d.useState(""),[A,T]=d.useState([]),[j,I]=d.useState(""),[N,P]=d.useState(""),[H,F]=d.useState(""),[$,D]=d.useState("safe-auto"),[K]=d.useState("custom-default"),[z,q]=d.useState(gI),[W,Y]=d.useState([]),[V,he]=d.useState(""),[ee,U]=d.useState(!1),[L,le]=d.useState(null),[ve,J]=d.useState(!1),[Ae,ce]=d.useState(""),[Te,Fe]=d.useState(!1),[$e,Ze]=d.useState(null),de=d.useRef(null),Be=d.useRef(null),Ve=d.useRef(null),Je=d.useRef(new Set),Qe=d.useRef(new Set),yt=d.useMemo(()=>n.filter(vh).map(pe=>pe.deviceId),[n]),ne=d.useMemo(()=>VD(cC,n,f,g,$,z),[z,n,$,g,f]);d.useEffect(()=>{u&&y(l)},[u,l]),d.useEffect(()=>{r?.deviceId&&(h("selected"),y([r.deviceId]),k(r.instruction),Fe(!1),window.requestAnimationFrame(()=>{de.current?.focus(),de.current?.setSelectionRange(r.instruction.length,r.instruction.length)}))},[r]);const me=d.useCallback(pe=>{const ae=Zg(pe,n);T(fe=>fe.map(Ee=>Ee.type==="task"&&Ee.batchId===pe.batchId?{...Ee,states:hI(Ee.states,ae),status:pe.status}:Ee)),["running","queued"].includes(pe.status)||I(fe=>fe===pe.batchId?"":fe)},[n]),Ge=d.useCallback((pe,ae)=>{Qe.current.has(pe.batchId)||(Qe.current.add(pe.batchId),T(fe=>[...fe,{type:"task",id:Kf("task"),batchId:pe.batchId,agentRunId:ae,operation:pe.operation||"diagnostics.collect",instruction:pe.instructionPreview,states:Zg(pe,n),status:pe.status}])),me(pe)},[n,me]),Se=d.useCallback((pe,ae)=>{for(const Ee of ae.taskBatches||[])Ge(Ee,pe);Y(ae.approvals||[]);const fe=["running","queued","waiting-approval"].includes(ae.status);if(Ze(fe?{runId:pe,stage:ae.stage||ae.status,message:ae.progressMessage||(ae.status==="waiting-approval"?"Review the requested action to continue.":"Codex is preparing the answer.")}:Ee=>Ee?.runId===pe?null:Ee),!fe&&!Je.current.has(pe)){Je.current.add(pe);const Ee=[ae.error,ae.errorMessage].filter(Boolean).join(" — "),je=ae.finalResponse?.trim()||(ae.status==="cancelled"?"Codex 작업을 취소했습니다.":Ee?`Codex 작업이 완료되지 않았습니다: ${Ee}`:"Codex 작업이 완료되었습니다.");T(De=>[...De,{type:ae.status==="failed"?"error":"agent",id:Kf("agent-run-result"),text:je}])}},[Ge]),ge=d.useCallback(async pe=>{const ae=Be.current;if(!(!ae||ae.id!==pe))try{return await ae.owner.refresh()}catch(fe){if(Be.current!==ae)return;throw fe}},[]);d.useEffect(()=>{if(!N){Be.current=null;return}const pe=N,ae=Nx({poll:Ee=>iI(t,pe,{signal:Ee,timeoutMs:Tx}),onResult:Ee=>{Se(pe,Ee),["running","queued","waiting-approval"].includes(Ee.status)||(P(je=>je===pe?"":je),J(!1))},onError:Ee=>{ce(Ee instanceof Error?Ee.message:String(Ee))}}),fe={id:pe,owner:ae};return Be.current=fe,()=>{ae.stop(),Be.current===fe&&(Be.current=null)}},[N,t,Se]),d.useEffect(()=>{if(!j){Ve.current=null;return}const pe=j,ae=Nx({poll:Ee=>fI(t,pe,{signal:Ee,timeoutMs:Tx}),onResult:Ee=>{me(Ee),["running","queued"].includes(Ee.status)||I(je=>je===pe?"":je)},onError:Ee=>{ce(Ee instanceof Error?Ee.message:String(Ee))}}),fe={id:pe,owner:ae};return Ve.current=fe,()=>{ae.stop(),Ve.current===fe&&(Ve.current=null)}},[j,t,me]);const Ue=async(pe="",ae,fe=!1)=>{const Ee=(pe||S).trim();if(!Ee||j||N)return;const je=ae||(f==="all"||f==="auto"?yt:g.filter(ft=>yt.includes(ft)));if(je.length===0){ce("Select at least one connected Client.");return}if($==="full-access"&&!ve&&!fe){le({instruction:Ee,targetIds:je});return}if(T(ft=>[...ft,{type:"user",id:Kf("user"),text:Ee}]),k(""),Fe(!1),ce(""),je.length===0){T(ft=>[...ft,{type:"error",id:Kf("no-targets"),text:"연결된 대상 장비를 하나 이상 선택해 주세요."}]);return}const Et=w==="ask"?`Read-only request. Inspect and answer without changing Client state.
180
-
181
- ${Ee}`:w==="plan"?`Plan only. Produce a safe execution plan, but do not change Client state.
182
-
183
- ${Ee}`:w==="execute"?`Execute this request within the configured LiveDesk approval policy.
184
-
185
- ${Ee}`:Ee,at=f==="auto"?`Auto target selection is enabled. Inspect the allowed Clients and use only the most suitable target or targets for this request.
186
-
187
- ${Et}`:Et;try{if($==="custom"){const jt=await dI(t,K,z);if(!jt.ok)throw new Error(jt.error||"Custom Agent policy could not be saved.")}const ft=await sI(t,{instruction:at,deviceIds:je,permissionMode:$,customPolicyId:K});if(!ft.ok||!ft.runId)throw new Error(ft.error||"Codex Agent run could not be started.");Y(ft.approvals||[]),Ze({runId:ft.runId,stage:ft.stage||ft.status||"queued",message:ft.progressMessage||"Codex request queued on the Hub."}),P(ft.runId)}catch(ft){T(jt=>[...jt,{type:"error",id:Kf("codex-run-error"),text:bI(ft)}])}},Me=async(pe,ae)=>{he(pe.approvalId);try{const fe=await cI(t,pe.runId,pe.approvalId,ae);if(!fe.ok)throw new Error(fe.error||"Agent approval could not be applied.");await ge(pe.runId)}catch(fe){ce(fe instanceof Error?fe.message:String(fe))}finally{he("")}},rt=async pe=>{he(pe.approvalId);try{const ae=await uI(t,pe.runId,pe.approvalId);if(!ae.ok)throw new Error(ae.error||"Agent approval could not be rejected.");await ge(pe.runId)}catch(ae){ce(ae instanceof Error?ae.message:String(ae))}finally{he("")}},At=async(pe,ae)=>{F(pe);try{if(ae){const Ee=await oI(t,ae);for(const je of Ee.taskBatches||[])me(je);P(je=>je===ae?"":je),Ze(je=>je?.runId===ae?null:je);return}const fe=await mI(t,pe);me(fe),I(Ee=>Ee===pe?"":Ee)}catch(fe){ce(fe instanceof Error?fe.message:String(fe))}finally{F("")}},O=async()=>{if(!(ee||!j&&!N)){U(!0);try{const pe=await lI(t);if(!pe.ok)throw new Error(pe.error||"모든 Agent 작업을 취소하지 못했습니다.");I(""),P(""),Ze(null),Y([]),T(ae=>ae.map(fe=>fe.type==="task"&&["queued","running"].includes(fe.status)?{...fe,status:"cancelled",states:fe.states.map(Ee=>["queued","running"].includes(Ee.status)?{...Ee,status:"cancelled",stage:"Cancelled",error:"Cancelled by user."}:Ee)}:fe))}catch(pe){ce(pe instanceof Error?pe.message:String(pe))}finally{U(!1)}}},qe=async pe=>{F(pe);try{const ae=await pI(t,pe);if(!ae.ok||!ae.batch||!ae.batchId)throw new Error(ae.error||"재시도하지 못했습니다.");T(fe=>fe.map(Ee=>Ee.type==="task"&&Ee.batchId===pe?{...Ee,batchId:ae.batchId,states:Zg(ae.batch,n),status:ae.batch.status}:Ee)),I(ae.batchId)}catch(ae){ce(ae instanceof Error?ae.message:String(ae))}finally{F("")}},B=pe=>{k(pe),Fe(!1),window.requestAnimationFrame(()=>de.current?.focus())},Oe=d.useMemo(()=>n.filter(vh),[n]),We=d.useMemo(()=>Oe.filter(pe=>g.includes(pe.deviceId)),[Oe,g]),et=f==="auto"?`Auto · ${Oe.length} available`:f==="all"?`All ${Oe.length} computers`:We.length===1?gh(We[0]):`${We.length} selected`,it=f==="auto"?"LiveDesk chooses the best computer for each task.":f==="all"?"The Agent may coordinate every connected computer.":We.length>0?We.map(gh).join(" · "):"Select one or more computers on the Wall.",ye=f==="selected"&&We.length===1?["Diagnose this computer","Analyze recent errors","Summarize running applications","Check disk and GPU capacity"]:f==="all"?["Compare all computer health","Find the busiest computer","Check disk capacity everywhere","Divide a task across computers"]:["Use the fastest computer","Find an idle computer","Choose the best GPU","Check all computer health"],Ne=f==="selected"?We.length>0?"What should this computer do?":"Choose a computer or use Auto.":f==="all"?"Use all your computers together.":"What should LiveDesk handle?",He=f==="auto"?"The Hub Codex Agent can inspect the available computers and choose the best target.":"Describe the outcome. The Hub Codex Agent will plan approved commands and show progress per computer.";return o.jsxs("section",{className:`agents-page ${u?"agents-dock-console":""}`,children:[u&&o.jsxs("header",{className:"agent-console-header",children:[o.jsxs("div",{className:"agent-console-title",children:[o.jsx("span",{className:"agent-console-mark",children:o.jsx(lc,{size:16})}),o.jsxs("div",{children:[o.jsx("small",{children:"Hub Codex Agent"}),o.jsx("strong",{children:"Command Console"})]}),o.jsx("i",{children:"Ready"})]}),o.jsxs("section",{className:"agent-console-target","aria-label":"Agent target scope",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Target"}),o.jsx("strong",{children:et}),o.jsx("small",{children:it})]}),o.jsxs("div",{className:"agent-console-target-modes",children:[o.jsxs("button",{className:f==="selected"?"active":"",onClick:()=>h("selected"),type:"button",children:[o.jsx(tl,{size:12})," Selected"]}),o.jsxs("button",{className:f==="all"?"active":"",onClick:()=>h("all"),type:"button",children:[o.jsx(pm,{size:12})," All"]}),o.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[o.jsx(pm,{size:12})," Group"]}),o.jsxs("button",{className:f==="auto"?"active":"",onClick:()=>h("auto"),type:"button",children:[o.jsx(lc,{size:12})," Auto"]})]})]}),o.jsx("div",{className:"agent-console-interaction-modes","aria-label":"Agent interaction mode",children:["auto","ask","plan","execute"].map(pe=>o.jsxs("button",{className:w===pe?"active":"",onClick:()=>b(pe),type:"button",children:[pe==="auto"?o.jsx(lc,{size:12}):pe==="execute"?o.jsx(nr,{size:12}):null,pe[0].toUpperCase()+pe.slice(1)]},pe))})]}),o.jsxs("div",{className:"agents-workspace",children:[(j||N)&&o.jsxs("div",{className:"agents-page-status",children:[o.jsxs("span",{children:[yt.length," Clients · ",vI($)]}),o.jsx("button",{type:"button",className:"agents-stop-all",onClick:()=>{O()},disabled:ee,children:ee?"Stopping…":"Stop all"})]}),L&&o.jsx("div",{className:"agents-permission-modal-backdrop",role:"presentation",children:o.jsxs("section",{className:"agents-permission-modal",role:"dialog","aria-modal":"true","aria-labelledby":"full-access-title",children:[o.jsx("span",{className:"agents-permission-modal-icon",children:o.jsx(wh,{size:20})}),o.jsx("h3",{id:"full-access-title",children:"Confirm Full Access"}),o.jsx("p",{children:"Codex may change files, run commands, manage applications, and modify system state on the selected Clients. This run is still limited to the selected devices, the fixed policy, and the tool budget."}),o.jsxs("div",{className:"agents-permission-modal-actions",children:[o.jsx("button",{type:"button",onClick:()=>le(null),children:"Cancel"}),o.jsx("button",{type:"button",className:"danger",onClick:()=>{const pe=L;le(null),J(!0),Ue(pe.instruction,pe.targetIds,!0)},children:"Run with Full Access"})]})]})}),Ae&&o.jsx("div",{className:"agents-error",role:"alert",children:Ae}),o.jsx(FD,{items:A,onCancel:At,onRetry:qe,busyBatchId:H,approvals:W,onApprove:Me,onReject:rt,busyApprovalId:V,progress:$e,emptyTitle:u?Ne:void 0,emptyBody:u?He:void 0}),u&&A.length===0&&!$e&&o.jsx("div",{className:"agent-console-suggestions","aria-label":"Suggested Agent commands",children:ye.map(pe=>o.jsx("button",{type:"button",onClick:()=>B(pe),children:pe},pe))}),o.jsxs("div",{className:"agents-composer-shell",children:[Te&&o.jsx(eI,{devices:n,targetMode:f,selectedIds:g,permissionMode:$,customCategories:z,onSelectPrompt:B,onClose:()=>Fe(!1)}),o.jsx(TD,{ref:de,value:S,onChange:k,onSubmit:()=>{Ue()},onOpenSuggestedTasks:()=>Fe(pe=>!pe),suggestedOpen:Te,suggestedTaskCount:ne,disabled:!!j||!!N,placeholder:u?"Tell LiveDesk what outcome you want...":void 0,compact:u})]})]}),!u&&o.jsxs("aside",{className:"agents-target-sidebar","aria-label":"Agent targets and permissions",children:[o.jsx(tI,{devices:n,mode:f,selectedIds:g,onModeChange:h,onToggle:pe=>y(ae=>ae.includes(pe)?ae.filter(fe=>fe!==pe):[...ae,pe]),permissionMode:$,onPermissionModeChange:pe=>{D(pe),pe!=="full-access"&&J(!1)}}),$==="custom"&&o.jsxs("section",{className:"agents-custom-policy","aria-label":"Custom Agent permissions",children:[o.jsxs("div",{className:"agents-custom-policy-head",children:[o.jsxs("div",{children:[o.jsx("span",{className:"agents-section-label",children:"Custom policy"}),o.jsx("strong",{children:"Choose what Codex may do automatically."})]}),o.jsx("span",{children:"Denied actions never reach a device."})]}),o.jsx("div",{className:"agents-custom-policy-grid",children:ND.map(pe=>o.jsxs("label",{children:[o.jsx("span",{children:yI(pe)}),o.jsxs("select",{value:z[pe],onChange:ae=>q(fe=>({...fe,[pe]:ae.target.value})),children:[o.jsx("option",{value:"allow",children:"Allow automatically"}),o.jsx("option",{value:"ask",children:"Ask every time"}),o.jsx("option",{value:"deny",children:"Deny"})]})]},pe))})]})]})]})}function dC(t){return{type:t.type,deviceIds:t.deviceIds,monitorIndex:t.monitorIndex,label:t.label}}async function fC(t){try{return(await t.json()).error||`${t.status} ${t.statusText}`}catch{return`${t.status} ${t.statusText}`}}async function mC(t,n,r){const s=encodeURIComponent(JSON.stringify({kind:n.kind,fileName:n.fileName,mimeType:t.type||"application/octet-stream",durationMs:n.durationMs,target:dC(n.target)})),l=await Wv(`/api/captures?metadata=${s}`,{method:"POST",headers:{"Content-Type":t.type||"application/octet-stream"},body:t},r);if(!l.ok)throw new Error(await fC(l));return await l.json()}async function wI(t,n){return await lt("/api/capture-sessions",{method:"POST",body:JSON.stringify({...t,target:dC(t.target)})},n)}async function xI(t,n,r,s){const l=await Wv(`/api/capture-sessions/${encodeURIComponent(t)}/chunks/${n}`,{method:"PUT",headers:{"Content-Type":r.type||"application/octet-stream"},body:r},s);if(!l.ok)throw new Error(await fC(l));return await l.json()}async function SI(t,n,r){return await lt(`/api/capture-sessions/${encodeURIComponent(t)}/finalize`,{method:"POST",body:JSON.stringify({durationMs:n})},r)}async function Ex(t,n){await lt(`/api/capture-sessions/${encodeURIComponent(t)}`,{method:"DELETE"},n)}async function CI(t){return await lt("/api/captures",void 0,t)}function jx(t,n){return`${Su(n)}/api/captures/${encodeURIComponent(t)}/content`}async function kI(t,n){return await lt(`/api/captures/${encodeURIComponent(t)}`,{method:"DELETE"},n)}function MI({hubUrl:t,onToast:n}){const[r,s]=d.useState([]),[l,u]=d.useState(!0),f=d.useCallback(async()=>{u(!0);try{s((await CI(t)).captures||[])}catch(g){n(g instanceof Error?g.message:String(g))}finally{u(!1)}},[t,n]);d.useEffect(()=>{f()},[f]);const h=async g=>{const y=jx(g.id,t);if(navigator.share)try{await navigator.share({title:g.fileName,url:y});return}catch{}window.open(y,"_blank","noopener,noreferrer")};return o.jsxs("section",{className:"capture-gallery",children:[o.jsxs("header",{children:[o.jsxs("div",{children:[o.jsx("span",{className:"settings-eyebrow",children:"Capture Gallery"}),o.jsx("h2",{children:"Saved captures"})]}),o.jsxs("button",{className:"text-button",onClick:()=>{f()},type:"button",children:[o.jsx(vu,{size:15})," Refresh"]})]}),l?o.jsx("p",{className:"settings-help",children:"Loading captures..."}):r.length===0?o.jsx("p",{className:"settings-help",children:"No captures saved yet."}):o.jsx("div",{className:"capture-gallery-grid",children:r.map(g=>{const y=jx(g.id,t);return o.jsxs("article",{className:"capture-gallery-card",children:[g.mimeType.startsWith("image/")?o.jsx("img",{src:y,alt:g.target.label}):o.jsx("video",{src:y,controls:!0,preload:"metadata"}),o.jsxs("div",{className:"capture-gallery-card-body",children:[o.jsx("strong",{children:g.fileName}),o.jsxs("small",{children:[g.target.label," · ",new Date(g.createdAt).toLocaleString()," · ",Math.ceil(g.sizeBytes/1024)," KB"]}),o.jsxs("div",{children:[o.jsx("button",{className:"icon-button",title:"Open","aria-label":"Open",onClick:()=>window.open(y,"_blank","noopener,noreferrer"),type:"button",children:o.jsx(rM,{size:15})}),o.jsx("a",{className:"icon-button",title:"Download","aria-label":"Download",href:`${y}?download=1`,download:g.fileName,children:o.jsx(mm,{size:15})}),o.jsx("button",{className:"icon-button",title:"Share","aria-label":"Share",onClick:()=>{h(g)},type:"button",children:o.jsx(C0,{size:15})}),o.jsx("button",{className:"icon-button danger",title:"Delete","aria-label":"Delete",onClick:()=>{window.confirm(`Delete ${g.fileName}?`)&&kI(g.id,t).then(()=>f()).catch(w=>n(w instanceof Error?w.message:String(w)))},type:"button",children:o.jsx(b0,{size:15})})]})]})]},g.id)})})]})}function zp(t){if(!t)return"";const n=Math.max(0,Math.floor((Date.now()-t)/1e3)),r=Math.floor(n/3600),s=Math.floor(n%3600/60),l=n%60;return r>0?`${String(r).padStart(2,"0")}:${String(s).padStart(2,"0")}:${String(l).padStart(2,"0")}`:`${String(s).padStart(2,"0")}:${String(l).padStart(2,"0")}`}function Dx({controller:t,compact:n=!1,onFirstRollingUse:r,onError:s}){const{state:l,settings:u,videoSupported:f}=t,h=async b=>{try{await b()}catch(S){s?.(S instanceof Error?S.message:String(S))}},g=async()=>{if(u.rollingEnabled){t.setRollingEnabled(!1);return}(r?await r():window.confirm(`Keep the most recent 30 seconds in memory temporarily?
188
- Nothing is saved until you press Save Last 30s.`))&&t.setRollingEnabled(!0)},y=l.recording?`Stop recording · ${zp(l.recordingStartedAt)}`:`Start recording · ${l.targetLabel}`,w=l.timelapse?`Stop timelapse · ${zp(l.timelapseStartedAt)}`:`Start timelapse · ${u.timelapseIntervalSeconds}s interval`;return o.jsxs("div",{className:`capture-toolbar ${n?"compact":""} ${l.recording?"recording-active":""}`,"aria-label":"Capture actions",children:[o.jsx("button",{className:"capture-action","aria-label":`Take screenshot · ${l.targetLabel}`,title:`Take screenshot · ${l.targetLabel}`,disabled:l.busy,onClick:()=>{h(t.takeScreenshot)},type:"button",children:o.jsx(sM,{size:17})}),o.jsx("button",{className:`capture-action ${l.recording?"active":""}`,"aria-label":y,title:y,disabled:!f||l.busy||l.timelapse,onClick:()=>{h(l.recording?t.stopRecording:t.startRecording)},type:"button",children:l.recording?o.jsxs(o.Fragment,{children:[o.jsx(_b,{size:14,fill:"currentColor"}),o.jsx("span",{children:zp(l.recordingStartedAt)})]}):o.jsx(w0,{size:18})}),o.jsxs("button",{className:"capture-action","aria-label":l.bufferEnabled?`Save last 30 seconds · ${l.bufferSeconds}s ready`:"Enable Last 30s memory buffer",title:l.bufferEnabled?`Save last 30 seconds · ${l.bufferSeconds}s ready`:"Enable Last 30s memory buffer",disabled:!f||l.recording||l.timelapse||l.busy||l.bufferEnabled&&l.bufferSeconds<1,onClick:()=>l.bufferEnabled?void h(t.saveLast30Seconds):void g(),type:"button",children:[o.jsx(iM,{size:17}),o.jsx("small",{children:"30s"})]}),o.jsx("button",{className:`capture-action ${l.timelapse?"timelapse-active":""}`,"aria-label":w,title:w,disabled:!f||l.busy||l.recording,onClick:()=>{h(l.timelapse?t.stopTimelapse:t.startTimelapse)},type:"button",children:l.timelapse?o.jsxs(o.Fragment,{children:[o.jsx(_b,{size:14,fill:"currentColor"}),o.jsx("span",{children:zp(l.timelapseStartedAt)})]}):o.jsx(oM,{size:17})})]})}function pC({state:t}){return t==="ok"?o.jsx(tr,{size:15,"aria-hidden":"true"}):o.jsx(S0,{size:15,"aria-hidden":"true"})}function Ix({active:t,refreshing:n,onClick:r}){return o.jsx("button",{className:`remote-status-button ${t?"active":""}`,type:"button",title:"Check Remote Status","aria-label":"Check Remote Status","aria-pressed":t,"aria-busy":n,onClick:r,children:n?o.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):o.jsx(lM,{size:18,"aria-hidden":"true"})})}function Lx({active:t,refreshing:n,onClick:r}){return o.jsx("button",{className:`remote-status-button debug-status-button ${t?"active":""}`,type:"button",title:"Check Debug Status","aria-label":"Check Debug Status","aria-pressed":t,"aria-busy":n,onClick:r,children:n?o.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):o.jsx(f0,{size:18,"aria-hidden":"true"})})}function Px({active:t,refreshing:n,onClick:r}){return o.jsx("button",{className:`remote-status-button hub-status-button ${t?"active":""}`,type:"button",title:"Check Hub Status","aria-label":"Check Hub Status","aria-pressed":t,"aria-busy":n,onClick:r,children:n?o.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):o.jsx(mo,{size:18,"aria-hidden":"true"})})}function hC({items:t,mode:n="remote"}){return o.jsx("span",{className:`remote-status-lines mode-${n}`,role:"status","aria-label":n==="debug"?"Debug status":"Remote status",onPointerDown:n==="debug"?r=>r.stopPropagation():void 0,onClick:n==="debug"?r=>r.stopPropagation():void 0,onDoubleClick:n==="debug"?r=>r.stopPropagation():void 0,children:t.map(r=>o.jsxs("span",{className:`remote-status-line state-${r.state}`,title:r.detail,children:[o.jsx(pC,{state:r.state}),o.jsxs("span",{children:[o.jsx("strong",{children:r.label}),o.jsx("small",{children:r.detail})]})]},r.id))})}function AI({items:t,collectedAt:n,onClose:r}){return o.jsxs("section",{className:"remote-status-dialog hub-status-dialog",role:"dialog","aria-modal":"false","aria-labelledby":"hub-status-dialog-title",children:[o.jsxs("header",{children:[o.jsx("span",{className:"remote-status-dialog-mark","aria-hidden":"true",children:o.jsx(mo,{size:19})}),o.jsxs("span",{children:[o.jsx("small",{children:"Hub measurements"}),o.jsx("h2",{id:"hub-status-dialog-title",children:"Hub Status"})]}),o.jsx("button",{type:"button",onClick:r,title:"Close Hub status","aria-label":"Close Hub status",children:o.jsx(vr,{size:17})})]}),o.jsx("p",{children:"LiveDesk collects these Hub and browser signals continuously. This check refreshed the latest snapshot instead of starting a one-time benchmark."}),o.jsx("div",{className:"remote-status-dialog-list",children:t.map(s=>o.jsxs("article",{className:`remote-status-dialog-row state-${s.state}`,children:[o.jsx(pC,{state:s.state}),o.jsxs("span",{children:[o.jsx("strong",{children:s.label}),o.jsx("small",{children:s.detail})]})]},s.id))}),o.jsxs("footer",{children:["Checked ",new Date(n).toLocaleTimeString()]})]})}const TI=/(nvenc|videotoolbox|qsv|quick\s*sync|amf|vaapi|v4l2m2m|mediafoundation|h264_mf)/i,NI=/(libx264|openh264|software|cpu)/i,Hv=2,RI=256,su=new Map,Ft=Object.freeze({frameAgeWarningMs:2500,networkDelayWarningMs:120,receiveRatioWarning:.62,deliveryRatioWarning:.82,decoderInputRatioWarning:.82,decoderOutputRatioWarning:.62,captureBudgetMultiplier:2.5,minimumCaptureBudgetMs:80,cpuWarningRatio:.82,memoryWarningRatio:.86,gpuWarningRatio:.92,gpuMemoryWarningRatio:.92,gpuTemperatureWarningC:85,networkUsageWarningRatio:.85,networkLatencyWarningMs:80,nativeTelemetryStaleMs:3e3,minimumClientStatusFreshMs:15e3,clientStatusFreshMultiplier:3,runtimeProcessCpuWarningRatio:.65,runtimeProcessMemoryWarningBytes:1.5*1024**3,captureHelperCpuWarningRatio:.55,captureHelperMemoryWarningBytes:1024**3,hubMinimumTotalMemoryBytes:8*1024**3,hubMinimumBrowserMemoryGb:4});function pn(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function yy(t,n){let r=t;for(const s of String(n).split(".")){if(!r||typeof r!="object")return;r=r[s]}return r}function Mt(t,...n){for(const r of n){const s=yy(t,r);if(s==null||s==="")continue;const l=Number(s);if(Number.isFinite(l))return l}}function qt(t,...n){for(const r of n){const s=yy(t,r);if(typeof s=="string"&&s.trim())return s.trim()}return""}function gC(t,...n){for(const r of n){const s=yy(t,r);if(typeof s=="boolean")return s;if(s===1||s==="1"||String(s).toLowerCase()==="true")return!0;if(s===0||s==="0"||String(s).toLowerCase()==="false")return!1}}function Ai(t,...n){const r=Mt(t,...n);if(r!==void 0)return Math.max(0,Math.min(1,r>1?r/100:r))}function Xe(t,n,r,s){return{id:t,state:n,label:r,detail:s}}function vC(t){const n=pn(t),r=Mt(n,"helperCount"),s=Mt(n,"helperOwnedIoTaskCount"),l=Mt(n,"helperUndisposedProcessCount"),u=Mt(n,"helperOwnedExitObserverCount"),f=Mt(n,"helperQuarantineCount"),h=Mt(n,"utilityQuarantineCount"),g=Mt(n,"utilityOwnedIoTaskCount"),y=Mt(n,"utilityUndisposedProcessCount"),w=Number(Mt(n,"helperDisposeFailureCount")||0),b=Number(Mt(n,"utilityDisposeFailureCount")||0),S=Math.max(0,Number(r||0)),k=Number(s||0),A=Number(l||0),T=Number(u||0),j=Math.max(0,Number(f||0)),I=Math.max(0,Number(h||0)),N=Number(g||0),P=Number(y||0),H=[s,l,u,f,h,g,y].every(D=>D!==void 0),F=H&&(k<0||A<0||T<0||A!==S||T!==0||S===0&&k!==0||S>0&&k===0),$=H&&(N<0||P<0||P!==I||N!==I*2);return{telemetryAvailable:H,helperOwnedIoTaskCount:k,helperUndisposedProcessCount:A,helperOwnedExitObserverCount:T,helperQuarantineCount:j,helperDisposeFailureCount:w,helperLastDisposeFailure:qt(n,"helperLastDisposeFailure"),helperLedgerMismatch:F,utilityQuarantineCount:I,utilityOwnedIoTaskCount:N,utilityUndisposedProcessCount:P,utilityQuarantinePids:Array.isArray(n.utilityQuarantinePids)?n.utilityQuarantinePids.map(D=>Number(D)).filter(D=>Number.isSafeInteger(D)&&D>0):[],utilityQuarantineProfiles:Array.isArray(n.utilityQuarantineProfiles)?n.utilityQuarantineProfiles.map(D=>String(D||"").trim()).filter(Boolean).slice(0,4):[],utilityQuarantineStartCount:Math.max(0,Number(Mt(n,"utilityQuarantineStartCount")||0)),utilityQuarantineStopCount:Math.max(0,Number(Mt(n,"utilityQuarantineStopCount")||0)),utilityDisposeFailureCount:b,utilityLastDisposeFailure:qt(n,"utilityLastDisposeFailure"),utilityLedgerMismatch:$,historicalCleanupFailure:w!==0||b!==0,currentProblem:j>0||I>0||F||$}}function yC({key:t,sampleId:n,mismatch:r}){if(!t)return{count:0,confirmed:!1};if(!r)return su.delete(t),{count:0,confirmed:!1};const s=String(n||"").trim();if(!s)return{count:0,confirmed:!1};const l=dm(s),u=su.get(t);if(u?.sampleId===s)return{count:u.count,confirmed:u.count>=Hv};const f=u&&l!==void 0&&u.sampleEpochMs!==void 0&&l>u.sampleEpochMs,h=u&&f?u.count+1:1;return!su.has(t)&&su.size>=RI&&su.delete(su.keys().next().value),su.set(t,{sampleId:s,sampleEpochMs:l,count:h}),{count:h,confirmed:h>=Hv}}function dm(t){const n=Date.parse(String(t||""));return Number.isFinite(n)&&n>0?n:void 0}function _x(t){return`${(Math.max(0,Number(t||0))/1024**3).toFixed(1)} GB`}function tc(t){const n=Number(t);return Number.isFinite(n)?`${(Math.max(0,n)/1024**2).toFixed(0)} MB`:"-"}function nc(t){const n=Number(t);return Number.isFinite(n)?`${(Math.max(0,n)*100).toFixed(1)}%`:"-"}function $p(t){const n=Number(t);return Number.isFinite(n)?`${Math.max(0,n).toFixed(1)}%`:"-"}function EI(t){const n=String(t||"").replace(/^::ffff:/,"").trim().toLowerCase();if(!n||n==="::1"||n==="localhost"||n==="127.0.0.1"||/^10\./.test(n)||/^192\.168\./.test(n))return!0;const r=n.match(/^172\.(\d{1,3})\./);return!!r&&Number(r[1])>=16&&Number(r[1])<=31||n.startsWith("fe80:")||n.startsWith("fc")||n.startsWith("fd")}function bC(t){const n=pn(t),r=qt(n,"controlTransport").toLowerCase();return r==="encrypted-rendezvous-relay"||/relay/.test(r)?"encrypted-rendezvous-relay":r==="direct-tcp"||/direct|tcp/.test(r)?"direct-tcp":""}function Ox(t){const n=String(t||"").trim();if(!n)return"";try{return new URL(n.includes("://")?n:`relay://${n}`).host}catch{return n.replace(/[?#].*$/,"").replace(/^[a-z][a-z0-9+.-]*:\/\//i,"").split("@").pop().split("/")[0].slice(0,256)}}function jI(t){const n=bC(t);return n==="encrypted-rendezvous-relay"?Xe("control-transport","ok","Control connection: Encrypted rendezvous relay","Commands and remote input use the end-to-end encrypted rendezvous relay."):n==="direct-tcp"?Xe("control-transport","ok","Control connection: Direct TCP","Commands and remote input use the direct Hub connection."):Xe("control-transport","warning","Control connection is not identified","Waiting for Direct TCP or encrypted rendezvous relay status.")}function DI(t,n){const r=pn(t),s=pn(n),l=bC(r);if(l==="encrypted-rendezvous-relay"){const u=qt(s,"state")||(s.connected===!0?"registered":"unknown"),f=Ox(qt(s,"endpoint"))||Ox(qt(r,"relayEndpoint")),h=r.connected!==!0||s.connected===!1||/(connecting|reconnect|failed|error|degraded|unavailable|disabled)/.test(u);return Xe("debug-control-transport",h?"warning":"ok",`Encrypted rendezvous relay control · ${u}`,[`endpoint ${f||"-"}`,`state ${u}`,`reconnect ${Math.max(0,Number(s.reconnectCount||0))}`,`handshake ${Math.max(0,Number(s.handshakeCount||0))}`,`peers ${Math.max(0,Number(s.peerCount||0))}`,qt(s,"lastError")].filter(Boolean).join(" · "))}if(l==="direct-tcp"){const u=qt(r,"remoteAddress"),f=Mt(r,"remotePort"),h=u?`${u}${f?`:${f}`:""}`:"-";return Xe("debug-control-transport",r.connected===!0?"ok":"warning","Direct TCP control",`peer ${h} · protocol ${qt(r,"protocol")||"-"} v${Mt(r,"protocolVersion")??"-"} · input ${pn(r.channels).input===!1?"shared control channel":"dedicated channel"}`)}return Xe("debug-control-transport","warning","Control transport is not identified","No Direct TCP or encrypted rendezvous relay metadata is available.")}function wC(t,n){const r=Number(t?.browserReceivedEpochMs);return Number.isFinite(r)&&r>0?Math.max(0,n-r):Number.POSITIVE_INFINITY}function xC(t,n,r){const s=pn(n?.frameTransport),l=qt(t,"frameTransportChangedAt"),u=qt(s,"changedAt"),f=dm(l),h=dm(u),g=h!==void 0&&(f===void 0||h>f),y=g?s:t,w=g?t:s,b=qt(t,"transport").toLowerCase(),S=qt(y,g?"active":"frameTransportActive")||qt(w,g?"frameTransportActive":"active"),k=qt(y,g?"protocol":"frameTransportProtocol")||qt(w,g?"frameTransportProtocol":"protocol"),T=(g?qt(s,"videoTransport","activeTransport")||[S,k].filter(Boolean).join("-")||qt(t,"videoTransport"):qt(t,"videoTransport")||qt(s,"videoTransport","activeTransport")||[S,k].filter(Boolean).join("-")).toLowerCase(),j=/(?:^|[-_])ws(?:$|[-_])|websocket/.test(T)||/(?:^|[-_])ws(?:$|[-_])|websocket/.test(b),N=/relay/.test(T)||/relay/.test(b)?"encrypted-relay":/p2p|udp/.test(T)||b==="udp-p2p"?"p2p-udp":/direct|tcp|ws|websocket/.test(T)||b==="binary"||j?j?"direct-ws":"direct-tcp":"",P=(qt(y,g?"state":"frameTransportState")||qt(w,g?"frameTransportState":"state")||(N?"active":"")).toLowerCase(),H=qt(y,g?"reason":"frameTransportReason")||qt(w,g?"frameTransportReason":"reason"),F=g?u||l:l||u,$=dm(F),D=$===void 0?void 0:Math.max(0,r-$),K=D===void 0?"":D<1e3?"changed now":D<6e4?`changed ${Math.round(D/1e3)}s ago`:D<36e5?`changed ${Math.round(D/6e4)}m ago`:`changed ${F}`,z=g?s.switchCount??t?.frameTransportSwitchCount:t?.frameTransportSwitchCount??s.switchCount,q=g?s.tcpFailureCount??t?.frameTransportTcpFailureCount:t?.frameTransportTcpFailureCount??s.tcpFailureCount,W=g?typeof s.p2pReady=="boolean"?s.p2pReady:t?.frameTransportP2pReady===!0:typeof t?.frameTransportP2pReady=="boolean"?t.frameTransportP2pReady:s.p2pReady===!0;return{rawTransport:b,videoTransport:N,state:P,reason:H,changedAt:F,changedLabel:K,switchCount:Math.max(0,Number(z??0)||0),tcpFailureCount:Math.max(0,Number(q??0)||0),p2pReady:W}}function II(t,n,r){const s=xC(t,n,r),l=/(connecting|recovering|failed|error|degraded|unavailable)/.test(s.state);if(s.videoTransport==="encrypted-relay")return Xe("transport",l?"warning":"ok",l?"Encrypted TCP relay fallback needs attention":"Encrypted TCP relay fallback",l?`End-to-end encrypted TCP relay is ${s.state||"not ready"}; open Debug Status for the technical reason${s.changedLabel?` · ${s.changedLabel}`:""}.`:`End-to-end encrypted TCP relay fallback is active${s.changedLabel?` · ${s.changedLabel}`:""}.`);if(s.videoTransport==="p2p-udp")return Xe("transport",l?"warning":"ok",l?"P2P video connection needs attention":"P2P video connection",l?`Encrypted UDP P2P is ${s.state||"not ready"}; open Debug Status for the technical reason${s.changedLabel?` · ${s.changedLabel}`:""}.`:`Encrypted UDP P2P fallback is active${s.changedLabel?` · ${s.changedLabel}`:""}.`);if(s.videoTransport==="direct-tcp"||s.videoTransport==="direct-ws"){const u=s.videoTransport==="direct-ws"?"WebSocket":"TCP";return Xe("transport",l?"warning":"ok",l?"Direct video connection needs attention":"Direct video connection",l?`Direct ${u} to Hub is ${s.state||"not ready"}; open Debug Status for the technical reason${s.changedLabel?` · ${s.changedLabel}`:""}.`:`Direct ${u} to Hub is active${s.changedLabel?` · ${s.changedLabel}`:""}.`)}return Xe("transport","warning","Video transport is not identified",s.reason||"Waiting for Direct TCP, encrypted UDP P2P, or encrypted TCP relay transport data.")}const LI=Object.freeze(["nativeEncodeFramesInFlight","nativeEncodePendingFrameCount","nativeEncodeTimestampOwnerCount","nativeEncodeTimestampOwnerHighWatermark","nativeBackpressureCoalescedFrameCount","nativeBackpressureSkippedFrameCount","nativeEncodePendingReplacedFrameCount","nativeIdleSkippedFrameCount","nativeVideoToolboxActiveSessionCount","nativeVideoToolboxSessionHighWatermark","nativeOutputQueueDepth","nativeOutputQueueBytes","nativeOutputQueueOldestAgeMs","nativeOutputQueueHighWatermark","nativeOutputQueueDroppedCount","nativeAnnexBAccessUnitAllocationCount","nativeAnnexBPayloadCopyCount","nativeAnnexBPayloadCopiedBytes","nativeAndPipeResidenceAgeMs","pipePayloadAllocationCount","pipePayloadCopyCount","pipePayloadCopiedBytes","handoffDroppedFrameCount","handoffRecoveryKeyFrameRequestCount","handoffOldestFrameAgeMs"]);function SC(t){const r=String(t?.platformProfile||"").toLowerCase().includes("macos-screencapturekit"),s=Number(t?.nativeCaptureTelemetryVersion)>=5&&LI.every(u=>Mt(t,u)!==void 0)&&typeof t?.nativeOutputQueueAwaitingKeyFrame=="boolean"&&t?.nativeCopyTelemetryAvailable===!0,l=t?.nativeCaptureTelemetryAvailable===!0&&t?.nativeCaptureResourceTelemetryAvailable===!0&&s;return{required:r,available:l,pending:Math.max(0,Number(t?.nativeEncodePendingFrameCount||0)),timestampOwners:Math.max(0,Number(t?.nativeEncodeTimestampOwnerCount||0)),timestampOwnerHighWatermark:Math.max(0,Number(t?.nativeEncodeTimestampOwnerHighWatermark||0)),coalesced:Math.max(0,Number(t?.nativeBackpressureCoalescedFrameCount||0)),pendingReplaced:Math.max(0,Number(t?.nativeEncodePendingReplacedFrameCount||0)),vtActive:Math.max(0,Number(t?.nativeVideoToolboxActiveSessionCount||0)),vtHighWatermark:Math.max(0,Number(t?.nativeVideoToolboxSessionHighWatermark||0)),outputOldestAgeMs:Math.max(0,Number(t?.nativeOutputQueueOldestAgeMs||0)),nativeAndPipeResidenceAgeMs:Math.max(0,Number(t?.nativeAndPipeResidenceAgeMs||0)),handoffDropped:Math.max(0,Number(t?.handoffDroppedFrameCount||0)),handoffRecoveryRequests:Math.max(0,Number(t?.handoffRecoveryKeyFrameRequestCount||0)),handoffOldestAgeMs:Math.max(0,Number(t?.handoffOldestFrameAgeMs||0)),annexBAllocations:Math.max(0,Number(t?.nativeAnnexBAccessUnitAllocationCount||0)),annexBPayloadCopies:Math.max(0,Number(t?.nativeAnnexBPayloadCopyCount||0)),annexBPayloadCopiedBytes:Math.max(0,Number(t?.nativeAnnexBPayloadCopiedBytes||0)),pipePayloadAllocations:Math.max(0,Number(t?.pipePayloadAllocationCount||0)),pipePayloadCopies:Math.max(0,Number(t?.pipePayloadCopyCount||0)),pipePayloadCopiedBytes:Math.max(0,Number(t?.pipePayloadCopiedBytes||0))}}function PI(t){const n=String(t?.frameMode||t?.mode||t?.codec||"").toLowerCase(),r=[t?.hardwareEncoder,t?.platformProfile].filter(Boolean).join(" · "),s=gC(t,"nativeEncoderHardwareAccelerated"),l=t?.nativeEncoderHardwareAccelerationKnown===!0||s!==void 0,u=SC(t);return!t||!/h264/.test(n)?Xe("encoder","warning","Video encoder unavailable","Waiting for an H.264 frame."):u.required&&!u.available?Xe("encoder","warning","H.264 encoder resource status is unavailable",`${r||"Native encoder"} has not provided complete VideoToolbox v5 ownership, queue, and copy telemetry.`):u.required&&(u.vtActive!==1||u.vtHighWatermark>1||u.timestampOwners>2||u.timestampOwnerHighWatermark>2)?Xe("encoder","warning","VideoToolbox encoder ownership needs attention",`${u.vtActive} active session(s); high-water ${u.vtHighWatermark}; timestamp owners ${u.timestampOwners}/2 (HWM ${u.timestampOwnerHighWatermark})`):u.required&&u.coalesced>0?Xe("encoder","warning","Hardware H.264 encoding is under load",`${u.coalesced} current-window frame(s) were coalesced while the encoder was busy.`):l&&s===!1?Xe("encoder","warning","H.264 hardware acceleration is not active",`${r||"Native encoder"} is running without confirmed hardware acceleration.`):l&&s===!0?Xe("encoder","ok","Hardware H.264 encoding",`${r||"Native encoder"} · hardware acceleration confirmed`):TI.test(r)?Xe("encoder","ok","Hardware H.264 encoding",r):NI.test(r)?Xe("encoder","warning","Software H.264 encoding",`${r||"CPU encoder"} may limit frame rate.`):Xe("encoder","warning","H.264 encoder not identified",r||"The Client has not reported its active encoder profile.")}function _I({device:t,frame:n,receiveStat:r,paintStat:s,codec:l,selectedMonitorIndex:u=0,control:f=!1,controlInputReady:h=!1,controlBinding:g,hubRelay:y,capturePaused:w=!1,capturePauseConfirmed:b=!0,capturePauseError:S="",clientHeartbeatMs:k=5e3,now:A=Date.now()}={}){const T=pn(t),j=pn(T.status),I=pn(s?.lastInfo),N=[],P=wC(n,A);N.push(jI(T)),N.push(w?b?Xe("connection","ok","Video capture is paused","Client screen capture and video encoder shutdown were confirmed by the Client."):Xe("connection","warning","Video stop needs attention",String(S||"The Hub is blocking video restart, but the Client did not confirm screen capture and video encoder shutdown.")):T.connected===!0&&P<=Ft.frameAgeWarningMs?Xe("connection","ok","Video connection is current",`${Math.round(P)}ms since the latest frame.`):Xe("connection","warning",T.connected===!0?"Video frame is stale":"Client is offline",T.connected===!0&&Number.isFinite(P)?`${Math.round(P)}ms since the latest frame.`:String(T.lastDisconnectReason||"No current Client session."))),N.push(II(n,j,A)),N.push(PI(n));const H=vC(j.capture),F=pn(j.capture),$=yC({key:`${String(T.deviceId||T.id||"")}:capture-cleanup`,sampleId:qt(F,"sampledAt"),mismatch:H.helperLedgerMismatch||H.utilityLedgerMismatch});(H.helperQuarantineCount>0||H.utilityQuarantineCount>0||$.confirmed)&&N.push(Xe("capture-cleanup","warning","Video capture cleanup needs attention",`capture quarantine ${H.helperQuarantineCount} · utility quarantine ${H.utilityQuarantineCount} · owned I/O ${H.helperOwnedIoTaskCount+H.utilityOwnedIoTaskCount} · exit observers ${H.helperOwnedExitObserverCount} · undisposed processes ${H.helperUndisposedProcessCount+H.utilityUndisposedProcessCount}`));const D=Math.max(0,Number(n?.requestedFps||n?.effectiveFps||0)),K=Math.max(0,Number(r?.framesPerSecond||0));Math.max(0,Number(n?.sourceGapMs||0));const z=Math.max(0,Number(n?.nativeCaptureFps||0)),q=Math.max(0,Number(n?.nativeEncodedFps||0)),W=Math.max(0,Number(n?.nativeCaptureSampleCount||0)),Y=Math.max(0,Number(n?.nativeCaptureTelemetryVersion||0)),V=Mt(n,"nativeCaptureTelemetryAgeMs"),ee=Math.max(0,Number(V||0))+(Number.isFinite(P)?P:0),U=Y<2||V!==void 0&&ee<=Ft.nativeTelemetryStaleMs,L=Math.max(0,Number(n?.nativeBackpressureSkippedFrameCount||0)),le=Math.max(0,Number(n?.nativeIdleSkippedFrameCount||0)),ve=n?.nativeCaptureTelemetryAvailable===!0&&W>0&&U,J=Mt(n,"captureP95Ms","captureAverageMs","captureStageMs"),Ae=Math.max(0,Number(J||0)),ce=n?.captureTimingAvailable===!0&&D>0&&Number(r?.sampleMs||0)>0&&J!==void 0,Te=ce||ve,Fe=Math.max(Ft.minimumCaptureBudgetMs,D>0?1e3/D*Ft.captureBudgetMultiplier:0),$e=D>0?1e3/D:100,Ze=D>0&&z>=D*Ft.receiveRatioWarning,de=q>0&&q<D*Ft.receiveRatioWarning,Be=ve&&Ze&&de&&q>=1&&le>=Math.max(10,z*.6)&&L===0,Ve=ve&&D>0&&(z<D*Ft.receiveRatioWarning||!Be&&q>0&&q<D*Ft.receiveRatioWarning),Je=ve?Ve:ce&&Ae>Fe;N.push(Te?Je?Xe("capture","warning","Screen capture cannot keep target speed",ve?`${z.toFixed(1)} native capture · ${q.toFixed(1)} encoded · ${D||"?"} requested fps`:`${Ae?`capture p95 ${Math.round(Ae)}ms`:"capture timing unavailable"} · ${K.toFixed(1)}/${D||"?"} fps`):Xe("capture","ok","Screen capture speed is healthy",ve?`${z.toFixed(1)} native capture · ${q.toFixed(1)} encoded · ${D||"?"} requested fps${Be?" · idle optimized":""}`:`${Ae?`capture p95 ${Math.round(Ae)}ms`:"no slow capture reported"}${D?` · ${K.toFixed(1)}/${D} fps`:""}`):Xe("capture","warning","Screen capture data is still collecting","A current frame-rate and capture-time sample is required."));const Qe=Mt(n,"hubPacketTransitAgeMs"),yt=Math.max(0,Number(Qe||0)),ne=Math.max(0,Number(n?.agentSendGapMs||0)),me=Math.max(0,Number(n?.agentSendDurationMs||0)),Ge=!EI(T.remoteAddress),Se=Ai(j,"network.usageRatio"),ge=Mt(j,"network.latencyMs"),Ue=(Se??0)>=Ft.networkUsageWarningRatio||(ge??0)>=Ft.networkLatencyWarningMs,Me=n?.hubClientQueueTelemetryAvailable===!0||Mt(n,"hubClientDropped")!==void 0&&Mt(n,"hubClientQueueDepth")!==void 0&&Mt(n,"hubClientQueueLimit")!==void 0&&Mt(n,"hubClientBufferedBytes")!==void 0,rt=Me?Math.max(0,Number(n?.hubClientQueueDepth||0)):0,At=Me?Math.max(0,Number(n?.hubClientQueueLimit||0)):0,O=Me&&At>0&&rt>=At,qe=Qe!==void 0&&Number(r?.sampleMs||0)>0,B=!Be&&D>0&&Number(r?.sampleMs||0)>0&&K<D*Ft.deliveryRatioWarning,Oe=!Be&&ne>Math.max(Ft.networkDelayWarningMs,$e*3),We=yt>Ft.networkDelayWarningMs||Oe||me>Ft.networkDelayWarningMs||B||P>Ft.frameAgeWarningMs||Ue||O;N.push(qe?We||Ge?Xe("network","warning",Ge?"External network route may add delay":Ue?"Client network adapter needs attention":O?"Hub browser video queue needs attention":"Video delivery is uneven",[yt?`${Math.round(yt)}ms Hub-to-browser`:"",ne?`${Math.round(ne)}ms Client send gap`:"",me?`${Math.round(me)}ms Client send time`:"",B?`${K.toFixed(1)} of ${D} requested fps`:"",ge!==void 0?`${Math.round(ge)}ms Client network latency`:"",Se!==void 0?`${Math.round(Se*100)}% Client link use`:"",Me&&At>0?`Hub queue ${rt}/${At}`:"",Ge?String(T.remoteAddress||"external route"):""].filter(Boolean).join(" · ")||"Frame delivery is not current."):Xe("network","ok","Network delivery is healthy",`${Math.round(yt)}ms Hub-to-browser · ${Be?`idle optimized at ${q.toFixed(1)} fps`:"the current video rate is on target."}`):Xe("network","warning","Network delivery data is still collecting","A calibrated Hub-to-browser transit sample is required."));const et=Ai(j,"cpu.usageRatio","cpu.usedRatio","cpu.percent"),it=Ai(j,"memory.usedRatio","usedMemRatio"),ye=Ai(j,"gpu.usageRatio"),Ne=Ai(j,"gpu.memory.usedRatio"),He=Mt(j,"gpu.temperatureC","thermal.gpuC"),pe=et!==void 0&&it!==void 0,ae=dm(T.lastStatusAt),fe=ae===void 0?Number.POSITIVE_INFINITY:Math.max(0,A-ae),Ee=Math.max(Ft.minimumClientStatusFreshMs,Math.max(1e3,Number(k||0))*Ft.clientStatusFreshMultiplier),je=fe<=Ee,De=(et??0)>=Ft.cpuWarningRatio||(it??0)>=Ft.memoryWarningRatio||(ye??0)>=Ft.gpuWarningRatio||(Ne??0)>=Ft.gpuMemoryWarningRatio||(He??0)>=Ft.gpuTemperatureWarningC;N.push(pe?je?De?Xe("computer","warning",(ye??0)>=Ft.gpuWarningRatio||(Ne??0)>=Ft.gpuMemoryWarningRatio||(He??0)>=Ft.gpuTemperatureWarningC?"Client GPU is under load":"Client computer is under load",[`CPU ${Math.round(et*100)}%`,`memory ${Math.round(it*100)}%`,ye!==void 0?`GPU ${Math.round(ye*100)}%`:"",Ne!==void 0?`GPU memory ${Math.round(Ne*100)}%`:"",He!==void 0?`GPU ${Math.round(He)}C`:""].filter(Boolean).join(" · ")):Xe("computer","ok","Client computer has working capacity",[`CPU ${Math.round(et*100)}%`,`memory ${Math.round(it*100)}%`,ye!==void 0?`GPU ${Math.round(ye*100)}%`:""].filter(Boolean).join(" · ")):Xe("computer","warning","Client performance snapshot is stale",Number.isFinite(fe)?`The latest CPU and memory report is ${Math.round(fe/1e3)} seconds old.`:"No current Client performance heartbeat has been received."):Xe("computer","warning","Client performance data is unavailable","CPU and memory telemetry have not been reported yet."));const Et=Number(n?.monitorIndex),at=Number.isInteger(Et)&&Et===Number(u),ft=pn(T.channels),jt=pn(T.capabilities),Ut=ft.input!==!1&&jt.remoteInput!==!1&&jt.accessibilityPermission!==!1,wt=jt.screenRecordingPermission!==!1,Wt=pn(g),gt=!f||String(n?.sessionId||"")&&String(n?.sessionId||"")===String(Wt.sessionId||"")&&String(n?.commandId||"")&&String(n?.commandId||"")===String(Wt.commandId||"")&&Number(n?.captureGeneration||0)>0&&Number(n?.captureGeneration||0)===Number(Wt.captureGeneration||0)&&Number(n?.monitorIndex)===Number(Wt.monitorIndex),yn=!f||h&&gt;N.push(at&&yn&&Ut&&wt?Xe("display","ok",f?"Display and remote input are bound":"Display and remote input are available",`Display ${Number(u)+1} · generation ${Number(n?.captureGeneration||0)||"current"}.`):Xe("display","warning",wt?Ut?f?"Remote input is not bound to this display":"Waiting for the selected display":"Remote input permission is missing":"Screen capture permission is missing",`Selected display ${Number(u)+1}; latest frame ${Number.isInteger(Et)?Et+1:"not available"}.`));const mt=pn(l),ha=Array.isArray(mt.canvases)?pn(mt.canvases[0]):{},hn=Math.max(0,Number(s?.decoderInputFps||0)),na=Math.max(0,Number(s?.decoderOutputFps||0)),za=hn>0&&Number(s?.sampleMs||r?.sampleMs||0)>0,ot=K>0&&Number(r?.sampleMs||0)>0&&Number(s?.sampleMs||0)>0&&hn<K*Ft.decoderInputRatioWarning,Pt=hn>0?na/hn:0,an=qt(ha,"configuredAcceleration","requestedAcceleration")||qt(I,"h264DecodeAcceleration"),Dr=qt(ha,"softwareFallbackReason"),_t=!!Dr||an==="prefer-software";return N.push(ot?Xe("decoder","warning","Browser decoder input is dropping frames",`${K.toFixed(1)} received / ${hn.toFixed(1)} decoder input / ${na.toFixed(1)} output fps.`):za?_t||Pt<Ft.decoderOutputRatioWarning?Xe("decoder","warning",_t?"Browser is using software H.264 fallback":"Browser decoder output is slow",`${Dr||String(I.decoderLabel||an||"decoder")} · ${hn.toFixed(1)} in / ${na.toFixed(1)} out fps.`):Xe("decoder","ok",an==="prefer-hardware"?"Browser requests hardware H.264":"Browser H.264 path is responsive",`${hn.toFixed(1)} in / ${na.toFixed(1)} out fps. Chrome does not expose definitive hardware acceptance.`):Xe("decoder","warning","Browser decoder data is still collecting","Decoder input and output samples are required before this path can be marked healthy.")),N}function oo(t){const n=String(t||"").trim();return n?n.length<=14?n:`${n.slice(0,6)}…${n.slice(-5)}`:"-"}function Rn(t,n=1){const r=Number(t);return Number.isFinite(r)?r.toFixed(n):"-"}function OI({device:t,frame:n,receiveStat:r,paintStat:s,codec:l,selectedMonitorIndex:u=0,control:f=!1,controlInputReady:h=!1,controlBinding:g,hubRelay:y,now:w=Date.now()}={}){const b=pn(t),S=pn(b.status),k=pn(S.runtimeProcess),A=pn(S.capture),T=vC(A),j=pn(g),I=pn(s?.lastInfo),N=pn(l),P=Array.isArray(N.canvases)?pn(N.canvases[0]):{},H=[],F=Number(u),$=Number(n?.monitorIndex),D=Number.isInteger($)&&$===F,K=Number(n?.captureGeneration||0),z=Number(j.captureGeneration||0),q=!f||D&&String(n?.sessionId||"")===String(j.sessionId||"")&&String(n?.commandId||"")===String(j.commandId||"")&&K>0&&K===z,W=Math.max(0,Number(n?.requestedFps||n?.effectiveFps||0)),Y=Math.max(0,Number(r?.framesPerSecond||0)),V=Math.max(0,Number(s?.framesPerSecond||0)),he=Math.max(0,Number(s?.decoderInputFps||0)),ee=Math.max(0,Number(s?.decoderOutputFps||0)),U=Number(r?.sampleMs||0)>0&&Number(s?.sampleMs||0)>0,L=W>0&&U&&Math.min(Y,V||Y,ee||Y)<W*Ft.deliveryRatioWarning,le=Math.max(0,Number(n?.sourceGapMs||0)),ve=Math.max(0,Number(n?.agentSendGapMs||0)),J=Math.max(0,Number(n?.agentSendDurationMs||0)),Ae=Math.max(0,Number(n?.agentSendDurationFrameSeq||0)),ce=Math.max(0,Number(n?.agentQueueBeforePaceMs||0)),Te=Math.max(0,Number(n?.agentFrameAgeMs||0)),Fe=Mt(n,"hubPacketTransitAgeMs"),$e=Math.max(0,Number(n?.droppedByAgent||0)),Ze=Math.max(0,Number(n?.hubIngressDropped||0)),de=n?.hubClientQueueTelemetryAvailable===!0||Mt(n,"hubClientDropped")!==void 0&&Mt(n,"hubClientQueueDepth")!==void 0&&Mt(n,"hubClientQueueLimit")!==void 0&&Mt(n,"hubClientBufferedBytes")!==void 0,Be=de?Math.max(0,Number(n?.hubClientDropped||0)):0,Ve=de?Math.max(0,Number(n?.hubClientQueueDepth||0)):0,Je=de?Math.max(0,Number(n?.hubClientQueueLimit||0)):0,Qe=de?Math.max(0,Number(n?.hubClientBufferedBytes||0)):0,yt=Math.max(0,Number(n?.udpIncompleteFrames||0)),ne=$e+Ze+Be,me=wC(n,w),Ge=qt(P,"configuredAcceleration","requestedAcceleration")||qt(I,"h264DecodeAcceleration"),Se=qt(P,"softwareFallbackReason"),ge=Math.max(0,Number(N.hardwareReleaseGeneration||0)),Ue=Math.max(0,Number(N.hardwareRecoveryProbeCount||0)),Me=Number(N.lastHardwareRecoveryProbeAt),rt=Number.isFinite(Me)&&Me>0?Math.max(0,w-Me):void 0,At=`hardware releases ${ge} · recovery probes ${Ue} · last probe ${rt===void 0?"-":`${Math.round(rt)}ms ago`}`,O=U&&Y>0&&he<Y*Ft.decoderInputRatioWarning,qe=xC(n,S,w),B=qt(b,"deviceId")||qt(n,"deviceId"),Oe=qt(n,"sessionId")||qt(b,"sessionId"),We=qt(b,"productVersion")||qt(S,"productVersion","runtime.productVersion"),et=qt(b,"agentVersion")||qt(S,"agentVersion","runtime.agentVersion"),it=Mt(b,"pid","runtimePid")??Mt(S,"pid","runtimePid","process.pid"),ye=Mt(k,"pid"),Ne=Ai(k,"cpuUsageRatio"),He=Mt(k,"cpuCorePercent"),pe=Mt(k,"workingSetBytes"),ae=Mt(k,"privateMemoryBytes"),fe=Math.max(pe||0,ae||0),Ee=(ye??0)>0&&(pe??0)>0,je=Ee&&(it??0)>0&&ye!==it,De=(Ne??0)>=Ft.runtimeProcessCpuWarningRatio||fe>=Ft.runtimeProcessMemoryWarningBytes,Et=Ai(S,"cpu.usageRatio"),at=Ai(S,"memory.usedRatio","usedMemRatio"),ft=Math.max(0,Number(Mt(A,"videoStreamCount")||0)),jt=Math.max(0,Number(Mt(A,"audioStreamCount")||0)),Ut=Mt(A,"helperCount"),wt=Math.max(0,Number(Ut||0)),Wt=Mt(A,"helperAliveCount"),gt=Wt===void 0?wt:Math.max(0,Number(Wt||0)),yn=Mt(A,"helperExitedOwnedCount"),mt=Math.max(0,Number(yn||0)),ha=Mt(A,"helperMaxConcurrent"),hn=Math.max(wt,Number(ha||0)),na=Array.isArray(A.helperPids)?A.helperPids.map(Li=>Number(Li)).filter(Li=>Number.isSafeInteger(Li)&&Li>0):[],za=Array.isArray(A.helperProfiles)?A.helperProfiles.map(Li=>String(Li||"").trim()).filter(Boolean).slice(0,4):[],G=Ai(A,"helperCpuUsageRatio"),ot=Mt(A,"helperCpuCorePercent"),Pt=Mt(A,"helperWorkingSetBytes"),an=Mt(A,"helperPrivateMemoryBytes"),Dr=Math.max(Pt||0,an||0),_t=Math.max(0,Number(Mt(A,"helperStartCount")||0)),vn=Math.max(0,Number(Mt(A,"helperStopCount")||0)),se=Ut!==void 0,ze=Wt!==void 0&&yn!==void 0,st=se&&_t>=vn&&(_t-vn!==wt||ze&&gt+mt!==wt),Lt=wt>1||gt>1||hn>1||ft>1||st||T.currentProblem,Sn=se&&(ft>0&&gt===0||ft===0&&gt>0),on=yC({key:B&&Oe?`${B}:${Oe}`:"",sampleId:qt(A,"sampledAt"),mismatch:Sn}),xt=Sn&&!on.confirmed,Jt=Lt||on.confirmed,In=(G??0)>=Ft.captureHelperCpuWarningRatio||Dr>=Ft.captureHelperMemoryWarningBytes,zn=!!(B&&Oe&&We&&et&&(it??0)>0),Cn=n?.nativeCaptureTelemetryAvailable===!0,bn=Math.max(0,Number(n?.nativeCaptureTelemetryVersion||0)),kn=bn>=2,Ce=SC(n),Ln=!Ce.required||Ce.available,En=Mt(n,"nativeCaptureTelemetryAgeMs"),Un=Math.max(0,Number(En||0))+(Number.isFinite(me)?me:0),go=En===void 0?"-":`${Math.round(Un)}ms`,jn=!kn||En!==void 0&&Un<=Ft.nativeTelemetryStaleMs,ri=Cn&&!jn,vo=gC(n,"nativeEncoderHardwareAccelerated"),si=n?.nativeEncoderHardwareAccelerationKnown===!0||vo!==void 0,Ri=qt(n,"nativeEncoderHardwareQueryStatus"),yr=Ri==="0"?"confirmed":Ri,Da=Math.max(0,Number(n?.nativeCaptureDisplayId||0)),vs=Math.max(0,Number(n?.nativeCaptureFps||0)),br=Math.max(0,Number(n?.nativeCompressionOutputCount||0)),_s=Math.max(0,Number(n?.nativeCompressionFps||0)),ii=Math.max(0,Number(n?.nativeEncodedFps||0)),ln=kn||br>0?_s:ii,Ei=Math.max(0,Number(n?.nativeCaptureSampleCount||0)),nn=Math.max(0,Number(n?.nativeEncodableFrameCount||0)),oi=Math.max(0,Number(n?.nativeSkippedFrameCount||0)),wr=Math.max(0,Number(n?.nativeEncodedFrameCount||0)),Os=Math.max(0,Number(n?.nativeEncodeFramesInFlight||0)),xr=Ce.pending,Fs=Ce.timestampOwners,rl=Ce.timestampOwnerHighWatermark,qr=Ce.coalesced,Ir=Math.max(0,Number(n?.nativeBackpressureSkippedFrameCount||0)),Bs=Ce.pendingReplaced,hc=Math.max(0,Number(n?.nativeIdleSkippedFrameCount||0)),Wr=Ce.vtActive,gc=Ce.vtHighWatermark,yo=Math.max(0,Number(n?.nativeOutputQueueDepth||0)),Lr=Math.max(0,Number(n?.nativeOutputQueueBytes||0)),ys=Ce.outputOldestAgeMs,Cu=Math.max(0,Number(n?.nativeOutputQueueHighWatermark||0)),bs=Math.max(0,Number(n?.nativeOutputQueueDroppedCount||0)),Hs=n?.nativeOutputQueueAwaitingKeyFrame===!0,Ct=Ce.nativeAndPipeResidenceAgeMs,sl=Ce.handoffDropped,Kn=Ce.handoffRecoveryRequests,bo=Ce.handoffOldestAgeMs,Kt=Os>2||xr>1||Fs>2||rl>2||qr>0||Os>=2&&Ir>0,$a=Ce.required&&Ce.available&&(Wr!==1||gc>1||Fs>2||rl>2),wo=yo>=3||Lr>=6*1024*1024||ys>120||bs>0||Hs||Ct>250||sl>0||Kn>0||bo>120,Gr=`in-flight ${Os}/2 · backpressure skipped ${Ir} · idle skipped ${hc} · stdout queue ${yo} AU/${Math.round(Lr/1024)} KB/${Math.round(ys)}ms · HWM ${Cu} · dropped ${bs} · awaiting key ${Hs?"yes":"no"} · native+pipe ${Math.round(Ct)}ms · handoff ${Math.round(bo)}ms/drop ${sl}/recovery ${Kn}`,Vr=`pending ${xr}/1; timestamp owners ${Fs}/2 (HWM ${rl}); coalesced ${qr}; pending replaced ${Bs}; VideoToolbox ${Wr} active/HWM ${gc}`,$t=Ce.available&&Ce.annexBAllocations>0&&Ce.annexBPayloadCopies>=Ce.annexBAllocations&&Ce.annexBPayloadCopiedBytes>0&&Ce.pipePayloadAllocations>0&&Ce.pipePayloadCopies>=Ce.pipePayloadAllocations&&Ce.pipePayloadCopiedBytes>0,Ua=`Annex-B allocation/copy ${Ce.annexBAllocations}/${Ce.annexBPayloadCopies} (${Math.round(Ce.annexBPayloadCopiedBytes/1024)} KB) · pipe allocation/read ${Ce.pipePayloadAllocations}/${Ce.pipePayloadCopies} (${Math.round(Ce.pipePayloadCopiedBytes/1024)} KB)`,Pr=Cn&&Ei>0&&jn,ji=W>0?1e3/W:100,Di=W>0&&vs>=W*Ft.receiveRatioWarning,il=ln>0&&ln<W*Ft.receiveRatioWarning,Pn=Pr&&Di&&il&&ln>=1&&ii>=1&&hc>=Math.max(10,vs*.6)&&Ir===0,Qn=L&&!Pn,li=!Pn&&ve>Math.max(Ft.networkDelayWarningMs,ji*3),Kr=Pr&&W>0&&vs<W*Ft.receiveRatioWarning,ku=Pr&&!Pn&&vs>0&&(kn&&ln<=0||ln>0&&ln<vs*Ft.receiveRatioWarning),ol=Pr&&br>0&&ln>0&&ii<ln*Ft.receiveRatioWarning,vc=ri?"Native capture telemetry is stale":Ln?$a?"VideoToolbox encoder ownership needs attention":Pr?Kr?"Native screen capture is below request":ku||Kt?"VideoToolbox compression is behind capture":ol||wo?"Native stdout delivery is backpressured":vo===!1?"Native hardware encoder is unavailable":"Native capture or encoder needs attention":"Native capture telemetry is unavailable":"Native encoder resource telemetry is unavailable";H.push(DI(b,y)),H.push(zn?Xe("debug-runtime","ok",`LiveDesk ${We} · Agent ${et}`,`pid ${it} · session ${oo(Oe)} · device ${oo(B)}`):Xe("debug-runtime","warning","Runtime identity is incomplete",`LiveDesk ${We||"-"} · Agent ${et||"-"} · pid ${it??"-"} · session ${oo(Oe)} · device ${oo(B)}`)),H.push(Ee&&!je&&!De?Xe("debug-process-load","ok","RemoteFast process load is healthy",`pid ${ye} · CPU ${nc(Ne)} machine / ${$p(He)} core · RSS ${tc(pe)} · private ${tc(ae)} · system CPU ${nc(Et)} · memory ${nc(at)}`):Xe("debug-process-load","warning",Ee?je?"RemoteFast process identity does not match":"RemoteFast process load needs attention":"RemoteFast process telemetry is collecting",`runtime pid ${ye??"-"} · reported pid ${it??"-"} · CPU ${nc(Ne)} machine / ${$p(He)} core · RSS ${tc(pe)} · private ${tc(ae)} · system CPU ${nc(Et)} · memory ${nc(at)}`)),H.push(n?Xe("debug-frame","ok",`Frame #${Number(n.frameSeq||0)} · ${String(n.streamPurpose||(f?"control":"wall"))}`,`stream ${oo(n.streamId)} · ${n.width||0}x${n.height||0} · ${Math.round(Number(n.byteLength||0)/1024)} KB · age ${Number.isFinite(me)?Math.round(me):"-"}ms`):Xe("debug-frame","warning","No current frame",`Device ${oo(b.deviceId)} has not produced a frame.`));const xo=/(connecting|recovering|failed|error|degraded|unavailable)/.test(qe.state);H.push(qe.videoTransport&&!xo?Xe("debug-transport","ok",`${qe.videoTransport==="encrypted-relay"?"Encrypted TCP relay fallback":qe.videoTransport==="p2p-udp"?"P2P UDP":qe.videoTransport==="direct-ws"?"Direct WebSocket":"Direct TCP"} · ${qe.state||"active"}`,[`raw ${qe.rawTransport||"-"}`,`P2P ${qe.p2pReady?"ready":"standby unavailable"}`,`switch ${qe.switchCount}`,`TCP failure ${qe.tcpFailureCount}`,qe.changedLabel,qe.reason].filter(Boolean).join(" · ")):Xe("debug-transport","warning",qe.videoTransport?`Video transport ${qe.state||"needs attention"}`:"Video transport is not identified",[qe.videoTransport||"no active path",`raw ${qe.rawTransport||"-"}`,`P2P ${qe.p2pReady?"ready":"not ready"}`,qe.changedLabel,qe.reason].filter(Boolean).join(" · "))),H.push(D?Xe("debug-monitor","ok",`Monitor selected ${F+1} · frame ${$+1}`,`reported ${Number(n?.monitorCount||0)||"?"} displays · generation ${K||"-"}`):Xe("debug-monitor","warning",`Monitor mismatch: selected ${F+1} · frame ${Number.isInteger($)?$+1:"-"}`,`reported ${Number(n?.monitorCount||0)||"?"} displays · generation ${K||"-"}`)),H.push(q&&(!f||h)?Xe("debug-binding","ok",f?"Control generation is bound":"Wall capture generation is current",`session ${oo(n?.sessionId)} · command ${oo(n?.commandId)} · generation ${K||"-"}`):Xe("debug-binding","warning",f?"Control generation is not bound":"Wall capture generation is unavailable",`frame ${oo(n?.commandId)}/${K||"-"} · expected ${oo(j.commandId)}/${z||"-"} · input ${h?"ready":"waiting"}`)),H.push(U&&!Qn?Xe("debug-cadence","ok",`Cadence ${Rn(Y)} rx · ${Rn(V)} paint · ${Rn(ee)} decode`,`requested ${Rn(W)} · decoder input ${Rn(he)} fps · receive p95 ${Rn(r?.p95IntervalMs)}ms${Pn?" · idle optimized":""}`):Xe("debug-cadence","warning",U?"Frame cadence is below request":"Frame cadence sample is collecting",`requested ${Rn(W)} · receive ${Rn(Y)} · paint ${Rn(V)} · decode ${Rn(ee)} fps`)),H.push(Pr&&Ln&&!Kr&&!ku&&!ol&&!Kt&&!$a&&!wo&&vo!==!1?Xe("debug-native-capture","ok",`Native capture ${Rn(vs)} fps · compress ${Rn(ln)} fps · stdout ${Rn(ii)} fps${Pn?" · idle optimized":""}`,`telemetry v${bn||1} · age ${go} · hardware ${si?vo?"yes":"no":"unknown"}${yr?` (${yr})`:""} · display ${Da||"-"} · capture samples ${Ei} · encodable ${nn} · skipped ${oi} · compression outputs ${br} · stdout written ${wr} · ${Gr} · encoded AU output gap ${Math.round(le)}ms`):Xe("debug-native-capture","warning",vc,`telemetry ${Cn?`v${bn||1}`:"no"} · age ${go} · hardware ${si?vo?"yes":"no":"unknown"}${yr?` (${yr})`:""} · display ${Da||"-"} · capture ${Rn(vs)} fps · compress ${Rn(ln)} fps · stdout ${Rn(ii)} fps · capture samples ${Ei} · encodable ${nn} · skipped ${oi} · compression outputs ${br} · stdout written ${wr} · ${Gr} · encoded AU output gap ${Math.round(le)}ms`)),Ce.required&&(H.push(Ln&&!Kt&&!$a?Xe("debug-native-resource","ok","VideoToolbox resource ownership is bounded",Vr):Xe("debug-native-resource","warning",Ln?$a?"VideoToolbox session ownership is not exclusive":"VideoToolbox encode lane is coalescing":"VideoToolbox resource telemetry is unavailable",Vr)),H.push(Ln&&$t?Xe("debug-native-copy","ok","Capture copy accounting is current",Ua):Xe("debug-native-copy","warning",Ln?"Capture copy accounting needs attention":"Capture copy accounting is unavailable",Ua))),H.push(se&&!Jt&&!In?Xe("debug-capture-ownership","ok",xt?"Capture ownership transition is settling":gt>0?"Capture helper ownership is exclusive":"Capture helpers are idle",`video ${ft} · audio ${jt} · helpers ${wt} owned / ${gt} alive / ${mt} exiting (max ${hn||"-"}) · pid ${na.join(",")||"-"} · profile ${za.join(", ")||"-"} · CPU ${nc(G)} machine / ${$p(ot)} core · RSS ${tc(Pt)} · private ${tc(an)} · starts ${_t} / stops ${vn}${xt?` · mismatch samples ${on.count}/${Hv}`:""}`):Xe("debug-capture-ownership","warning",se?wt>1||gt>1||hn>1?"Duplicate capture helpers detected":Jt?"Capture stream and helper ownership do not match":"Capture helper load needs attention":"Capture process telemetry is collecting",`video ${ft} · audio ${jt} · helpers ${wt} owned / ${gt} alive / ${mt} exiting (max ${hn||"-"}) · pid ${na.join(",")||"-"} · profile ${za.join(", ")||"-"} · CPU ${nc(G)} machine / ${$p(ot)} core · RSS ${tc(Pt)} · private ${tc(an)} · starts ${_t} / stops ${vn}`));const Ii=`helper I/O ${T.helperOwnedIoTaskCount} | exit observers ${T.helperOwnedExitObserverCount} | undisposed ${T.helperUndisposedProcessCount} | quarantine ${T.helperQuarantineCount} | dispose failures ${T.helperDisposeFailureCount} | utility I/O ${T.utilityOwnedIoTaskCount} | undisposed ${T.utilityUndisposedProcessCount} | quarantine ${T.utilityQuarantineCount} | utility pid ${T.utilityQuarantinePids.join(",")||"-"} | profile ${T.utilityQuarantineProfiles.join(", ")||"-"} | utility starts ${T.utilityQuarantineStartCount} / stops ${T.utilityQuarantineStopCount} | dispose failures ${T.utilityDisposeFailureCount}${T.helperLastDisposeFailure?` | helper last ${T.helperLastDisposeFailure}`:""}${T.utilityLastDisposeFailure?` | utility last ${T.utilityLastDisposeFailure}`:""}`;H.push(T.telemetryAvailable&&!T.currentProblem&&!T.historicalCleanupFailure?Xe("debug-capture-cleanup","ok",wt>0?"Capture cleanup ownership is exact":"Capture cleanup is idle",Ii):Xe("debug-capture-cleanup","warning",T.telemetryAvailable?T.currentProblem?"Capture cleanup is quarantined or mismatched":"Capture cleanup recorded a disposal failure":"Capture cleanup telemetry is collecting",Ii)),H.push(de?ne===0&&yt===0&&(Je<=0||Ve<Je)&&!li&&J<=Ft.networkDelayWarningMs&&Te<=Ft.networkDelayWarningMs&&(Fe===void 0||Fe<=Ft.networkDelayWarningMs)?Xe("debug-delivery","ok","Delivery counters are clear",`encoded AU output gap ${Math.round(le)}ms · Client send gap ${Math.round(ve)}ms · Client send time ${Math.round(J)}ms (frame ${Ae||"-"}) · Agent queue ${Math.round(ce)}ms · Agent age ${Math.round(Te)}ms · Agent drop ${$e} · Hub transit ${Fe===void 0?"-":Math.round(Fe)}ms · Hub ingress drop ${Ze} · browser queue drop ${Be} (${Ve}/${Je||"-"}) · buffered ${Math.round(Qe/1024)} KB · UDP incomplete ${yt}${Pn?" · idle optimized":""}`):Xe("debug-delivery","warning","Delivery counters show loss or delay",`encoded AU output gap ${Math.round(le)}ms · Client send gap ${Math.round(ve)}ms · Client send time ${Math.round(J)}ms (frame ${Ae||"-"}) · Agent queue ${Math.round(ce)}ms · Agent age ${Math.round(Te)}ms · Agent drop ${$e} · Hub transit ${Fe===void 0?"-":Math.round(Fe)}ms · Hub ingress drop ${Ze} · browser queue drop ${Be} (${Ve}/${Je||"-"}) · buffered ${Math.round(Qe/1024)} KB · UDP incomplete ${yt}`):Xe("debug-delivery","warning","Browser queue counters are available in Hub Status",`encoded AU output gap ${Math.round(le)}ms · Client send gap ${Math.round(ve)}ms · Agent drop ${$e} · Hub ingress drop ${Ze} · per-browser lane counters are intentionally collected outside video packets.`));const yc=Mt(n,"captureP95Ms");return H.push(n?.captureTimingAvailable===!0&&yc!==void 0?Xe("debug-capture","ok",`Capture p95 ${Rn(yc)}ms · avg ${Rn(n?.captureAverageMs)}ms`,`stage ${Rn(n?.captureStageMs)}ms · slow ${Number(n?.slowFrameCount||0)} · helper restart ${Number(n?.captureHelperRestarts||0)} · source skip ${Number(n?.captureSourceSkipped||0)}`):Pr&&kn?Xe("debug-capture","ok","Capture latency is not instrumented; native cadence is current",`ScreenCaptureKit ${Rn(vs)} fps · VideoToolbox ${Rn(ln)} fps · stdout ${Rn(ii)} fps · telemetry age ${go}`):Xe("debug-capture","warning","Capture timing sample is unavailable",`stage ${Rn(n?.captureStageMs)}ms · helper restart ${Number(n?.captureHelperRestarts||0)} · source serial ${Number(n?.captureSourceSerial||0)}`)),H.push(!Se&&Ge!=="prefer-software"&&!O?Xe("debug-decoder","ok",`Decoder ${Ge||"acceleration unknown"}`,`${String(n?.frameMode||n?.codec||"-")} · ${String(n?.hardwareEncoder||"-")} · ${String(n?.platformProfile||"-")} · ${At}`):Xe("debug-decoder","warning",O?"Decoder input is losing received frames":"Decoder software fallback is active",O?`${Rn(Y)} received / ${Rn(he)} decoder input / ${Rn(ee)} output fps · ${At}`:`${Se||Ge||"software"} · ${Rn(he)} in / ${Rn(ee)} out fps · ${At}`)),H}function FI({status:t,deviceDiagnostics:n=[],codec:r,browser:s,frameStats:l}={}){const u=pn(t),f=pn(u.diagnostics),h=pn(f.system),g=pn(f.network),y=pn(r),w=pn(s),b=Array.isArray(n)?n:[],S=b.reduce((Te,Fe)=>Te+(Array.isArray(Fe)&&Fe.some($e=>$e?.state==="warning")?1:0),0),k=Ai(h,"cpuUsageRatio","processCpuRatio"),A=Ai(h,"memoryUsedRatio"),T=Mt(h,"totalMemoryBytes"),j=Mt(h,"cpuLogicalCores")??Mt(w,"hardwareConcurrency"),I=Mt(w,"deviceMemory"),N=(j??0)>0&&k!==void 0&&A!==void 0&&(T??0)>0,P=(T??0)>0&&T<Ft.hubMinimumTotalMemoryBytes,H=(I??0)>0&&I<Ft.hubMinimumBrowserMemoryGb,F=(j??0)>0&&j<4||(k??0)>=Ft.cpuWarningRatio||(A??0)>=Ft.memoryWarningRatio||P||H,$=Math.max(0,Number(y.activeSoftwareFallbackCount??y.softwareFallbackCount??0)),D=Math.max(0,Number(y.activeDecoderCount||0)),K=Math.max(0,Number(l?.bytesPerSecond||0)*8/1e6),z=Mt(g,"externalDeviceCount"),q=qt(g,"route"),W=z!==void 0&&!!q,Y=(z??0)>0||q==="external",V=pn(u.frameLanes),he=pn(V.packetFanout),ee=["packetBuilds","metadataSerializations","payloadCopyOperations","fanoutEligibleSubscribers"].every(Te=>Mt(he,Te)!==void 0),U=Array.isArray(V.clients)?V.clients.map(pn):[],L=Mt(V,"clientCount")!==void 0&&Array.isArray(V.clients)&&ee,le=U.some(Te=>{const Fe=Math.max(0,Number(Te.queueDepth||0)),$e=Math.max(0,Number(Te.queueLimit||0)),Ze=Math.max(0,Number(Te.queuedBytes||0)),de=Math.max(0,Number(Te.queueByteLimit||0));return Math.max(0,Number(Te.droppedPackets||0))>0||$e>0&&Fe>=$e||de>0&&Ze>=de||Array.isArray(Te.backpressuredDeviceIds)&&Te.backpressuredDeviceIds.length>0}),ve=Math.max(0,Number(he.packetBuilds||0)),J=Math.max(0,Number(he.metadataSerializations||0)),Ae=Math.max(0,Number(he.payloadCopyOperations||0)),ce=Math.max(0,Number(he.fanoutEligibleSubscribers||0));return[u.started&&!u.lastError?Xe("hub-runtime","ok","Hub runtime is ready",`${u.connectedDeviceCount||0} Clients connected.`):Xe("hub-runtime","warning","Hub runtime needs attention",String(u.lastError||"Hub is not ready.")),N?F?Xe("hub-computer","warning",P?"Hub has limited system memory":H?"Browser reports limited memory capacity":"Hub computer may limit remote performance",[`${j||"?"} logical cores`,`${_x(T)} RAM`,I!==void 0?`${I} GB browser memory class`:"",`CPU ${k===void 0?"?":Math.round(k*100)}%`,`memory ${A===void 0?"?":Math.round(A*100)}%`].filter(Boolean).join(" · ")):Xe("hub-computer","ok","Hub computer capacity is healthy",`${j||"?"} logical cores · ${_x(T)} RAM · CPU ${k===void 0?"not reported":`${Math.round(k*100)}%`}.`):Xe("hub-computer","warning","Hub performance data is unavailable","Logical-core, CPU, used-memory, and total-memory telemetry are required."),D<=0?Xe("hub-codec","warning","No active browser H.264 decoder to check","Open Wall or Control and wait for a video frame."):$>0?Xe("hub-codec","warning","Some browser decoders use software fallback",`${D} active H.264 decoders · ${$} software fallbacks. Chrome does not expose definitive hardware acceptance.`):Xe("hub-codec","ok","All active streams request hardware H.264",`${D} active decoders. Chrome hardware acceptance is inferred from health, not directly exposed.`),L?le?Xe("hub-frame-lanes","warning","A Hub browser video lane needs attention",`${U.length}/${V.clientCount||0} lanes reported · packet builds ${ve} · metadata serializations ${J} · payload copies ${Ae} · fanout deliveries ${ce}.`):Xe("hub-frame-lanes","ok","Hub browser video lanes are bounded",`${U.length}/${V.clientCount||0} lanes reported · packet builds ${ve} · metadata serializations ${J} · payload copies ${Ae} · fanout deliveries ${ce}.`):Xe("hub-frame-lanes","warning","Hub browser queue data is unavailable","Per-browser queue, drop, buffered-byte, and packet-allocation evidence is required."),S>0?Xe("hub-clients","warning",`${S} Clients need attention`,"Open the matching Wall slot lines for the exact cause."):Xe("hub-clients","ok","Connected Clients report healthy remote paths",`${b.length} Client reports checked.`),Xe("hub-network",!W||Y||K>120?"warning":"ok",W?Y?`${z} Clients use an external network route`:K>120?"Hub receive load is high":"Hub receive load is within range":"Hub network route data is unavailable",W?`${q.toUpperCase()} route · ${K.toFixed(K>=10?0:1)} Mbps received by this browser.`:"The Hub has not reported LAN/external route classification yet.")]}async function BI(t,n={}){const r=t.filter(b=>b.canvas&&b.canvas.width>0&&b.canvas.height>0),s=Math.max(320,n.maxWidth||1920),l=Math.max(180,n.maxHeight||1080),u=r.length<=1?1:r.length<=4?2:r.length<=9?3:4,f=Math.max(1,Math.ceil(Math.max(1,r.length)/u)),h=Math.floor(s/u),g=Math.floor(l/f),y=document.createElement("canvas");y.width=Math.max(320,h*u),y.height=Math.max(180,g*f);const w=y.getContext("2d",{alpha:!1});if(!w)return y;w.fillStyle="#0b1220",w.fillRect(0,0,y.width,y.height),w.font="600 14px system-ui, sans-serif",w.textBaseline="bottom";for(let b=0;b<r.length;b+=1){const S=r[b],k=b%u,A=Math.floor(b/u),T=k*h,j=A*g,I=S.canvas,N=Math.min(h/I.width,g/I.height),P=Math.max(1,Math.floor(I.width*N)),H=Math.max(1,Math.floor(I.height*N)),F=T+Math.floor((h-P)/2),$=j+Math.floor((g-H)/2);w.drawImage(I,F,$,P,H),n.includeLabels!==!1&&(w.fillStyle="rgba(4, 10, 20, .74)",w.fillRect(T,j+g-28,h,28),w.fillStyle="#f8fafc",w.fillText(S.label,T+9,j+g-9))}return y}function HI(t){return t?.signature||"none"}function zI(t){return t?.label||"No capture target"}function Fx(t){return{...t,deviceIds:[...t.deviceIds],sourceCanvas:t.sourceCanvas||null}}function $I(){const t=new Date,n=r=>String(r).padStart(2,"0");return`${t.getFullYear()}${n(t.getMonth()+1)}${n(t.getDate())}_${n(t.getHours())}${n(t.getMinutes())}${n(t.getSeconds())}`}function UI(t){return t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"Wall"}function qI(t){return`LiveDesk_${t.type==="wall"||t.type==="selection"?"Wall":`${UI(t.label)}_Monitor-${Number(t.monitorIndex||0)+1}`}_${$I()}.png`}async function WI(t,n,r){const s=await new Promise((u,f)=>t.toBlob(h=>h?u(h):f(new Error("Screenshot could not be encoded.")),"image/png")),l=await mC(s,{kind:"screenshot",fileName:qI(n),target:n},r);try{await navigator.clipboard.write([new ClipboardItem({"image/png":s})])}catch{}return l.capture}function CC(){return["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"].find(n=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(n))||""}function GI(t,n){const r=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","_"),s=n.label.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,70)||"Wall";return t==="timelapse"?`LiveDesk_Timelapse_${s}_${r}.webm`:`LiveDesk_Recording_${s}_${r}.webm`}async function kC(t){if(typeof MediaRecorder>"u"||typeof t.canvas.captureStream!="function")throw new Error("This browser does not support video recording.");const n=CC();if(!n)throw new Error("This browser does not support WebM recording.");const r=t.kind||"recording",s=await wI({kind:r,fileName:GI(r,t.target),mimeType:n,target:t.target},t.hubUrl),l=t.canvas.captureStream(t.frameRequests?0:t.fps),u=new MediaRecorder(l,{mimeType:n,videoBitsPerSecond:r==="timelapse"?2e6:4e6}),f=performance.now();let h=0,g=!1,y=null,w=Promise.resolve();return u.ondataavailable=b=>{if(!b.data||b.data.size===0)return;const S=h++;w=w.then(()=>xI(s.sessionId,S,b.data,t.hubUrl).then(()=>{})).catch(k=>{y=y||(k instanceof Error?k:new Error(String(k))),t.onError?.(y)})},u.onerror=()=>{y=new Error("Video recording stopped unexpectedly."),t.onError?.(y)},u.start(1e3),{requestFrame:()=>{l.getVideoTracks()[0]?.requestFrame?.()},stop:async()=>{if(!g){if(g=!0,await new Promise(b=>{u.addEventListener("stop",()=>b(),{once:!0}),u.stop()}),l.getTracks().forEach(b=>b.stop()),await w,y)throw await Ex(s.sessionId,t.hubUrl).catch(()=>{}),y;await SI(s.sessionId,Math.max(0,performance.now()-f),t.hubUrl)}},cancel:async()=>{g||(g=!0,u.stop(),l.getTracks().forEach(b=>b.stop()),await Ex(s.sessionId,t.hubUrl).catch(()=>{}))}}}class VI{recorder=null;stream=null;segments=[];totalBytes=0;targetSignature="";startedAt=0;maxDurationMs=3e4;maxBytes=128*1024*1024;get seconds(){return!this.startedAt||this.segments.length===0?0:Math.min(30,Math.max(0,(performance.now()-this.segments[0].at)/1e3))}get active(){return this.recorder!==null}async start(n,r){if(this.recorder&&this.targetSignature===r.signature)return;if(this.stop(),typeof MediaRecorder>"u"||typeof n.captureStream!="function")throw new Error("This browser does not support Last 30s.");const s=CC();if(!s)throw new Error("This browser does not support WebM recording.");this.targetSignature=r.signature,this.stream=n.captureStream(20),this.recorder=new MediaRecorder(this.stream,{mimeType:s,videoBitsPerSecond:3e6}),this.startedAt=performance.now(),this.recorder.ondataavailable=l=>{if(!l.data.size)return;const u=performance.now();for(this.segments.push({blob:l.data,at:u}),this.totalBytes+=l.data.size;this.segments.length>1&&(u-this.segments[0].at>this.maxDurationMs||this.totalBytes>this.maxBytes);){const f=this.segments.shift();this.totalBytes-=f.blob.size}},this.recorder.start(1e3)}stop(){const n=this.recorder;this.recorder=null,n&&n.state!=="inactive"&&(n.ondataavailable=null,n.stop()),this.stream?.getTracks().forEach(r=>r.stop()),this.stream=null,this.segments=[],this.totalBytes=0,this.startedAt=0}async save(n,r){if(this.segments.length===0)throw new Error("The Last 30s buffer is not ready yet.");const s=new Blob(this.segments.map(f=>f.blob),{type:this.segments[0].blob.type||"video/webm"}),u=`LiveDesk_Last30s_${n.label.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,70)||"Wall"}_${new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","_")}.webm`;return await mC(s,{kind:"last-30s",fileName:u,target:n,durationMs:Math.min(3e4,this.segments.length*1e3)},r)}}async function KI(t,n,r,s,l){const u=await kC({canvas:t,target:n,kind:"timelapse",fps:30,frameRequests:!0,hubUrl:s,onError:l});u.requestFrame?.();const f=window.setInterval(()=>u.requestFrame?.(),Math.max(5,r)*1e3);return{stop:async()=>{window.clearInterval(f),await u.stop()},cancel:async()=>{window.clearInterval(f),await u.cancel()}}}const MC="livedesk.captureSettings";function QI(){const t={rollingEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0};try{const n=JSON.parse(localStorage.getItem(MC)||"null");return{...t,...n&&typeof n=="object"?n:{}}}catch{return t}}function YI(t){const[n,r]=d.useState(QI),[s,l]=d.useState(0),[u,f]=d.useState(0),[h,g]=d.useState(0),[y,w]=d.useState(!1),b=d.useRef(void 0),S=d.useRef(!1),k=d.useRef(""),A=d.useRef(null),T=d.useRef(null),j=d.useRef(null),I=d.useRef(null),N=d.useRef(new VI),P=t.sourceRegistry.resolveCurrentTarget(),H=HI(P),F=zI(P),$=typeof MediaRecorder<"u"&&typeof HTMLCanvasElement<"u"&&"captureStream"in HTMLCanvasElement.prototype;d.useEffect(()=>{if(localStorage.setItem(MC,JSON.stringify(n)),!S.current)return;const le=JSON.stringify(n);le!==k.current&&(k.current=le,lt("/api/settings",{method:"PATCH",body:JSON.stringify({revision:b.current,filesAudio:{rollingBufferEnabled:n.rollingEnabled,recordingQuality:n.recordingQuality,timelapseIntervalSeconds:n.timelapseIntervalSeconds,includeRemoteCursor:n.includeRemoteCursor}})},t.hubUrl).then(ve=>{b.current=Number(ve.revision||b.current||0)}).catch(()=>{}))},[t.hubUrl,n]),d.useEffect(()=>{let le=!0;return lt("/api/settings",void 0,t.hubUrl).then(ve=>{if(!le)return;const J=ve.settings?.filesAudio||{},Ae=typeof J.rollingBufferEnabled=="boolean"?J.rollingBufferEnabled:n.rollingEnabled,ce=J.recordingQuality==="high"?"high":"standard",Te=[5,10,30,60].includes(Number(J.timelapseIntervalSeconds))?Number(J.timelapseIntervalSeconds):n.timelapseIntervalSeconds,Fe=typeof J.includeRemoteCursor=="boolean"?J.includeRemoteCursor:n.includeRemoteCursor,$e={rollingEnabled:Ae,recordingQuality:ce,timelapseIntervalSeconds:Te,includeRemoteCursor:Fe};b.current=Number(ve.revision||0),k.current=JSON.stringify($e),S.current=!0,r($e)}).catch(()=>{S.current=!0}),()=>{le=!1}},[t.hubUrl]);const D=d.useCallback(async le=>{if(le.sourceCanvas&&le.sourceCanvas.width>0&&le.sourceCanvas.height>0)return{target:Fx(le),canvas:le.sourceCanvas,cleanup:()=>{}};const ve=await t.sourceRegistry.composeWall(le.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0});let J=!1;const Ae=window.setInterval(async()=>{if(J)return;const ce=await t.sourceRegistry.composeWall(le.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0}).catch(()=>null);!ce||J||((ve.width!==ce.width||ve.height!==ce.height)&&(ve.width=ce.width,ve.height=ce.height),ve.getContext("2d")?.drawImage(ce,0,0))},100);return{target:Fx(le),canvas:ve,cleanup:()=>{J=!0,window.clearInterval(Ae)}}},[t.sourceRegistry]);d.useEffect(()=>{const le=N.current;if(!n.rollingEnabled||!P||!$){le.stop(),g(0);return}let ve=!1,J=null;return(async()=>{try{if(J=await D(P),ve)return;await le.start(J.canvas,J.target);const ce=window.setInterval(()=>g(Math.round(le.seconds)),500),Te=()=>{window.clearInterval(ce),J?.cleanup()};le.__cleanup=Te}catch(ce){ve||t.onToast(ce instanceof Error?ce.message:String(ce))}})(),()=>{ve=!0,le.stop(),le.__cleanup?.(),le.__cleanup=void 0,g(0)}},[D,t.onToast,n.rollingEnabled,H,$]);const K=d.useCallback(le=>r(ve=>({...ve,rollingEnabled:le})),[]),z=d.useCallback(le=>r(ve=>({...ve,recordingQuality:le})),[]),q=d.useCallback(le=>r(ve=>({...ve,timelapseIntervalSeconds:le})),[]),W=d.useCallback(async()=>{const le=t.sourceRegistry.resolveCurrentTarget();if(!le)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);let ve=null;try{ve=await D(le),await WI(ve.canvas,ve.target,t.hubUrl),t.onToast("Screenshot saved")}finally{ve?.cleanup(),w(!1)}},[D,t.hubUrl,t.onToast,t.sourceRegistry]),Y=d.useCallback(async()=>{if(j.current)throw new Error("Stop the timelapse before recording.");const le=t.sourceRegistry.resolveCurrentTarget();if(!le)throw new Error("화면이 준비된 후 다시 시도하세요.");const ve=await D(le),J=await kC({canvas:ve.canvas,target:ve.target,fps:le.type==="control"?30:15,hubUrl:t.hubUrl,onError:Ae=>t.onToast(Ae.message)});T.current=ve.cleanup,A.current=J,l(Date.now()),t.onToast("Recording started")},[D,t.hubUrl,t.onToast,t.sourceRegistry]),V=d.useCallback(async()=>{const le=A.current;if(le){w(!0);try{await le.stop(),t.onToast("Recording saved")}finally{A.current=null,T.current?.(),T.current=null,l(0),w(!1)}}},[t.onToast]),he=d.useCallback(async()=>{if(A.current||j.current)throw new Error("Last 30s is unavailable during a recording.");const le=t.sourceRegistry.resolveCurrentTarget();if(!le)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);try{await N.current.save(le,t.hubUrl),t.onToast("Last 30 seconds saved")}finally{w(!1)}},[t.hubUrl,t.onToast,t.sourceRegistry]),ee=d.useCallback(async()=>{if(A.current)throw new Error("Stop the recording before starting a timelapse.");const le=t.sourceRegistry.resolveCurrentTarget();if(!le)throw new Error("화면이 준비된 후 다시 시도하세요.");const ve=await D(le),J=await KI(ve.canvas,ve.target,n.timelapseIntervalSeconds,t.hubUrl,Ae=>t.onToast(Ae.message));I.current=ve.cleanup,j.current=J,f(Date.now()),t.onToast("Timelapse started")},[D,t.hubUrl,t.onToast,t.sourceRegistry,n.timelapseIntervalSeconds]),U=d.useCallback(async()=>{const le=j.current;if(le){w(!0);try{await le.stop(),t.onToast("Timelapse saved")}finally{j.current=null,I.current?.(),I.current=null,f(0),w(!1)}}},[t.onToast]);return d.useEffect(()=>{const le=ve=>{!A.current&&!j.current||(ve.preventDefault(),ve.returnValue="")};return window.addEventListener("beforeunload",le),()=>window.removeEventListener("beforeunload",le)},[]),d.useEffect(()=>()=>{N.current.stop(),A.current?.cancel(),j.current?.cancel(),T.current?.(),I.current?.()},[]),{state:d.useMemo(()=>({recording:!!A.current,recordingStartedAt:s,timelapse:!!j.current,timelapseStartedAt:u,bufferSeconds:h,bufferEnabled:n.rollingEnabled,busy:y,targetLabel:F}),[h,y,s,n.rollingEnabled,F,u]),settings:n,videoSupported:$,targetKey:H,setRollingEnabled:K,setRecordingQuality:z,setTimelapseInterval:q,takeScreenshot:W,startRecording:Y,stopRecording:V,saveLast30Seconds:he,startTimelapse:ee,stopTimelapse:U}}function XI(){if(typeof window>"u")return{isIos:!1,isAndroid:!1,isSafari:!1,browserName:"browser"};const t=window.navigator.userAgent,n=window.navigator.standalone,r=yN(t,window.navigator.platform,window.navigator.maxTouchPoints,n),s=/Android/i.test(t),l=r&&/CriOS/i.test(t),u=r&&/Safari/i.test(t)&&!/(CriOS|FxiOS|EdgiOS|OPiOS|DuckDuckGo)/i.test(t);return{isIos:r,isAndroid:s,isSafari:u,browserName:l?"Chrome":u?"Safari":"browser"}}const ZI=120,JI=999,Jf=5,em=30,eL=Number.POSITIVE_INFINITY,AC="livedesk.remoteDirectory",zv="livedesk.localHubAccessEnabled",tL="livedesk.streamSettings",nL=18,aL="livedesk.controlStreamSettings",rL=10,TC="livedesk.wallCadence",NC="livedesk.wallViewScale",RC="livedesk.mobileWallStatsVisible",sL=1e3,EC="livedesk.wallMonitorSelections",jC=2,Jg=512*1024,iL=!1;"".trim();"".trim();const oL=Object.freeze([{code:"ShiftLeft",label:"Shift"},{code:"ControlLeft",label:"Ctrl"},{code:"AltLeft",label:"Alt"},{code:"MetaLeft",label:"Win"}]),lL=1e3/60,ev=1500,cL=650,uL=1800,dL=650,fL=2500,tv=1500,Bx=15e3,Hx=120,zx=100,$x=20,mL=6e4,pL=6e4,Ux=240,hL=1024,gL=640,vL=360,qx="Connected LiveDesk clients are updating in batches. Hub will restart after every target reconnects on the requested versions.",Up="LiveDesk is replacing the Hub and verifying the requested version.",qp=5*6e4,yL=5e3,Wx=2e3,bL=8e3;function Gx(t,n){return`${t}:${n.deviceId}:${n.completedAt||n.candidateSessionId||n.commandId||"completed"}`}function iu({label:t,tooltip:n,disabled:r=!1,active:s=!1,danger:l=!1,pressed:u,onClick:f,children:h}){return o.jsx("span",{className:`manual-action-tooltip ${r?"disabled":""}`.trim(),"data-tooltip":n,children:o.jsx("button",{className:`manual-action ${s?"active":""} ${l?"danger":""}`.trim(),onClick:f,disabled:r,"aria-label":t,"aria-pressed":u,type:"button",children:h})})}function wL(t,n){if(n.deviceId!==t.deviceId)return!1;const r=Number(n.browserReceivedEpochMs);if(!Number.isFinite(r)||r<t.startedAtEpochMs)return!1;const s=Number(n.monitorIndex);if(Number.isFinite(s)&&Math.floor(s)!==t.monitorIndex)return!1;const l=String(n.frameMode||n.mode||"").trim().toLowerCase();return!l||l===t.frameMode}const ou={free:{name:"Free",price:"$0",limit:Jf,audience:"Personal trial",note:"5 devices with a standard ad banner."},ltd:{name:"Plus",price:"$79 LTD",ltd:"$79 LTD",limit:em,audience:"Creators and homelabs",note:"30 devices, no ads, personal use."},pro:{name:"Pro",price:"$199 LTD",ltd:"$199 LTD",limit:eL,audience:"Business and studios",note:"Commercial use and larger Client walls."}},xL={"mode3-h264-hw":30};function Vx(t,n){const r=f=>{const g=String(f||"").trim().replace(/^v/i,"").match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/);if(!g)return null;const y=g[4]?g[4].split(".").map(w=>/^\d+$/.test(w)?w.length>1&&w.startsWith("0")?Number.NaN:Number(w):w):[];return y.some(w=>typeof w=="number"&&!Number.isFinite(w))?null:{core:[Number(g[1]),Number(g[2]),Number(g[3])],prerelease:y}},s=r(t),l=r(n);if(!s||!l)return!1;for(let f=0;f<3;f+=1){if(s.core[f]>l.core[f])return!0;if(s.core[f]<l.core[f])return!1}if(s.prerelease.length===0||l.prerelease.length===0)return s.prerelease.length===0;const u=Math.max(s.prerelease.length,l.prerelease.length);for(let f=0;f<u;f+=1){const h=s.prerelease[f],g=l.prerelease[f];if(h===void 0||g===void 0)return g===void 0;if(h!==g){if(typeof h=="number"&&typeof g=="number")return h>g;if(typeof h=="number")return!1;if(typeof g=="number"||h>g)return!0;if(h<g)return!1}}return!0}const SL=512;function ma(t,n){return`${t}:${n}`}function lo(t){return[t.deviceId,t.sessionId||"",t.streamId||"",t.commandId||"",Number(t.captureGeneration||0),Number(t.monitorIndex??-1),t.streamPurpose||""].join("|")}const CL={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:xL["mode3-h264-hw"],maxWidth:1920,maxHeight:1080,atlasTileWidth:320,atlasTileHeight:180,atlasTileSizeMode:"auto",quality:75,autoStartLive:!0,showScreenStatus:!0,visibleOnlyLive:!0,adaptiveLoadShedding:!0,adaptiveSizeByWall:!0},kL={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:30,maxWidth:3840,maxHeight:2160,quality:75,showScreenStatus:!1},Kx={maxWidth:3840,maxHeight:2160};function Qf(t,n){if(t.length===0)return 0;const r=[...t].sort((l,u)=>l-u),s=Math.max(0,Math.min(r.length-1,Math.ceil(r.length*n)-1));return r[s]}function DC(t,n){t.push(n),t.length>Ux&&t.splice(0,t.length-Ux)}function Wp(t,n){t.sampleFrames=0,t.sampleStartedAt=n,t.intervalCount=0,t.intervalSumMs=0,t.minIntervalMs=Number.POSITIVE_INFINITY,t.maxIntervalMs=0,t.intervalSamplesMs.length=0,t.seqGapCount=0,t.maxSeqGap=0}function Qx(t,n,r){if(t.lastAt!==void 0){const s=Math.max(0,n-t.lastAt);t.intervalCount+=1,t.intervalSumMs+=s,t.minIntervalMs=Math.min(t.minIntervalMs,s),t.maxIntervalMs=Math.max(t.maxIntervalMs,s),DC(t.intervalSamplesMs,s)}if(t.lastFrameSeq!==void 0){const s=r-t.lastFrameSeq;s!==1&&(t.seqGapCount+=1,t.maxSeqGap=Math.max(t.maxSeqGap,Math.abs(s)))}t.lastAt=n,t.lastFrameSeq=r}function Yx(t){return!t||t.intervalCount<=0?"waiting":`${Math.round(t.averageIntervalMs)}ms avg / p95 ${Math.round(t.p95IntervalMs)}ms / max ${Math.round(t.maxIntervalMs)}ms`}function Xx(t){return!t||t.seqGapCount<=0?"none":`${t.seqGapCount} gaps / max ${t.maxSeqGap}`}function ML(t){return Number.isFinite(t)?String(t):"30+"}const IC=[1,2,5,8,12,20,30],Zx={large:{maxWidth:1920,maxHeight:1080},medium:{maxWidth:1280,maxHeight:720},list:{maxWidth:960,maxHeight:540}},Mi={visibleRootMargin:"520px 0px 760px 0px",fallbackVisibleCounts:{large:12,medium:18,list:32},maxWallBytesPerSecond:80*1024*1024,maxFrameGapMs:280,downshiftCooldownMs:1800,downshiftStableSampleMs:ta.adaptiveDownshiftStableMs,downshiftConsecutiveSamples:ta.adaptiveDownshiftConsecutiveSamples,recoveryCooldownMs:14e3,minFps:5},Jx=2200,AL=2500,TL=8e3,NL=3500,RL=7e3,EL=2,jL=2500,DL=7e3,IL=2600,LL=4200,PL=750,_L=2,e0=2500,t0=4200,n0=2200;function a0(t,n){return Math.min(3e4,t*2**Math.min(3,Math.max(0,n)))}function nh(t,n){const r=t.capabilities?.[n];return typeof r=="boolean"?r:/^(1|true|yes|on)$/i.test(String(r||"").trim())}function er(t){return t.deviceName||t.hostname||t.deviceId}function OL(){return"npx -y --prefer-online livedesk@latest client"}function FL(){return"npx -y --prefer-online livedesk@latest"}function BL(){try{return localStorage.getItem(AC)||""}catch{return""}}function HL(){try{return localStorage.getItem(zv)==="1"}catch{return!1}}function Ed(t){try{t?localStorage.setItem(zv,"1"):localStorage.removeItem(zv)}catch{}}function Ti(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function uo(t){const n=Ti(t.status),r=Ti(n.screens),s=Ti(t.capabilities),l=Ti(t.latestLiveFrame),u=Ti(t.activeLiveStream),h=[n.monitorCount,n.screenCount,r.count,s.monitorCount,s.screenCount,l.monitorCount,u.monitorCount,Array.isArray(r.displays)?r.displays.length:0,Array.isArray(n.displays)?n.displays.length:0,Array.isArray(n.monitors)?n.monitors.length:0].map(Number).filter(g=>Number.isFinite(g)&&g>0).map(g=>Math.max(1,Math.min(64,Math.floor(g))));return h.length>0?Math.max(...h):1}function oc(t){const n=Number(t);return Number.isFinite(n)&&n>0?Math.floor(n):0}function LC(t){const n=Ti(t.status),s=[Ti(n.screens).displays,n.displays,n.monitors];for(const l of s)if(!(!Array.isArray(l)||l.length===0))return l.map(u=>Ti(u));return[]}function by(t,n){const r=LC(t),s=r.find(g=>Number(g.index)===n)||r[n]||r[0]||{},l=oc(s.width),u=oc(s.height),f=[s.name,s.displayName,s.deviceName,s.id].find(g=>typeof g=="string"&&g.trim()),h=typeof f=="string"?f.trim():`Display ${n+1}`;return{index:n,name:h,width:l,height:u,primary:s.primary===!0||s.isPrimary===!0}}function zL(t){const n=uo(t);return Array.from({length:n},(r,s)=>by(t,s))}function $L(t){const n=LC(t);if(n.length===0)return"";const r=n.map((s,l)=>{const u=Number(s.index),f=[s.name,s.displayName,s.deviceName,s.id].find(g=>typeof g=="string"&&g.trim()),h=g=>{const y=Number(g);return Number.isFinite(y)?y:null};return[Number.isFinite(u)?Math.floor(u):l,typeof f=="string"?f.trim().toLowerCase():"",h(s.left),h(s.top),h(s.width),h(s.height),s.primary===!0||s.isPrimary===!0]}).sort((s,l)=>s[0]-l[0]);return JSON.stringify(r)}function UL(t){const n=[t.name||`Display ${t.index+1}`];return t.width>0&&t.height>0&&n.push(`${t.width}x${t.height}`),t.primary&&n.push("Primary"),n.join(" - ")}function PC(t,n){const r=by(t,n);if(r.width>0&&r.height>0)return{width:r.width,height:r.height};const s=Ti(t.status),l=oc(s.screenWidth||s.width),u=oc(s.screenHeight||s.height);return l>0&&u>0?{width:l,height:u}:null}function _C(t){if(!t)return null;const n=oc(t.sourceWidth)||oc(t.width),r=oc(t.sourceHeight)||oc(t.height);return n>0&&r>0?{width:n,height:r}:null}function qL(t,n,r){const u=((typeof n?.monitorIndex=="number"?tm(n.monitorIndex,Math.max(1,n.monitorCount||1)):r)===r?_C(n):null)||PC(t,r);return u?Math.max(.25,Math.min(4,u.width/u.height)):16/9}const Gp=16/9;function tm(t,n){const r=Math.max(1,Math.min(64,Math.floor(Number(n)||1))),s=Math.floor(Number(t));return Number.isFinite(s)?Math.max(0,Math.min(r-1,s)):0}function Ls(t,n){return uN(n,uo(t),t.platform)}function WL(){try{const t=localStorage.getItem(EC);if(!t)return{selections:{},topologyFingerprints:{}};const n=JSON.parse(t),r=n&&typeof n=="object"&&!Array.isArray(n)?n.selections:void 0;if(Number(n?.version)!==jC||!r||typeof r!="object"||Array.isArray(r))return{selections:{},topologyFingerprints:{}};const s={},l={};for(const[u,f]of Object.entries(r)){const h=u.trim(),g=Ti(f),y=g.monitorIndex,w=Math.floor(Number(y));if(!h||!Number.isFinite(w))continue;s[h]=Math.max(0,Math.min(63,w));const b=typeof g.topologyFingerprint=="string"?g.topologyFingerprint.trim():"";b&&(l[h]=b)}return{selections:s,topologyFingerprints:l}}catch{return{selections:{},topologyFingerprints:{}}}}function GL(t,n){try{const r=Object.fromEntries(Object.entries(t).map(([s,l])=>[s,{monitorIndex:l,topologyFingerprint:n[s]||""}]));localStorage.setItem(EC,JSON.stringify({version:jC,selections:r}))}catch{}}function VL(){return{...CL}}function KL(t){try{localStorage.setItem(tL,JSON.stringify({...t,version:nL}))}catch{}}function QL(){return{...kL}}function YL(t){try{localStorage.setItem(aL,JSON.stringify({...t,version:rL}))}catch{}}function XL(){try{return localStorage.getItem(TC)==="slow"?"slow":"fast"}catch{return"fast"}}function ZL(t){try{localStorage.setItem(TC,t)}catch{}}function JL(){try{return localStorage.getItem(RC)==="true"}catch{return!1}}function eP(t){try{localStorage.setItem(RC,String(t))}catch{}}function tP(){try{const t=localStorage.getItem(NC);return t===null?xu:xm(Number(t))}catch{return xu}}function nP(t){try{localStorage.setItem(NC,String(xm(t)))}catch{}}function nv(t,n){return t.length!==n.length?!1:t.every((r,s)=>r===n[s])}function av(t){return[...new Set(t.filter(Boolean))].sort()}function aP(t){return Mi.fallbackVisibleCounts[t]||Mi.fallbackVisibleCounts.large}function r0(t,n,r){if(t.frameMode==="mode4-h264-atlas")return t.atlasTileSizeMode==="auto"?n==="large"?{maxWidth:640,maxHeight:360}:{maxWidth:320,maxHeight:180}:{maxWidth:t.atlasTileWidth,maxHeight:t.atlasTileHeight};if(!t.adaptiveSizeByWall)return{maxWidth:t.maxWidth,maxHeight:t.maxHeight};const s=Zx[n]||Zx.large;return{maxWidth:Math.min(t.maxWidth,s.maxWidth),maxHeight:Math.min(t.maxHeight,s.maxHeight)}}function rP(t,n=Mi.minFps){const r=[...IC].sort((l,u)=>l-u),s=Math.max(n,Math.floor(t/2));return[...r].reverse().find(l=>l<t&&l>=n)||s}function sP(t,n){return[...IC].sort((s,l)=>s-l).find(s=>s>t&&s<=n)||n}function nm(t){if(!Number.isFinite(t)||t<=0)return"0 B";const n=["B","KB","MB","GB","TB"];let r=t,s=0;for(;r>=1024&&s<n.length-1;)r/=1024,s+=1;const l=s===0||r>=100?0:1;return`${r.toFixed(l)} ${n[s]}`}function s0(t){if(!Number.isFinite(t)||!t||t<=0)return"0GB";const n=1024**4,r=1024**3;return t>=n?`${Math.max(1,Math.round(t/n))}TB`:`${Math.max(1,Math.round(t/r))}GB`}function rv(t,n){if(!Number.isFinite(t)||!t||t<=0)return"not reported";const r=Math.max(0,t-Math.max(0,Number(n||0)));return`${s0(r)} / ${s0(t)}`}function iP(t){const n=new Uint8Array(t),r=32768;let s="";for(let l=0;l<n.length;l+=r){const u=n.subarray(l,l+r);s+=String.fromCharCode(...u)}return btoa(s)}function i0(t){return Array.from(t).filter(n=>n.size>=0).map(n=>{const r=n.webkitRelativePath||n.name;return{file:n,relativePath:r,fingerprint:`${n.size}:${n.lastModified}`}})}function oP(t){return t===1?"middle":t===2?"right":"left"}function o0(t,...n){for(const r of n){const s=t?.[r];if(typeof s=="string"&&s.trim())return s.trim()}return""}function l0(t){const n=Number(t);return Number.isInteger(n)&&n>=1&&n<=JI?n:0}const lP={cpu:"CPU",memory:"MEM",disk:"Disk",gpu:"GPU",vram:"VRAM",npu:"NPU",temp:"Temp",network:"Net"};function cP(t,n,r){if(t==="online")return"Online";if(t==="busy")return"Busy";if(t==="stale")return"Stale";if(t==="offline")return"Offline";if(r==="failed")return"Task failed";const s=t==="critical"?"critical":"warn",l=n.find(f=>f.state===s)||n.find(f=>f.state==="critical"||f.state==="warn");if(!l)return t==="critical"?"Issue":"Check";const u=lP[l.id]||l.label;return l.value&&l.value!=="-"?`${u} ${l.value}`:u}function OC(t,n){const r=n.split(".");let s=t;for(const l of r){if(s==null)return;if(Array.isArray(s)){const u=Number(l);s=Number.isInteger(u)?s[u]:void 0;continue}if(typeof s=="object"){s=s[l];continue}return}return s}function oa(t,...n){for(const r of n){const s=OC(t,r),l=Number(s);if(Number.isFinite(l))return l}}function co(t,...n){for(const r of n){const s=OC(t,r);if(typeof s=="string"&&s.trim())return s.trim();if(typeof s=="number"&&Number.isFinite(s))return String(s)}return""}function Jo(t){const n=Number(t);if(Number.isFinite(n))return Math.max(0,Math.min(1,n>1?n/100:n))}function sv(t,n){if(!(typeof t!="number"||typeof n!="number"||!Number.isFinite(t)||!Number.isFinite(n)||t<=0))return Jo((t-Math.max(0,n))/t)}function jd(t){return t===void 0?"-":`${Math.round(t*100)}%`}function iv(t){return t===void 0||!Number.isFinite(t)?"":t>=1e3?`${(t/1e3).toFixed(t>=1e4?0:1)}Gb/s`:`${Math.round(t)}Mb/s`}function lu(t,n=.92,r=.78){return t===void 0?"unknown":t>=n?"critical":t>=r?"warn":"good"}function uP(t){return!Number.isFinite(t)||!t||t<=0?"-":t<3600?`${Math.round(t/60)}m`:t<86400?`${Math.round(t/3600)}h`:`${Math.round(t/86400)}d`}function FC(t){const n=t.status||{},r=oa(n,"cpu.cores","cpuCores","processorCount"),s=oa(n,"loadavg.0","cpu.load1"),l=Jo(oa(n,"cpu.usedRatio","cpu.usageRatio","cpu.ratio","cpu.usedPct","cpu.usagePct","cpu.percent")??(r&&s!==void 0?s/Math.max(1,r):void 0)),u=oa(n,"memory.totalBytes","totalMem"),f=oa(n,"memory.freeBytes","freeMem"),h=Jo(oa(n,"memory.usedRatio","memory.usedPct","usedMemRatio"))??sv(u,f),g=oa(n,"disk.totalBytes","rootDisk.totalBytes","storage.totalBytes"),y=oa(n,"disk.freeBytes","rootDisk.freeBytes","storage.freeBytes"),w=Jo(oa(n,"disk.usedRatio","disk.usedPct","rootDisk.usedRatio","storage.usedRatio"))??sv(g,y),b=oa(n,"thermal.cpuC","temperatureC","cpu.temperatureC","gpu.temperatureC"),S=Jo(oa(n,"gpu.usedRatio","gpu.usageRatio","gpu.usedPct","gpu.usagePct","gpu.percent","accelerators.gpu.usageRatio")),k=co(n,"gpu.name","gpu.model","accelerators.gpu.name"),A=oa(n,"gpu.memory.totalBytes","gpu.totalMemoryBytes","gpu.vramTotalBytes"),T=oa(n,"gpu.memory.freeBytes","gpu.freeMemoryBytes","gpu.vramFreeBytes"),j=Jo(oa(n,"gpu.memory.usedRatio","gpu.vramUsedRatio"))??sv(A,T),I=oa(n,"gpu.temperatureC","thermal.gpuC"),N=Jo(oa(n,"npu.usedRatio","npu.usageRatio","npu.usedPct","npu.usagePct","npu.percent","accelerators.npu.usageRatio")),P=co(n,"npu.name","npu.model","accelerators.npu.name"),H=oa(n,"npu.tops","npu.topsInt8","accelerators.npu.tops"),F=oa(n,"network.rxMbps","network.receiveMbps","network.downMbps"),$=oa(n,"network.txMbps","network.transmitMbps","network.upMbps"),D=oa(n,"network.latencyMs","network.rttMs"),K=Jo(oa(n,"network.usedRatio","network.usageRatio","network.saturationRatio")),z=co(n,"network.link","network.interface","network.name"),q=Math.max(b??Number.NEGATIVE_INFINITY,I??Number.NEGATIVE_INFINITY),W=Number.isFinite(q)?q:void 0,Y=W===void 0?void 0:Jo((W-35)/60),V=b!==void 0&&I!==void 0?`CPU ${Math.round(b)}° · GPU ${Math.round(I)}°`:b!==void 0?`CPU ${Math.round(b)}°`:I!==void 0?`GPU ${Math.round(I)}°`:"-",he=co(n,"workload.role","role","lane")||(nh(t,"taskDispatch")?"Command-ready Client":"Local machine"),ee=co(t.latestTask,"status")||co(n,"workload.status")||"idle",U=co(t.latestTask,"title","instructionPreview")||co(n,"workload.title"),L=co(t.latestTask,"resultSummary","error","instructionPreview")||co(n,"workload.summary"),le=Date.parse(t.lastSeenAt||t.connectedAt||""),ve=Number.isFinite(le)?Date.now()-le:0;let J="online";t.connected?ve>5*6e4?J="stale":(b??0)>=86||(I??0)>=88||(l??0)>=.94||(S??0)>=.96||(j??0)>=.96||(N??0)>=.96||(h??0)>=.94||(w??0)>=.94||(D??0)>=200||ee==="failed"?J="critical":(b??0)>=78||(I??0)>=80||(l??0)>=.82||(S??0)>=.86||(j??0)>=.88||(N??0)>=.86||(h??0)>=.82||(w??0)>=.86||(D??0)>=80?J="warn":["queued","running","targeted"].includes(ee)&&(J="busy"):J="offline";const Ae=[{id:"cpu",label:"CPU",value:jd(l),detail:r?`${r} cores`:s!==void 0?`load ${s.toFixed(1)}`:"not reported",ratio:l,state:lu(l,.92,.78)},{id:"memory",label:"RAM",value:jd(h),detail:rv(u,f),ratio:h,state:lu(h,.92,.78)},{id:"disk",label:"DISK",value:jd(w),detail:rv(g,y),ratio:w,state:lu(w,.92,.82)},{id:"gpu",label:"GPU",value:jd(S),detail:k||(A&&T!==void 0?`${nm(T)} VRAM free`:I!==void 0?`${Math.round(I)}C`:"not reported"),ratio:S,state:I!==void 0&&I>=88?"critical":I!==void 0&&I>=80?"warn":lu(S,.96,.86)},{id:"vram",label:"VRAM",value:jd(j),detail:rv(A,T),ratio:j,state:lu(j,.96,.88)},{id:"npu",label:"NPU",value:N!==void 0?jd(N):H!==void 0?`${Math.round(H)} TOPS`:"-",detail:P||(H!==void 0?"neural engine":"not reported"),ratio:N,state:lu(N,.96,.86)},{id:"temp",label:"TEMP",value:V,detail:`uptime ${uP(oa(n,"uptimeSec"))}`,ratio:Y,state:W===void 0?"unknown":W>=86?"critical":W>=78?"warn":"good"},{id:"network",label:"NET",value:iv(F)||(D!==void 0?`${Math.round(D)}ms`:z||"-"),detail:iv($)?`${iv($)} up`:z||"not reported",ratio:K,state:D!==void 0&&D>=200?"critical":D!==void 0&&D>=80?"warn":lu(K,.9,.75)}];return{state:J,label:cP(J,Ae,ee),role:he,taskLabel:U||(ee==="idle"?"idle":ee),taskStatus:ee,taskSummary:L,metrics:Ae}}const dP=[{id:"slow",label:"Slow",fps:Iv("slow")},{id:"fast",label:"Fast",fps:Iv("fast")}],fP=[{id:"list",label:"List"},{id:"medium",label:"Small"},{id:"large",label:"Large"}],mP=[{id:"sync-server",label:"Hub",icon:mo,accent:"blue",tooltip:"hub"},{id:"wall",label:"Wall",icon:k0,accent:"blue",tooltip:"wall"},{id:"control",label:"Control",icon:Yf,accent:"red",tooltip:"control"},{id:"share-files",label:"Share Files",icon:sm,accent:"green",tooltip:"share-files"},{id:"agents",label:"Agents",icon:Kp,accent:"violet",tooltip:"agents"}],pP=[{id:"doc",label:"Doc",icon:ah,accent:"amber"},{id:"support",label:"Support",icon:am,accent:"violet"},{id:"pricing",label:"Pricing",icon:rm,accent:"green"}];function hP(t){return t.replaceAll("npx -y @livedesk/client","npx -y --prefer-online livedesk@latest client").replaceAll("npx @livedesk/client","npx -y --prefer-online livedesk@latest client").replaceAll("npx -y livedesk client","npx -y --prefer-online livedesk@latest client").replaceAll("npx livedesk client","npx -y --prefer-online livedesk@latest client").replaceAll("npx -y livedesk","npx -y --prefer-online livedesk@latest").replaceAll("npx livedesk","npx -y --prefer-online livedesk@latest")}function ea(t){return hP(t).replaceAll("Sync Server","Hub").replace(/\bRemoteHub\b/g,"Hub client endpoint").replace(/\bManagers\b/g,"Hubs").replace(/\bManager\b/g,"Hub").replace(/\bmanager\b/g,"Hub").replace(/\bMANAGER\b/g,"HUB").replace(/매니저/g,"Hub")}function cu(t){return t.map(n=>ea(n))}function Er(t){return{languageName:t.languageName,languageLabel:t.languageLabel,eyebrow:t.eyebrow,title:ea(t.title),intro:ea(t.intro),sections:[{title:ea(t.managerTitle),body:ea(t.managerBody),points:cu(t.managerPoints)},{title:ea(t.clientTitle),body:ea(t.clientBody),points:cu(t.clientPoints)},{title:ea(t.syncTitle),body:ea(t.syncBody),points:cu(t.syncPoints)},...t.agentTitle&&t.agentBody&&t.agentPoints?[{title:ea(t.agentTitle),body:ea(t.agentBody),points:cu(t.agentPoints)}]:[],{title:ea(t.platformTitle),body:ea(t.platformBody),points:cu(t.platformPoints)}],sync:{title:ea(t.syncTitle),body:ea(t.syncBody),points:cu(t.syncPoints)},firewall:{title:ea(t.firewallTitle),body:ea(t.firewallBody),points:cu(t.firewallPoints)},commands:{title:ea(t.commandsTitle),body:ea(t.commandsBody),manager:ea(t.managerCommandLabel),primary:ea(t.clientCommandLabel),slot:ea(t.slotCommandLabel),manual:ea(t.manualCommandLabel)}}}const Fd={ko:Er({languageName:"한국어",languageLabel:"문서 언어",eyebrow:"LiveDesk Manual",title:"한 줄로 여는 로컬 Screen Wall",intro:"LiveDesk는 매니저 PC 한 대에서 여러 작업 PC, 미니 PC, 맥미니, 개발 장비를 한 화면에 모니터링하고 필요한 제어를 실행하는 npm-first 원격 작업 데크입니다.",managerTitle:"1. 매니저 실행",managerBody:"화면을 모아 볼 컴퓨터에서 LiveDesk 매니저를 실행합니다. 매니저는 UI와 로컬 서버를 같이 열고 브라우저를 http://127.0.0.1:5179 로 띄웁니다.",managerPoints:["명령은 npx -y livedesk 입니다.","매니저는 Screen Wall/API 포트 5179와 클라이언트 접속 포트 5197을 사용합니다.","기존 LiveDesk 포트가 남아 있으면 기본적으로 정리하고 새로 시작합니다. 필요하면 --no-clean 을 붙입니다."],clientTitle:"2. 워크스테이션 연결",clientBody:"모니터링할 PC에서는 Google 로그인 또는 Hub 화면의 6자리 PIN으로 연결합니다. Hub가 꺼져 있으면 실시간 온라인 알림을 기다리고 적응형 간격으로 다시 확인합니다.",clientPoints:["빈 자리에 자동 배치하려면 npx -y livedesk client 를 실행합니다.","자리 번호를 고정하려면 npx -y livedesk client 3 처럼 번호를 붙입니다.","브라우저 연결 페이지에서 Google 버튼 또는 6자리 PIN 입력 중 하나를 선택합니다."],syncTitle:"3. Sync Server와 자동 발견",syncBody:"Sync Server는 이 매니저를 현재 계정의 활성 Screen Wall로 Supabase에 등록합니다. 클라이언트는 같은 Google 계정으로 로그인한 뒤 그 기록을 읽고 접속 후보들을 순서대로 시도합니다.",syncPoints:["등록 정보에는 host instance, LAN/private 주소, public 후보 주소, pair token, 짧은 lease가 포함됩니다.","같은 LAN 후보를 먼저 쓰고, 필요하면 외부 주소 후보를 시도합니다.","매니저 위치, VPN, 방화벽, 공유기 설정이 바뀌었거나 개발 중 활성 매니저를 바꿀 때 Sync Server를 누릅니다.","이제 livedesk.pages.dev의 Chrome Local Network Access 허용은 기본 실행 경로가 아닙니다. npm 매니저 앱이 실제 서버입니다."],agentTitle:"4. Agent로 여러 장비 작업하기",agentBody:"Agents 화면은 Hub에서 실행되는 Codex 기반 Agent가 연결된 장비를 확인하고, 선택한 권한 범위 안에서 작업을 실행하는 공간입니다. 클라이언트 PC에 Codex 앱이나 Codex SDK를 설치할 필요는 없습니다.",agentPoints:["Suggested tasks에는 일반적인 읽기·운영 명령 템플릿이 있으며, 검색과 권한·플랫폼·capability 조건으로 실행 가능 항목을 안내합니다.","Ask, Safe Auto, Full Access, Custom 권한 모드를 선택할 수 있습니다. 위험한 변경 작업은 승인 카드와 장비 capability 검사를 거칩니다.","All connected 또는 Selected로 대상 장비를 제한하고, 결과는 장비별 상태 칩과 실제 RAM·디스크·GPU·프로세스 요약으로 확인합니다.","Hub의 Codex Agent는 지시를 승인된 LiveDesk 도구로 변환하고 컴퓨터별 실행 상태와 결과를 표시합니다."],platformTitle:"5. 현재 플랫폼과 스트림 상태",platformBody:"Windows의 Wall, Control, 파일 전송, 원격 오디오와 RemoteFast 경로를 현재 기준으로 확인했습니다. macOS와 Linux는 같은 npm 명령 경로를 유지하면서 권한과 캡처 백엔드를 확장하고 있습니다.",platformPoints:["자동 Wall과 Control은 모든 Client에서 직접 H.264를 사용합니다. RGB565/LZO Atlas는 내부 진단 실험에만 남고 자동 전송 경로에는 사용되지 않습니다.","원격 오디오는 선택한 장비가 capability를 광고할 때 사용할 수 있으며, 브라우저는 queue·drop·resync·automatic restart 상태를 진단합니다.","macOS: 화면 캡처와 제어에는 Screen Recording/Accessibility 권한이 필요합니다. RemoteFast 로그는 필요한 상태 중심으로 제한됩니다.","Linux: linux-x64 runtime, X11/XTEST 입력과 PipeWire/PulseAudio 기본 출력 오디오 캡처를 지원합니다."],firewallTitle:"방화벽과 외부 장소 연결",firewallBody:"LiveDesk는 Direct TCP를 먼저 시도하고, 직접 연결이 안 되면 암호화된 rendezvous relay로 제어를 연결하며 가능한 경우 영상은 암호화된 UDP P2P로 전송합니다.",firewallPoints:["LAN Direct TCP의 기본 클라이언트 포트는 5197입니다.","클라이언트와 매니저는 설정된 rendezvous 서버로 나가는 연결이 가능해야 합니다.","Direct TCP가 실패하면 relay 제어와 UDP P2P 영상을 자동으로 시도합니다.","외부망에서도 Direct TCP를 원할 때만 TCP 5197 포트포워딩이나 VPN/IP allowlist를 설정합니다.","Screen Wall/API 포트 5179는 외부 브라우저가 Wall을 직접 열 때만 노출합니다."],commandsTitle:"현재 사용 명령",commandsBody:"웹사이트를 찾아가 설치 파일을 받는 방식보다 터미널 한 줄로 모든 운영체제에서 거의 같은 흐름을 쓰는 것이 LiveDesk의 기본 방향입니다.",managerCommandLabel:"매니저 시작",clientCommandLabel:"워크스테이션 연결",slotCommandLabel:"3번 슬롯에 고정",manualCommandLabel:"고급 수동 연결"}),en:Er({languageName:"English",languageLabel:"Document language",eyebrow:"LiveDesk Manual",title:"Open a local Screen Wall with one command",intro:"LiveDesk is an npm-first remote work deck for monitoring Clients, mini PCs, Mac minis, and development machines from one manager PC.",managerTitle:"1. Run the manager",managerBody:"Run LiveDesk on the computer that will watch the screens. The manager starts the UI and local server together, then opens http://127.0.0.1:5179.",managerPoints:["The command is npx -y livedesk.","The manager uses port 5179 for the Screen Wall/API and port 5197 for client connections.","If an old LiveDesk process still owns those ports, startup cleans it by default. Add --no-clean when you want to keep it."],clientTitle:"2. Connect a Client",clientBody:"On each monitored computer, connect with Google sign-in or the 6-digit PIN shown on the Hub screen. If no manager is online yet, the client waits for a live online signal and falls back to adaptive retries.",clientPoints:["Run npx -y livedesk client for first available placement.","Run npx -y livedesk client 3 to pin the machine to slot 3.","The browser connection page lets you choose Google or a 6-digit PIN."],syncTitle:"3. Sync Server and discovery",syncBody:"Sync Server publishes this manager as the active Screen Wall for the signed-in account. Clients read that Supabase record after Google sign-in and try the endpoint candidates in order.",syncPoints:["The record includes host instance, LAN/private addresses, public endpoint candidates, pair token, and a short lease.","LAN candidates are preferred first, then public candidates if needed.","Press Sync Server after manager moves, VPN/firewall/router changes, or when this development machine should take over as active manager.","Chrome Local Network Access on livedesk.pages.dev is no longer the default runtime path. The npm manager app is the real server."],agentTitle:"4. Run multi-Client tasks with Agent",agentBody:"The Agents page runs a Codex-based Agent in the Hub to inspect connected Clients and perform actions within the selected permission scope. Client PCs do not need the Codex app or Codex SDK installed.",agentPoints:["Suggested tasks provide generic read-only and operational command templates with search plus permission, platform, and capability checks.","Choose Ask, Safe Auto, Full Access, or Custom. Risky changes go through approval cards and explicit Client capability checks.","Limit targets with All connected or Selected. Results use compact per-device status chips and show real RAM, disk, GPU, and process summaries.","The Hub-hosted Codex Agent turns instructions into approved LiveDesk tool calls and shows progress and results for each computer."],platformTitle:"5. Current platform and stream state",platformBody:"Windows Wall, Control, file transfer, remote audio, and the RemoteFast path are verified against the current implementation. macOS and Linux keep the same npm command path while capture and permission backends expand.",platformPoints:["Automatic Wall and Control use direct H.264 for every Client. The RGB565/LZO Atlas remains only for internal diagnostic experiments and is never selected automatically.","Remote audio is available when the selected Client advertises the capability, with queue, drop, resync, and automatic-restart diagnostics in the browser.","macOS requires Screen Recording and Accessibility permissions for capture and control. RemoteFast logs focus on actionable state.","Linux includes the linux-x64 runtime, X11/XTEST input, and default-output audio capture through PipeWire or PulseAudio."],firewallTitle:"Firewall and remote locations",firewallBody:"LiveDesk tries Direct TCP first; if direct access fails, control uses the encrypted rendezvous relay and video uses encrypted UDP P2P when available.",firewallPoints:["The default LAN Direct TCP client port is 5197.","Clients and the manager need outbound access to the configured rendezvous server.","Relay control and UDP P2P video are attempted automatically after Direct TCP fails.","Forward TCP 5197 or configure VPN/IP allowlists only when Direct TCP is required across networks.","Expose Screen Wall/API port 5179 only when a remote browser must open the Wall directly."],commandsTitle:"Current commands",commandsBody:"The product direction is one terminal command across operating systems instead of finding a website, downloading, and installing manually.",managerCommandLabel:"Start manager",clientCommandLabel:"Connect Client",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ja:Er({languageName:"日本語",languageLabel:"ドキュメント言語",eyebrow:"LiveDesk Manual",title:"1行でローカル Screen Wall を開く",intro:"LiveDesk は、複数の作業 PC、mini PC、Mac mini、開発機を1台の manager PC から監視する npm-first のリモート作業デッキです。",managerTitle:"1. manager を実行",managerBody:"画面を集めて見るコンピューターで LiveDesk manager を実行します。UI とローカルサーバーが同時に起動し、http://127.0.0.1:5179 が開きます。",managerPoints:["コマンドは npx -y livedesk です。","Screen Wall/API は 5179、client 接続は 5197 を使います。","古い LiveDesk プロセスがポートを使っている場合は、基本的に自動で整理して起動します。"],clientTitle:"2. Client を接続",clientBody:"監視される PC で同じ Google アカウントにログインします。manager がまだ無い場合、client はオンライン通知を待ち、適応型の間隔で再確認します。",clientPoints:["空きスロットに入れるには npx -y livedesk client を実行します。","スロットを固定するには npx -y livedesk client 3 のように番号を付けます。","大量の PC でも再ログインなしで待ち続けます。"],syncTitle:"3. Sync Server と自動検出",syncBody:"Sync Server はこの manager を現在の Google アカウントの active Screen Wall として Supabase に登録します。",syncPoints:["host instance、LAN/private アドレス、public 候補、pair token、短い lease を登録します。","client は LAN 候補を優先し、必要なら public 候補も試します。","VPN、firewall、router、manager の場所が変わったら Sync Server を押します。","livedesk.pages.dev の Chrome Local Network Access は標準実行経路ではありません。npm manager アプリが実際のサーバーです。"],platformTitle:"4. 現在のプラットフォーム状態",platformBody:"Windows は live screen transfer まで確認済みです。macOS と Linux も同じ npm コマンド経路を目標に対応を広げています。",platformPoints:["Windows: 動作確認済み。","macOS: 画面取得と制御には Screen Recording/Accessibility 権限が必要です。","Linux: linux-x64 runtime、grim/gnome-screenshot/import/scrot capture、X11/XTEST input backend を追加済み。audio は未対応です。"],firewallTitle:"Firewall と外部拠点",firewallBody:"LiveDesk は Direct TCP を先に試し、失敗した場合は暗号化 rendezvous relay で制御し、可能なら映像に暗号化 UDP P2P を使います。",firewallPoints:["LAN の Direct TCP client 既定ポートは 5197 です。","client と manager は設定済み rendezvous server へ outbound 接続できる必要があります。","Direct TCP 失敗後は relay 制御と UDP P2P 映像を自動的に試します。","ネットワーク越しに Direct TCP が必要な場合だけ TCP 5197 の転送または VPN/IP allowlist を設定します。","5179 は外部ブラウザが Wall を直接開く場合だけ公開します。"],commandsTitle:"現在のコマンド",commandsBody:"Web サイトから installer を探すより、OS をまたいで terminal 1行で動かす方向です。",managerCommandLabel:"manager 起動",clientCommandLabel:"Client 接続",slotCommandLabel:"slot 3 に固定",manualCommandLabel:"高度な手動接続"}),"zh-CN":Er({languageName:"简体中文",languageLabel:"文档语言",eyebrow:"LiveDesk Manual",title:"用一条命令打开本地 Screen Wall",intro:"LiveDesk 是 npm-first 的远程工作台,用一台 manager PC 监控多台工作电脑、迷你主机、Mac mini 和开发机器。",managerTitle:"1. 运行 manager",managerBody:"在负责查看屏幕的电脑上运行 LiveDesk manager。它会同时启动 UI 和本地服务器,并打开 http://127.0.0.1:5179。",managerPoints:["命令是 npx -y livedesk。","Screen Wall/API 使用 5179,client 连接使用 5197。","如果旧的 LiveDesk 进程占用端口,默认会清理后重新启动。"],clientTitle:"2. 连接 Client",clientBody:"在被监控的电脑上使用同一个 Google 账号登录。如果 manager 尚未在线,client 会等待上线通知,并以自适应间隔重新检查。",clientPoints:["自动放入空位: npx -y livedesk client。","固定到 3 号位置: npx -y livedesk client 3。","大量电脑也可以持续等待,不需要反复登录。"],syncTitle:"3. Sync Server 和自动发现",syncBody:"Sync Server 会把当前 manager 作为该账号的 active Screen Wall 写入 Supabase。client 登录后读取记录并依次尝试连接候选地址。",syncPoints:["记录包括 host instance、LAN/private 地址、public 候选、pair token 和短 lease。","优先尝试同一 LAN 地址,需要时再尝试外部地址。","manager 位置、VPN、防火墙或路由变化后请点击 Sync Server。","livedesk.pages.dev 的 Chrome Local Network Access 不再是默认运行方式。npm manager app 才是真正服务器。"],platformTitle:"4. 当前平台状态",platformBody:"Windows 已确认可传输实时画面。macOS 和 Linux 正按同一 npm 命令路径扩展支持。",platformPoints:["Windows: 已确认可用。","macOS: 画面捕获和控制需要 Screen Recording/Accessibility 权限。","Linux: 已加入 linux-x64 runtime、grim/gnome-screenshot/import/scrot 捕获、X11/XTEST 输入后端。音频尚未启用。"],firewallTitle:"防火墙和外部地点",firewallBody:"LiveDesk 会先尝试 Direct TCP;直连失败时,控制改用加密 rendezvous relay,视频在可用时使用加密 UDP P2P。",firewallPoints:["LAN Direct TCP 的默认 client 端口是 5197。","client 和 manager 必须能向已配置的 rendezvous server 建立出站连接。","Direct TCP 失败后会自动尝试 relay 控制和 UDP P2P 视频。","只有跨网络需要 Direct TCP 时才转发 TCP 5197 或配置 VPN/IP 白名单。","只有远程浏览器需要直接打开 Wall 时才暴露 5179。"],commandsTitle:"当前命令",commandsBody:"产品方向是跨操作系统使用一条终端命令,而不是先找网站、下载、安装。",managerCommandLabel:"启动 manager",clientCommandLabel:"连接 Client",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"高级手动连接"}),"zh-TW":Er({languageName:"繁體中文",languageLabel:"文件語言",eyebrow:"LiveDesk Manual",title:"用一行指令開啟本機 Screen Wall",intro:"LiveDesk 是 npm-first 的遠端工作台,用一台 manager PC 監看多台工作電腦、迷你主機、Mac mini 與開發機。",managerTitle:"1. 執行 manager",managerBody:"在負責看畫面的電腦上執行 LiveDesk manager。它會同時啟動 UI 與本機伺服器,並開啟 http://127.0.0.1:5179。",managerPoints:["指令是 npx -y livedesk。","Screen Wall/API 使用 5179,client 連線使用 5197。","若舊的 LiveDesk 程序占用連接埠,預設會清理後重新啟動。"],clientTitle:"2. 連接 Client",clientBody:"在被監看的電腦上使用同一個 Google 帳號登入。如果 manager 尚未上線,client 會等待上線通知,並以自適應間隔重新檢查。",clientPoints:["自動放入空位: npx -y livedesk client。","固定到 3 號位置: npx -y livedesk client 3。","大量電腦也能持續等待,不需要反覆登入。"],syncTitle:"3. Sync Server 與自動探索",syncBody:"Sync Server 會把目前 manager 登錄為此帳號的 active Screen Wall。client 登入後讀取 Supabase 記錄並依序嘗試連線候選地址。",syncPoints:["記錄包含 host instance、LAN/private 位址、public 候選、pair token 與短 lease。","優先嘗試 LAN 位址,需要時再嘗試外部位址。","manager 位置、VPN、防火牆或路由設定改變後請按 Sync Server。","livedesk.pages.dev 的 Chrome Local Network Access 不再是預設執行路徑。npm manager app 才是真正伺服器。"],platformTitle:"4. 目前平台狀態",platformBody:"Windows 已確認可傳輸即時畫面。macOS 與 Linux 也沿用相同 npm 指令路徑擴充支援。",platformPoints:["Windows: 已確認可用。","macOS: 畫面擷取與控制需要 Screen Recording/Accessibility 權限。","Linux: 已加入 linux-x64 runtime、grim/gnome-screenshot/import/scrot capture、X11/XTEST input backend。音訊尚未啟用。"],firewallTitle:"防火牆與外部地點",firewallBody:"LiveDesk 會先嘗試 Direct TCP;直連失敗時,控制改用加密 rendezvous relay,影像在可用時使用加密 UDP P2P。",firewallPoints:["LAN Direct TCP 的預設 client 連接埠是 5197。","client 與 manager 必須能向已設定的 rendezvous server 建立外送連線。","Direct TCP 失敗後會自動嘗試 relay 控制與 UDP P2P 影像。","只有跨網路需要 Direct TCP 時才轉送 TCP 5197 或設定 VPN/IP allowlist。","只有遠端瀏覽器需要直接開啟 Wall 時才公開 5179。"],commandsTitle:"目前指令",commandsBody:"產品方向是跨作業系統用一行 terminal 指令,而不是先找網站、下載、安裝。",managerCommandLabel:"啟動 manager",clientCommandLabel:"連接 Client",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"進階手動連線"}),es:Er({languageName:"Español",languageLabel:"Idioma del documento",eyebrow:"LiveDesk Manual",title:"Abre un Screen Wall local con un comando",intro:"LiveDesk es una consola npm-first para vigilar equipos de trabajo, mini PC, Mac mini y equipos de desarrollo desde un PC manager.",managerTitle:"1. Ejecuta el manager",managerBody:"Ejecuta LiveDesk en el equipo que verá las pantallas. El manager inicia la UI y el servidor local juntos y abre http://127.0.0.1:5179.",managerPoints:["El comando es npx -y livedesk.","El manager usa 5179 para Screen Wall/API y 5197 para conexiones client.","Si un proceso antiguo ocupa los puertos, el arranque lo limpia por defecto."],clientTitle:"2. Conecta una Client",clientBody:"En cada equipo monitoreado, inicia sesión con la misma cuenta Google. Si el manager aún no está activo, el client espera una señal en tiempo real y vuelve a comprobar con intervalos adaptativos.",clientPoints:["Usa npx -y livedesk client para el primer slot libre.","Usa npx -y livedesk client 3 para fijar el equipo al slot 3.","Los clients siguen esperando para no repetir login en muchas máquinas."],syncTitle:"3. Sync Server y descubrimiento",syncBody:"Sync Server publica este manager como Screen Wall activo para la cuenta. Los clients leen el registro en Supabase y prueban los endpoints.",syncPoints:["Incluye host instance, direcciones LAN/private, candidatos public, pair token y lease corto.","Primero se prueban candidatos LAN, luego públicos si hace falta.","Pulsa Sync Server después de cambios de manager, VPN, firewall o router.","Chrome Local Network Access en livedesk.pages.dev ya no es el flujo principal. La app npm manager es el servidor real."],platformTitle:"4. Estado de plataformas",platformBody:"Windows ya fue verificado con transferencia de pantalla. macOS y Linux siguen el mismo camino npm.",platformPoints:["Windows: verificado.","macOS: captura y control requieren permisos Screen Recording/Accessibility.","Linux: runtime linux-x64, entrada X11/XTEST y audio de salida mediante PipeWire o PulseAudio."],firewallTitle:"Firewall y sedes remotas",firewallBody:"LiveDesk intenta primero Direct TCP; si falla, el control usa el rendezvous relay cifrado y el vídeo usa UDP P2P cifrado cuando está disponible.",firewallPoints:["El puerto client predeterminado para Direct TCP en LAN es 5197.","Clients y manager necesitan acceso saliente al servidor rendezvous configurado.","Tras fallar Direct TCP se intentan automáticamente control relay y vídeo UDP P2P.","Reenvía TCP 5197 o configura VPN/allowlist de IP solo si necesitas Direct TCP entre redes.","Expón 5179 solo si un navegador remoto debe abrir el Wall directamente."],commandsTitle:"Comandos actuales",commandsBody:"La dirección del producto es un comando de terminal común entre sistemas, no descargar e instalar desde una web.",managerCommandLabel:"Iniciar manager",clientCommandLabel:"Conectar Client",slotCommandLabel:"Fijar al slot 3",manualCommandLabel:"Conexión manual avanzada"}),fr:Er({languageName:"Français",languageLabel:"Langue du document",eyebrow:"LiveDesk Manual",title:"Ouvrir un Screen Wall local en une commande",intro:"LiveDesk est un deck npm-first pour surveiller plusieurs postes, mini PC, Mac mini et machines dev depuis un PC manager.",managerTitle:"1. Lancer le manager",managerBody:"Lancez LiveDesk sur l’ordinateur qui observe les écrans. Le manager démarre l’UI et le serveur local, puis ouvre http://127.0.0.1:5179.",managerPoints:["La commande est npx -y livedesk.","Le manager utilise 5179 pour Screen Wall/API et 5197 pour les connexions client.","Si un ancien processus utilise les ports, le démarrage le nettoie par défaut."],clientTitle:"2. Connecter une Client",clientBody:"Sur chaque ordinateur surveillé, connectez-vous avec le même compte Google. Si le manager n’est pas encore actif, le client réessaie toutes les 5 secondes.",clientPoints:["Utilisez npx -y livedesk client pour le premier slot libre.","Utilisez npx -y livedesk client 3 pour fixer la machine au slot 3.","Les clients continuent d’attendre pour éviter les reconnexions répétées."],syncTitle:"3. Sync Server et découverte",syncBody:"Sync Server publie ce manager comme Screen Wall actif du compte. Les clients lisent l’enregistrement Supabase et testent les endpoints.",syncPoints:["Il contient host instance, adresses LAN/private, candidats public, pair token et lease court.","Les candidats LAN sont essayés en premier, puis les candidats publics si besoin.","Cliquez Sync Server après un changement de manager, VPN, firewall ou routeur.","Chrome Local Network Access sur livedesk.pages.dev n’est plus le chemin par défaut. L’app npm manager est le vrai serveur."],platformTitle:"4. État des plateformes",platformBody:"Windows est vérifié avec transfert d’écran live. macOS et Linux suivent le même chemin npm.",platformPoints:["Windows: vérifié.","macOS: capture et contrôle nécessitent Screen Recording/Accessibility.","Linux: runtime linux-x64, entrée X11/XTEST et audio de sortie via PipeWire ou PulseAudio."],firewallTitle:"Firewall et sites distants",firewallBody:"LiveDesk tente d’abord Direct TCP ; en cas d’échec, le contrôle utilise le relais rendezvous chiffré et la vidéo UDP P2P chiffrée lorsqu’elle est disponible.",firewallPoints:["Le port client Direct TCP par défaut sur le LAN est 5197.","Clients et manager doivent avoir un accès sortant au serveur rendezvous configuré.","Après un échec Direct TCP, le contrôle relay et la vidéo UDP P2P sont tentés automatiquement.","Redirigez TCP 5197 ou configurez VPN/allowlist IP seulement si Direct TCP est requis entre réseaux.","Exposez 5179 uniquement si un navigateur distant doit ouvrir directement le Wall."],commandsTitle:"Commandes actuelles",commandsBody:"La direction produit est une commande terminal commune aux OS, plutôt qu’un téléchargement manuel depuis un site.",managerCommandLabel:"Démarrer manager",clientCommandLabel:"Connecter Client",slotCommandLabel:"Fixer au slot 3",manualCommandLabel:"Connexion manuelle avancée"}),de:Er({languageName:"Deutsch",languageLabel:"Dokumentsprache",eyebrow:"LiveDesk Manual",title:"Lokale Screen Wall mit einem Befehl öffnen",intro:"LiveDesk ist ein npm-first Arbeitsdeck, um viele Clients, Mini-PCs, Mac minis und Dev-Rechner von einem Manager-PC zu überwachen.",managerTitle:"1. Manager starten",managerBody:"Starte LiveDesk auf dem Computer, der die Screens sieht. Der Manager startet UI und lokalen Server zusammen und öffnet http://127.0.0.1:5179.",managerPoints:["Der Befehl ist npx -y livedesk.","Der Manager nutzt 5179 für Screen Wall/API und 5197 für Client-Verbindungen.","Wenn alte LiveDesk-Prozesse Ports belegen, werden sie beim Start standardmäßig bereinigt."],clientTitle:"2. Client verbinden",clientBody:"Melde dich auf jedem überwachten Computer mit demselben Google-Konto an. Wenn kein Manager online ist, wartet der Client auf ein Live-Signal und prüft mit adaptiven Intervallen erneut.",clientPoints:["npx -y livedesk client nutzt den ersten freien Slot.","npx -y livedesk client 3 fixiert den Rechner auf Slot 3.","Clients warten weiter, damit große Setups kein wiederholtes Login brauchen."],syncTitle:"3. Sync Server und Discovery",syncBody:"Sync Server veröffentlicht diesen Manager als aktive Screen Wall des Kontos. Clients lesen den Supabase-Eintrag und testen Endpoints der Reihe nach.",syncPoints:["Enthält host instance, LAN/private Adressen, public Kandidaten, pair token und kurze lease.","LAN-Kandidaten werden zuerst versucht, danach public Kandidaten.","Nach Änderungen an Manager, VPN, Firewall oder Router Sync Server drücken.","Chrome Local Network Access auf livedesk.pages.dev ist nicht mehr der Standardpfad. Die npm Manager App ist der echte Server."],platformTitle:"4. Plattformstatus",platformBody:"Windows wurde mit Live-Screen-Transfer geprüft. macOS und Linux folgen demselben npm-Pfad.",platformPoints:["Windows: verifiziert.","macOS: Capture und Control brauchen Screen Recording/Accessibility Rechte.","Linux: linux-x64 Runtime, X11/XTEST Eingabe und Ausgangsaudio über PipeWire oder PulseAudio."],firewallTitle:"Firewall und entfernte Standorte",firewallBody:"LiveDesk versucht zuerst Direct TCP; schlägt dies fehl, nutzt die Steuerung das verschlüsselte Rendezvous-Relay und Video nach Möglichkeit verschlüsseltes UDP P2P.",firewallPoints:["Der Standardport für LAN Direct TCP Clients ist 5197.","Clients und Manager benötigen ausgehenden Zugriff auf den konfigurierten Rendezvous-Server.","Nach einem Direct-TCP-Fehler werden Relay-Steuerung und UDP-P2P-Video automatisch versucht.","TCP 5197 nur weiterleiten oder VPN/IP-Allowlist einrichten, wenn Direct TCP netzübergreifend nötig ist.","5179 nur öffnen, wenn ein Remote-Browser die Wall direkt laden muss."],commandsTitle:"Aktuelle Befehle",commandsBody:"Die Produktlinie ist ein Terminalbefehl über Betriebssysteme hinweg, statt Website suchen, herunterladen und installieren.",managerCommandLabel:"Manager starten",clientCommandLabel:"Client verbinden",slotCommandLabel:"An Slot 3 fixieren",manualCommandLabel:"Erweiterte manuelle Verbindung"}),"pt-BR":Er({languageName:"Português",languageLabel:"Idioma do documento",eyebrow:"LiveDesk Manual",title:"Abra um Screen Wall local com um comando",intro:"LiveDesk é um deck npm-first para monitorar várias estações, mini PCs, Mac minis e máquinas dev a partir de um PC manager.",managerTitle:"1. Execute o manager",managerBody:"Rode LiveDesk no computador que verá as telas. O manager inicia a UI e o servidor local juntos e abre http://127.0.0.1:5179.",managerPoints:["O comando é npx -y livedesk.","O manager usa 5179 para Screen Wall/API e 5197 para conexões client.","Se um processo antigo ocupa as portas, a inicialização limpa por padrão."],clientTitle:"2. Conecte uma Client",clientBody:"Em cada computador monitorado, entre com a mesma conta Google. Se o manager ainda não estiver online, o client aguarda um sinal em tempo real e verifica novamente em intervalos adaptativos.",clientPoints:["Use npx -y livedesk client para o primeiro slot livre.","Use npx -y livedesk client 3 para fixar no slot 3.","Clients continuam tentando para evitar login repetido em muitos PCs."],syncTitle:"3. Sync Server e descoberta",syncBody:"Sync Server publica este manager como Screen Wall ativo da conta. Clients leem o registro no Supabase e testam endpoints.",syncPoints:["Inclui host instance, endereços LAN/private, candidatos public, pair token e lease curto.","Candidatos LAN vêm primeiro; public depois se necessário.","Clique Sync Server após mudanças de manager, VPN, firewall ou roteador.","Chrome Local Network Access em livedesk.pages.dev não é mais o caminho padrão. O app npm manager é o servidor real."],platformTitle:"4. Estado das plataformas",platformBody:"Windows foi verificado com transferência de tela. macOS e Linux seguem o mesmo caminho npm.",platformPoints:["Windows: verificado.","macOS: captura e controle precisam de permissões Screen Recording/Accessibility.","Linux: runtime linux-x64, captura grim/gnome-screenshot/import/scrot e entrada X11/XTEST adicionados. Áudio ainda desativado."],firewallTitle:"Firewall e locais remotos",firewallBody:"LiveDesk tenta Direct TCP primeiro; se falhar, o controle usa o rendezvous relay criptografado e o vídeo usa UDP P2P criptografado quando disponível.",firewallPoints:["A porta client padrão para Direct TCP na LAN é 5197.","Clients e manager precisam de acesso de saída ao servidor rendezvous configurado.","Após falha no Direct TCP, controle relay e vídeo UDP P2P são tentados automaticamente.","Encaminhe TCP 5197 ou configure VPN/allowlist IP apenas se Direct TCP entre redes for necessário.","Exponha 5179 somente se um navegador remoto precisar abrir o Wall diretamente."],commandsTitle:"Comandos atuais",commandsBody:"A direção do produto é um comando de terminal comum entre sistemas, não baixar e instalar manualmente.",managerCommandLabel:"Iniciar manager",clientCommandLabel:"Conectar Client",slotCommandLabel:"Fixar no slot 3",manualCommandLabel:"Conexão manual avançada"}),it:Er({languageName:"Italiano",languageLabel:"Lingua documento",eyebrow:"LiveDesk Manual",title:"Apri uno Screen Wall locale con un comando",intro:"LiveDesk è un deck npm-first per monitorare Client, mini PC, Mac mini e macchine dev da un solo PC manager.",managerTitle:"1. Avvia il manager",managerBody:"Esegui LiveDesk sul computer che guarderà gli schermi. Il manager avvia UI e server locale e apre http://127.0.0.1:5179.",managerPoints:["Il comando è npx -y livedesk.","Il manager usa 5179 per Screen Wall/API e 5197 per connessioni client.","Se vecchi processi occupano le porte, l’avvio le pulisce di default."],clientTitle:"2. Connetti una Client",clientBody:"Su ogni computer monitorato, accedi con lo stesso account Google. Se il manager non è online, il client riprova ogni 5 secondi.",clientPoints:["npx -y livedesk client usa il primo slot libero.","npx -y livedesk client 3 fissa la macchina allo slot 3.","I client continuano a provare per evitare login ripetuti."],syncTitle:"3. Sync Server e discovery",syncBody:"Sync Server pubblica questo manager come Screen Wall attivo dell’account. I client leggono Supabase e provano gli endpoint.",syncPoints:["Include host instance, indirizzi LAN/private, candidati public, pair token e lease breve.","Prima LAN, poi public se necessario.","Premi Sync Server dopo cambi di manager, VPN, firewall o router.","Chrome Local Network Access su livedesk.pages.dev non è più il percorso principale. L’app npm manager è il server reale."],platformTitle:"4. Stato piattaforme",platformBody:"Windows è verificato con trasferimento schermo live. macOS e Linux seguono lo stesso percorso npm.",platformPoints:["Windows: verificato.","macOS: capture e control richiedono permessi Screen Recording/Accessibility.","Linux: aggiunti runtime linux-x64, capture grim/gnome-screenshot/import/scrot e input X11/XTEST. Audio disattivato."],firewallTitle:"Firewall e sedi remote",firewallBody:"LiveDesk prova prima Direct TCP; se fallisce, il controllo usa il rendezvous relay cifrato e il video usa UDP P2P cifrato quando disponibile.",firewallPoints:["La porta client predefinita per Direct TCP in LAN è 5197.","Client e manager devono avere accesso in uscita al server rendezvous configurato.","Dopo un errore Direct TCP, controllo relay e video UDP P2P vengono tentati automaticamente.","Inoltra TCP 5197 o configura VPN/allowlist IP solo se serve Direct TCP tra reti.","Esponi 5179 soltanto se un browser remoto deve aprire direttamente la Wall."],commandsTitle:"Comandi attuali",commandsBody:"La direzione è un comando terminale comune tra sistemi operativi, invece di download e install manuale.",managerCommandLabel:"Avvia manager",clientCommandLabel:"Connetti Client",slotCommandLabel:"Fissa allo slot 3",manualCommandLabel:"Connessione manuale avanzata"}),id:Er({languageName:"Bahasa Indonesia",languageLabel:"Bahasa dokumen",eyebrow:"LiveDesk Manual",title:"Buka Screen Wall lokal dengan satu perintah",intro:"LiveDesk adalah deck npm-first untuk memantau banyak Client, mini PC, Mac mini, dan mesin dev dari satu PC manager.",managerTitle:"1. Jalankan manager",managerBody:"Jalankan LiveDesk di komputer yang melihat layar. Manager membuka UI dan server lokal bersama, lalu membuka http://127.0.0.1:5179.",managerPoints:["Perintahnya npx -y livedesk.","Manager memakai 5179 untuk Screen Wall/API dan 5197 untuk koneksi client.","Jika proses lama memakai port itu, startup membersihkannya secara default."],clientTitle:"2. Hubungkan Client",clientBody:"Di komputer yang dipantau, masuk dengan akun Google yang sama. Jika manager belum online, client tetap mencoba tiap 5 detik.",clientPoints:["npx -y livedesk client memakai slot kosong pertama.","npx -y livedesk client 3 mengunci mesin ke slot 3.","Client terus mencoba agar banyak PC tidak perlu login berulang."],syncTitle:"3. Sync Server dan discovery",syncBody:"Sync Server menerbitkan manager ini sebagai Screen Wall aktif untuk akun. Client membaca Supabase dan mencoba endpoint.",syncPoints:["Berisi host instance, alamat LAN/private, kandidat public, pair token, dan lease pendek.","Kandidat LAN dicoba lebih dulu, lalu public jika perlu.","Tekan Sync Server setelah perubahan manager, VPN, firewall, atau router.","Chrome Local Network Access di livedesk.pages.dev bukan jalur utama lagi. App npm manager adalah server sebenarnya."],platformTitle:"4. Status platform",platformBody:"Windows sudah diverifikasi dengan live screen transfer. macOS dan Linux mengikuti jalur npm yang sama.",platformPoints:["Windows: terverifikasi.","macOS: capture dan control perlu izin Screen Recording/Accessibility.","Linux: runtime linux-x64, capture grim/gnome-screenshot/import/scrot, dan input X11/XTEST sudah ditambahkan. Audio belum aktif."],firewallTitle:"Firewall dan lokasi luar",firewallBody:"LiveDesk mencoba Direct TCP lebih dulu; jika gagal, kontrol memakai rendezvous relay terenkripsi dan video memakai UDP P2P terenkripsi bila tersedia.",firewallPoints:["Port client default untuk Direct TCP di LAN adalah 5197.","Client dan manager memerlukan akses keluar ke server rendezvous yang dikonfigurasi.","Setelah Direct TCP gagal, kontrol relay dan video UDP P2P dicoba otomatis.","Forward TCP 5197 atau atur VPN/IP allowlist hanya jika Direct TCP antarjaringan diperlukan.","Buka 5179 hanya jika browser jarak jauh harus membuka Wall secara langsung."],commandsTitle:"Perintah saat ini",commandsBody:"Arah produk adalah satu perintah terminal lintas OS, bukan download dan instal manual.",managerCommandLabel:"Mulai manager",clientCommandLabel:"Hubungkan Client",slotCommandLabel:"Kunci ke slot 3",manualCommandLabel:"Koneksi manual lanjutan"}),vi:Er({languageName:"Tiếng Việt",languageLabel:"Ngôn ngữ tài liệu",eyebrow:"LiveDesk Manual",title:"Mở Screen Wall cục bộ bằng một lệnh",intro:"LiveDesk là deck npm-first để giám sát nhiều Client, mini PC, Mac mini và máy dev từ một PC manager.",managerTitle:"1. Chạy manager",managerBody:"Chạy LiveDesk trên máy dùng để xem màn hình. Manager khởi động UI và server cục bộ cùng lúc, rồi mở http://127.0.0.1:5179.",managerPoints:["Lệnh là npx -y livedesk.","Manager dùng 5179 cho Screen Wall/API và 5197 cho kết nối client.","Nếu tiến trình cũ giữ port, startup mặc định sẽ dọn và khởi động lại."],clientTitle:"2. Kết nối Client",clientBody:"Trên mỗi máy được giám sát, đăng nhập cùng tài khoản Google. Nếu manager chưa online, client tiếp tục thử mỗi 5 giây.",clientPoints:["npx -y livedesk client dùng slot trống đầu tiên.","npx -y livedesk client 3 ghim máy vào slot 3.","Client tiếp tục chờ để nhiều máy không cần đăng nhập lại."],syncTitle:"3. Sync Server và tự phát hiện",syncBody:"Sync Server đăng manager này là Screen Wall đang hoạt động của tài khoản. Client đọc Supabase và thử các endpoint.",syncPoints:["Bao gồm host instance, địa chỉ LAN/private, public candidate, pair token và lease ngắn.","Ưu tiên LAN trước, sau đó thử public nếu cần.","Bấm Sync Server sau thay đổi manager, VPN, firewall hoặc router.","Chrome Local Network Access trên livedesk.pages.dev không còn là đường chạy chính. App npm manager mới là server thật."],platformTitle:"4. Trạng thái nền tảng",platformBody:"Windows đã được kiểm chứng với truyền màn hình live. macOS và Linux đi theo cùng đường npm.",platformPoints:["Windows: đã kiểm chứng.","macOS: capture và control cần quyền Screen Recording/Accessibility.","Linux: đã thêm runtime linux-x64, capture grim/gnome-screenshot/import/scrot và input X11/XTEST. Audio chưa bật."],firewallTitle:"Firewall và địa điểm ngoài",firewallBody:"LiveDesk thử Direct TCP trước; nếu thất bại, control dùng rendezvous relay mã hóa và video dùng UDP P2P mã hóa khi khả dụng.",firewallPoints:["Port client mặc định cho Direct TCP trong LAN là 5197.","Client và manager cần kết nối outbound tới rendezvous server đã cấu hình.","Sau khi Direct TCP thất bại, relay control và UDP P2P video được thử tự động.","Chỉ forward TCP 5197 hoặc cấu hình VPN/IP allowlist khi cần Direct TCP giữa các mạng.","Chỉ mở 5179 khi browser từ xa cần mở Wall trực tiếp."],commandsTitle:"Lệnh hiện tại",commandsBody:"Hướng sản phẩm là một lệnh terminal dùng chung giữa các OS, thay vì tải và cài thủ công.",managerCommandLabel:"Khởi động manager",clientCommandLabel:"Kết nối Client",slotCommandLabel:"Ghim vào slot 3",manualCommandLabel:"Kết nối thủ công nâng cao"}),th:Er({languageName:"ไทย",languageLabel:"ภาษาของเอกสาร",eyebrow:"LiveDesk Manual",title:"เปิด Screen Wall ภายในด้วยคำสั่งเดียว",intro:"LiveDesk คือ deck แบบ npm-first สำหรับดู Client, mini PC, Mac mini และเครื่อง dev หลายเครื่องจาก manager PC เครื่องเดียว",managerTitle:"1. รัน manager",managerBody:"รัน LiveDesk บนเครื่องที่ใช้ดูหน้าจอ Manager จะเปิด UI และ local server พร้อมกัน แล้วเปิด http://127.0.0.1:5179",managerPoints:["คำสั่งคือ npx -y livedesk","Manager ใช้ 5179 สำหรับ Screen Wall/API และ 5197 สำหรับ client connection","ถ้า process เก่ายังใช้ port อยู่ startup จะล้างให้โดย default"],clientTitle:"2. เชื่อม Client",clientBody:"บนเครื่องที่ต้อง monitor ให้ login ด้วย Google account เดียวกัน ถ้า manager ยังไม่ออนไลน์ client จะลองใหม่ทุก 5 วินาที",clientPoints:["npx -y livedesk client จะใช้ slot ว่างแรก","npx -y livedesk client 3 จะตรึงเครื่องไว้ที่ slot 3","Client จะรอต่อเนื่องเพื่อไม่ต้อง login ซ้ำเมื่อมีหลายเครื่อง"],syncTitle:"3. Sync Server และ discovery",syncBody:"Sync Server จะ publish manager นี้เป็น active Screen Wall ของ account แล้ว client อ่านข้อมูลจาก Supabase และลอง endpoint ต่างๆ",syncPoints:["มี host instance, LAN/private address, public candidate, pair token และ short lease","ลอง LAN ก่อน แล้วค่อยลอง public ถ้าจำเป็น","กด Sync Server หลังเปลี่ยน manager, VPN, firewall หรือ router","Chrome Local Network Access บน livedesk.pages.dev ไม่ใช่ runtime หลักแล้ว app npm manager คือ server จริง"],platformTitle:"4. สถานะ platform",platformBody:"Windows ตรวจสอบแล้วว่าส่งภาพ live ได้ macOS และ Linux ใช้เส้นทาง npm เดียวกัน",platformPoints:["Windows: verified","macOS: capture/control ต้องใช้สิทธิ์ Screen Recording/Accessibility","Linux: เพิ่ม linux-x64 runtime, grim/gnome-screenshot/import/scrot capture และ X11/XTEST input แล้ว audio ยังปิดอยู่"],firewallTitle:"Firewall และเครื่องต่างสถานที่",firewallBody:"LiveDesk จะลอง Direct TCP ก่อน หากล้มเหลว control จะใช้ rendezvous relay ที่เข้ารหัส และ video จะใช้ UDP P2P ที่เข้ารหัสเมื่อพร้อม",firewallPoints:["Port client เริ่มต้นสำหรับ Direct TCP ใน LAN คือ 5197","Client และ manager ต้องเชื่อมต่อ outbound ไปยัง rendezvous server ที่ตั้งค่าไว้ได้","หลัง Direct TCP ล้มเหลว ระบบจะลอง relay control และ UDP P2P video อัตโนมัติ","Forward TCP 5197 หรือตั้ง VPN/IP allowlist เฉพาะเมื่อต้องการ Direct TCP ข้าม network","เปิด 5179 เฉพาะเมื่อ browser ระยะไกลต้องเปิด Wall โดยตรง"],commandsTitle:"คำสั่งปัจจุบัน",commandsBody:"ทิศทาง product คือคำสั่ง terminal เดียวข้าม OS ไม่ใช่ download/install จากเว็บไซต์",managerCommandLabel:"เริ่ม manager",clientCommandLabel:"เชื่อม Client",slotCommandLabel:"ตรึง slot 3",manualCommandLabel:"manual connection ขั้นสูง"}),hi:Er({languageName:"हिन्दी",languageLabel:"दस्तावेज़ भाषा",eyebrow:"LiveDesk Manual",title:"एक कमांड से local Screen Wall खोलें",intro:"LiveDesk एक npm-first remote work deck है जिससे एक manager PC से कई Client, mini PC, Mac mini और dev machines देखे जा सकते हैं।",managerTitle:"1. manager चलाएं",managerBody:"जिस computer से screens देखनी हैं उस पर LiveDesk manager चलाएं। यह UI और local server साथ में शुरू करता है और http://127.0.0.1:5179 खोलता है।",managerPoints:["कमांड है npx -y livedesk।","Manager Screen Wall/API के लिए 5179 और client connections के लिए 5197 इस्तेमाल करता है।","अगर पुराने LiveDesk ports बचे हों तो startup default रूप से साफ करता है।"],clientTitle:"2. Client जोड़ें",clientBody:"हर monitored computer पर उसी Google account से sign in करें। Manager online न हो तब भी client बंद नहीं होता और हर 5 सेकंड retry करता है।",clientPoints:["npx -y livedesk client पहला खाली slot लेता है।","npx -y livedesk client 3 machine को slot 3 पर pin करता है।","बहुत सी machines हों तब भी बार-बार login की जरूरत नहीं रहती।"],syncTitle:"3. Sync Server और discovery",syncBody:"Sync Server इस manager को account का active Screen Wall बनाकर Supabase में publish करता है। Clients record पढ़कर endpoints try करते हैं।",syncPoints:["इसमें host instance, LAN/private addresses, public candidates, pair token और short lease होता है।","LAN candidates पहले try होते हैं, जरूरत हो तो public candidates।","Manager, VPN, firewall या router बदलने के बाद Sync Server दबाएं।","livedesk.pages.dev का Chrome Local Network Access अब default runtime नहीं है। npm manager app ही real server है।"],platformTitle:"4. Platform status",platformBody:"Windows live screen transfer के साथ verified है। macOS और Linux भी इसी npm path पर आगे बढ़ रहे हैं।",platformPoints:["Windows: verified.","macOS: capture/control के लिए Screen Recording/Accessibility permissions चाहिए।","Linux: linux-x64 runtime, X11/XTEST input और PipeWire/PulseAudio output audio capture उपलब्ध हैं।"],firewallTitle:"Firewall और remote locations",firewallBody:"LiveDesk पहले Direct TCP आज़माता है; विफल होने पर control encrypted rendezvous relay उपयोग करता है और उपलब्ध होने पर video encrypted UDP P2P उपयोग करता है।",firewallPoints:["LAN Direct TCP का default client port 5197 है।","Clients और manager को configured rendezvous server तक outbound access चाहिए।","Direct TCP विफल होने के बाद relay control और UDP P2P video अपने आप try होते हैं।","TCP 5197 forward या VPN/IP allowlist तभी सेट करें जब networks के बीच Direct TCP चाहिए।","5179 तभी expose करें जब remote browser को Wall सीधे खोलना हो।"],commandsTitle:"Current commands",commandsBody:"Product direction है OS के बीच एक terminal command, website से download/install नहीं।",managerCommandLabel:"Start manager",clientCommandLabel:"Connect Client",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ar:Er({languageName:"العربية",languageLabel:"لغة المستند",eyebrow:"LiveDesk Manual",title:"افتح Screen Wall محلي بأمر واحد",intro:"LiveDesk هو deck بنمط npm-first لمراقبة عدة Clients وأجهزة mini PC وMac mini وأجهزة تطوير من كمبيوتر manager واحد.",managerTitle:"1. شغل manager",managerBody:"شغل LiveDesk على الكمبيوتر الذي سيعرض الشاشات. يبدأ manager الواجهة والخادم المحلي معا ويفتح http://127.0.0.1:5179.",managerPoints:["الأمر هو npx -y livedesk.","يستخدم manager المنفذ 5179 للواجهة/API والمنفذ 5197 لاتصالات client.","إذا بقيت عملية LiveDesk قديمة على المنافذ، يتم تنظيفها افتراضيا عند التشغيل."],clientTitle:"2. وصل Client",clientBody:"على كل كمبيوتر تتم مراقبته، سجل الدخول بنفس حساب Google. إذا لم يكن manager متاحا، يبقى client يعمل ويحاول كل 5 ثوان.",clientPoints:["npx -y livedesk client يختار أول slot فارغ.","npx -y livedesk client 3 يثبت الجهاز في slot 3.","clients تستمر بالمحاولة لتجنب تكرار تسجيل الدخول عند كثرة الأجهزة."],syncTitle:"3. Sync Server والاكتشاف",syncBody:"Sync Server ينشر هذا manager كـ active Screen Wall للحساب. يقرأ clients سجل Supabase ويجربون endpoints بالترتيب.",syncPoints:["السجل يتضمن host instance وعناوين LAN/private وpublic candidates وpair token وlease قصير.","يتم تفضيل LAN أولا، ثم public عند الحاجة.","اضغط Sync Server بعد تغيير manager أو VPN أو firewall أو router.","Chrome Local Network Access على livedesk.pages.dev لم يعد مسار التشغيل الافتراضي. تطبيق npm manager هو الخادم الحقيقي."],platformTitle:"4. حالة المنصات",platformBody:"Windows تم التحقق منه مع نقل شاشة live. macOS وLinux يتبعان نفس مسار npm.",platformPoints:["Windows: تم التحقق.","macOS: capture/control يحتاجان أذونات Screen Recording/Accessibility.","Linux: تمت إضافة linux-x64 runtime وgrim/gnome-screenshot/import/scrot capture وX11/XTEST input. الصوت ما زال معطلا."],firewallTitle:"Firewall والمواقع البعيدة",firewallBody:"يجرب LiveDesk اتصال Direct TCP أولا؛ وإذا فشل يستخدم التحكم rendezvous relay المشفر ويستخدم الفيديو UDP P2P المشفر عند توفره.",firewallPoints:["منفذ client الافتراضي لاتصال Direct TCP داخل LAN هو 5197.","يحتاج client وmanager إلى اتصال outbound بخادم rendezvous المهيأ.","بعد فشل Direct TCP تتم محاولة relay control وUDP P2P video تلقائيا.","وجه TCP 5197 أو اضبط VPN/IP allowlist فقط عند الحاجة إلى Direct TCP بين الشبكات.","اكشف 5179 فقط إذا كان browser بعيد يحتاج فتح Wall مباشرة."],commandsTitle:"الأوامر الحالية",commandsBody:"اتجاه المنتج هو أمر terminal واحد عبر الأنظمة، وليس تحميل وتثبيت يدوي من موقع.",managerCommandLabel:"Start manager",clientCommandLabel:"Connect Client",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),tr:Er({languageName:"Türkçe",languageLabel:"Belge dili",eyebrow:"LiveDesk Manual",title:"Yerel Screen Wall tek komutla açılsın",intro:"LiveDesk, tek bir manager PC üzerinden birçok Client, mini PC, Mac mini ve dev machine izlemek için npm-first bir çalışma deckidir.",managerTitle:"1. Manager çalıştır",managerBody:"Ekranları izleyecek bilgisayarda LiveDesk manager çalıştır. Manager UI ve local server birlikte başlar ve http://127.0.0.1:5179 açılır.",managerPoints:["Komut: npx -y livedesk.","Manager Screen Wall/API için 5179, client bağlantıları için 5197 kullanır.","Eski LiveDesk process portları tutuyorsa başlangıç varsayılan olarak temizler."],clientTitle:"2. Client bağla",clientBody:"İzlenecek bilgisayarda aynı Google hesabıyla giriş yap. Manager henüz online değilse client kapanmaz ve her 5 saniyede tekrar dener.",clientPoints:["npx -y livedesk client ilk boş slota yerleşir.","npx -y livedesk client 3 makineyi slot 3’e sabitler.","Çok makinede tekrar tekrar login gerekmesin diye client beklemeye devam eder."],syncTitle:"3. Sync Server ve discovery",syncBody:"Sync Server bu managerı hesabın active Screen Wall kaydı olarak Supabase’e yazar. Clients bu kaydı okuyup endpoint adaylarını dener.",syncPoints:["Host instance, LAN/private adresler, public adaylar, pair token ve kısa lease içerir.","Önce LAN adayları, gerekirse public adaylar denenir.","Manager, VPN, firewall veya router değişince Sync Server’a bas.","livedesk.pages.dev üzerindeki Chrome Local Network Access artık default runtime yolu değil. Gerçek server npm manager app."],platformTitle:"4. Platform durumu",platformBody:"Windows live screen transfer ile doğrulandı. macOS ve Linux aynı npm yolunu takip ediyor.",platformPoints:["Windows: doğrulandı.","macOS: capture/control için Screen Recording/Accessibility izinleri gerekir.","Linux: linux-x64 runtime, grim/gnome-screenshot/import/scrot capture ve X11/XTEST input backend eklendi. Audio kapalı."],firewallTitle:"Firewall ve uzak konumlar",firewallBody:"LiveDesk önce Direct TCP dener; başarısız olursa kontrol şifreli rendezvous relay kullanır ve video mümkün olduğunda şifreli UDP P2P kullanır.",firewallPoints:["LAN Direct TCP için varsayılan client portu 5197dir.","Client ve manager yapılandırılmış rendezvous servera outbound erişebilmelidir.","Direct TCP başarısız olduktan sonra relay control ve UDP P2P video otomatik denenir.","Ağlar arasında Direct TCP gerekiyorsa TCP 5197 forward et veya VPN/IP allowlist yapılandır.","5179u yalnız uzak browser Wallu doğrudan açacaksa expose et."],commandsTitle:"Güncel komutlar",commandsBody:"Ürün yönü, webden indirip kurmak yerine işletim sistemleri arasında ortak tek terminal komutu.",managerCommandLabel:"Manager başlat",clientCommandLabel:"Client bağla",slotCommandLabel:"Slot 3’e sabitle",manualCommandLabel:"Gelişmiş manuel bağlantı"})},gP=Object.entries(Fd).map(([t,n])=>({id:t,label:n.languageName}));function vP(){if(typeof navigator>"u")return"en";const t=navigator.languages?.length?navigator.languages:[navigator.language];for(const n of t){const r=n.toLowerCase();if(Fd[n])return n;if(r.startsWith("zh-tw")||r.startsWith("zh-hk"))return"zh-TW";if(r.startsWith("pt"))return"pt-BR";const s=r.split("-")[0];if(Fd[s])return s}return"en"}function c0({index:t}){const n=t+1;return o.jsx("article",{className:"device-tile placeholder-tile","aria-label":`Empty slot ${n}`,children:o.jsxs("div",{className:"tile-screen","aria-hidden":"true",children:[o.jsx("span",{className:"slot-grid","aria-hidden":"true"}),o.jsxs("span",{className:"empty-screen",children:[o.jsx(nr,{size:24}),o.jsxs("strong",{children:["Slot ",String(n).padStart(3,"0")]})]})]})})}const yP=["cpu","gpu","memory","vram","network","disk","temp"];function bP({device:t,slotNumber:n,selected:r,updateIndicator:s,remoteDiagnostics:l,diagnosticsMode:u="remote",onSelect:f,onOpenControl:h}){const g=FC(t),y=new Map(g.metrics.map(b=>[b.id,b])),w=s?.label||g.label;return o.jsxs("div",{className:`wall-device-list-row state-${g.state} ${r?"selected":""}`,role:"row","aria-selected":r,tabIndex:0,onClick:f,onDoubleClick:b=>{b.preventDefault(),h()},onKeyDown:b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),f())},children:[o.jsxs("span",{className:"wall-device-name",role:"gridcell",children:[o.jsx("span",{className:"wall-device-icon","aria-hidden":"true",children:o.jsx(nr,{size:17})}),o.jsxs("span",{children:[o.jsx("strong",{children:er(t)}),o.jsxs("small",{children:["Slot ",String(n).padStart(3,"0"),t.platform?` · ${t.platform}`:"",t.arch?` · ${t.arch}`:""]})]}),r&&o.jsx(tl,{size:16,strokeWidth:3,"aria-label":"Selected"})]}),o.jsxs("span",{className:`wall-device-list-status state-${g.state} ${s?`update-${s.state}`:""}`,role:"gridcell",title:s?.error||w,children:[o.jsx("i",{"aria-hidden":"true"}),o.jsx("strong",{children:w})]}),yP.map(b=>{const S=y.get(b);return o.jsxs("span",{className:`wall-device-list-metric state-${S?.state||"unknown"}`,role:"gridcell",title:S?`${S.label}: ${S.value} · ${S.detail}`:"Not reported",children:[o.jsx("strong",{children:S?.value||"-"}),o.jsx("small",{children:S?.detail||"not reported"}),S?.ratio!==void 0&&o.jsx("i",{style:{width:`${Math.round(S.ratio*100)}%`},"aria-hidden":"true"})]},b)}),l&&o.jsx("span",{className:"wall-device-list-diagnostics",role:"gridcell",children:o.jsx(hC,{items:l,mode:u})})]})}function wP(t){if(!t)return!1;const n=String(t.platform||"").trim().toLowerCase();return fo(n)&&t.capabilities?.screenRecordingPermission===!1}function fo(t){const n=String(t||"").trim().toLowerCase();return n==="macos"||n==="darwin"||n==="mac"||n==="macosx"}function xP(t){const n=String(t||"").trim().toLowerCase();return n==="linux"||n.startsWith("linux ")}function u0(t){const n=String(t||"").trim().toLowerCase();return["win32","windows","win32nt"].includes(n)?"mode5-lzo-delta":fo(n)?"mode1-jpeg":""}function ov({device:t,frame:n,selected:r,controlEnabled:s,showStatus:l,showDeviceTitle:u=!0,monitorIndex:f,monitorCount:h,onSelect:g,onFocusDevice:y,onOpenControl:w,onCycleMonitor:b,onCanvasReady:S,sendInput:k,remoteModifierState:A,updateIndicator:T,presentationReady:j,showPresentationSpinner:I=!1,remoteDiagnostics:N,diagnosticsMode:P="remote"}){const H=d.useRef(null),F=d.useRef(null),$=d.useRef(null),D=d.useRef(0),K=d.useRef(null),z=d.useRef(null),q=d.useRef(new Map),W=d.useRef(null),Y=d.useRef(dh()),V=d.useRef(null),he=d.useRef(null),ee=FC(t),U=["cpu","gpu","memory","vram"].map(B=>ee.metrics.find(Oe=>Oe.id===B)).filter(B=>!!B),L=ny(f),le=h>1,ve=j??!!n,J=wP(t)&&!ve,Ae=I&&t.connected&&!ve&&!J,ce=qL(t,n,L),Te=ce>=Gp?100:ce/Gp*100,Fe=ce>=Gp?Gp/ce*100:100,$e={"--screen-aspect":ce.toFixed(5),"--screen-content-width":`${Math.max(1,Math.min(100,Te)).toFixed(3)}%`,"--screen-content-height":`${Math.max(1,Math.min(100,Fe)).toFixed(3)}%`},Ze=s?{transformOrigin:"0 0",transform:`translate3d(${Y.current.translateX.toFixed(2)}px, ${Y.current.translateY.toFixed(2)}px, 0) scale(${Y.current.scale.toFixed(4)})`}:void 0,de=d.useCallback(B=>{Y.current=B;const Oe=H.current;Oe&&(Oe.style.transformOrigin="0 0",Oe.style.transform=`translate3d(${B.translateX.toFixed(2)}px, ${B.translateY.toFixed(2)}px, 0) scale(${B.scale.toFixed(4)})`,Oe.dataset.touchZoom=B.scale.toFixed(2))},[]),Be=d.useCallback(B=>{if(H.current=B,B&&s){const Oe=Y.current;B.style.transformOrigin="0 0",B.style.transform=`translate3d(${Oe.translateX.toFixed(2)}px, ${Oe.translateY.toFixed(2)}px, 0) scale(${Oe.scale.toFixed(4)})`,B.dataset.touchZoom=Oe.scale.toFixed(2)}S(t.deviceId,B)},[s,t.deviceId,S]),Ve=B=>{const Oe=B.currentTarget.getBoundingClientRect();return QT(B.clientX,B.clientY,Oe)},Je=B=>aN(B,A),Qe=d.useCallback(()=>{K.current!==null&&(window.cancelAnimationFrame(K.current),K.current=null)},[]),yt=d.useCallback(()=>{const B=V.current;B&&(window.clearTimeout(B.timerId),V.current=null);const Oe=he.current;Oe&&window.clearTimeout(Oe.timerId),he.current=null},[]),ne=d.useCallback(()=>{const B=$.current;if(!B)return;$.current=null;const Oe=Number(B.input.normalizedX),We=Number(B.input.normalizedY);if(!Number.isFinite(Oe)||!Number.isFinite(We))return;k(t.deviceId,{...B.input,normalizedX:Oe,normalizedY:We})&&(D.current=performance.now())},[t.deviceId,k]),me=d.useCallback(()=>{K.current===null&&(K.current=window.requestAnimationFrame(()=>{K.current=null,ne()}))},[ne]);d.useEffect(()=>{const B=dh();return de(B),()=>{Qe(),yt(),$.current=null,z.current=null,q.current.clear(),W.current=null}},[L,de,yt,Qe,s,t.deviceId]);const Ge=(B,Oe)=>{if(!s)return;const We={type:Oe,monitorIndex:L,...Ve(B),button:oP(B.button),...Je(B)};if(Oe==="pointermove"){const et=performance.now();$.current={input:We},et-D.current>=lL&&(Qe(),ne()),me();return}$.current&&(Qe(),ne()),k(t.deviceId,We)},Se=B=>({monitorIndex:L,...Ve(B),...Je(B)}),ge=(B,Oe)=>{k(t.deviceId,{...B,type:"pointerdown",button:Oe}),k(t.deviceId,{...B,type:"pointerup",button:Oe})},Ue=(B,Oe)=>{const We=V.current;We&&(window.clearTimeout(We.timerId),V.current=null,ge(We.input,"left"));const et={tap:B,input:Oe,timerId:0};et.timerId=window.setTimeout(()=>{V.current===et&&(V.current=null,ge(Oe,"left"))},Nv),V.current=et},Me=B=>{if(B.pointerType!=="touch")return!1;if(B.preventDefault(),B.stopPropagation(),q.current.set(B.pointerId,{clientX:B.clientX,clientY:B.clientY}),B.currentTarget.setPointerCapture(B.pointerId),W.current)return!0;const Oe=z.current;if(Oe&&Oe.pointerId!==B.pointerId){const ye=q.current.get(Oe.pointerId),Ne=q.current.get(B.pointerId),He=F.current?.getBoundingClientRect();return ye&&Ne&&He&&(Qe(),$.current=null,yt(),z.current=null,W.current={gesture:YT(ye,Ne,Y.current,He),pointerIds:[Oe.pointerId,B.pointerId]}),!0}const We=performance.now(),et=V.current,it={clientX:B.clientX,clientY:B.clientY,at:We};if(et&&Nw(et.tap,it)){window.clearTimeout(et.timerId),V.current=null;const ye={...et,timerId:0};ye.timerId=window.setTimeout(()=>{he.current===ye&&(he.current=null,ge(ye.input,"left"))},Math.max(0,et.tap.at+Nv-We)),he.current=ye}else he.current=null,et&&(window.clearTimeout(et.timerId),V.current=null,ge(et.input,"left"));return z.current=ZT(B.pointerId,B.clientX,B.clientY),y(),B.currentTarget.focus(),!0},rt=B=>{if(B.pointerType!=="touch")return!1;B.preventDefault(),q.current.set(B.pointerId,{clientX:B.clientX,clientY:B.clientY});const Oe=W.current;if(Oe){const it=q.current.get(Oe.pointerIds[0]),ye=q.current.get(Oe.pointerIds[1]);if(it&&ye){const Ne=XT(Oe.gesture,it,ye);de(Ne)}return!0}const We=z.current;if(!We||We.pointerId!==B.pointerId)return!0;const et=SS(We,B.pointerId,B.clientX,B.clientY);if(z.current=et,et?.dragged&&he.current){const it=he.current;window.clearTimeout(it.timerId),he.current=null,ge(it.input,"left")}return et?.dragged&&Ge(B,"pointermove"),!0},At=B=>{if(B.pointerType!=="touch")return!1;if(B.preventDefault(),B.stopPropagation(),q.current.set(B.pointerId,{clientX:B.clientX,clientY:B.clientY}),W.current)return q.current.delete(B.pointerId),q.current.size===0&&(W.current=null),B.currentTarget.hasPointerCapture(B.pointerId)&&B.currentTarget.releasePointerCapture(B.pointerId),!0;const Oe=JT(z.current,B.pointerId,B.clientX,B.clientY,performance.now());if(Oe.kind==="ignore")return q.current.delete(B.pointerId),B.currentTarget.hasPointerCapture(B.pointerId)&&B.currentTarget.releasePointerCapture(B.pointerId),!0;q.current.delete(B.pointerId),Oe.kind==="drag"&&(Ge(B,"pointermove"),Qe(),ne()),z.current=null;const We=he.current;if(We&&window.clearTimeout(We.timerId),he.current=null,Oe.kind==="tap"&&Oe.tap){const et=Se(B);We&&Nw(We.tap,Oe.tap)?ge(et,"right"):(We&&ge(We.input,"left"),Ue(Oe.tap,et))}else We&&ge(We.input,"left");return B.currentTarget.hasPointerCapture(B.pointerId)&&B.currentTarget.releasePointerCapture(B.pointerId),!0},O=B=>{if(B.pointerType!=="touch")return!1;if(B.preventDefault(),B.stopPropagation(),q.current.delete(B.pointerId),W.current)return q.current.size===0&&(W.current=null),B.currentTarget.hasPointerCapture(B.pointerId)&&B.currentTarget.releasePointerCapture(B.pointerId),!0;if(z.current?.pointerId===B.pointerId){Qe(),$.current=null,z.current=null;const Oe=he.current;Oe&&(window.clearTimeout(Oe.timerId),ge(Oe.input,"left")),he.current=null}return B.currentTarget.hasPointerCapture(B.pointerId)&&B.currentTarget.releasePointerCapture(B.pointerId),!0},qe=d.useCallback(B=>{const Oe=document.activeElement;Oe instanceof HTMLElement&&B.contains(Oe)&&Oe.classList.contains("monitor-cycle-button")&&Oe.blur()},[]);return o.jsx("article",{className:`device-tile ${r?"selected":""} ${t.connected?"online":"offline"}`,"data-live-device-id":t.deviceId,style:$e,children:o.jsxs("div",{className:`tile-screen ${ve?"has-frame":"is-empty"}`,role:"button",tabIndex:s?-1:0,"aria-pressed":r,onClick:B=>{B.target instanceof Element&&B.target.closest(".monitor-cycle")||s||g()},onKeyDown:B=>{B.target instanceof Element&&B.target.closest(".monitor-cycle")||s||(B.key==="Enter"||B.key===" ")&&(B.preventDefault(),g())},onDoubleClick:B=>{if(!(B.target instanceof Element&&B.target.closest(".monitor-cycle"))){if(B.preventDefault(),s){B.stopPropagation();return}w()}},onPointerLeave:B=>qe(B.currentTarget),children:[o.jsx("span",{ref:F,className:`screen-content ${ve?"has-frame":"is-empty"}`,children:o.jsx("canvas",{ref:Be,className:`remote-canvas ${ve?"has-frame":"is-empty"} ${s?"control-input-enabled":""}`,"data-monitor-index":L,"data-touch-zoom":Y.current.scale.toFixed(2),style:Ze,tabIndex:s?0:-1,onPointerDown:B=>{s&&(Me(B)||(B.preventDefault(),B.stopPropagation(),y(),B.currentTarget.focus(),B.currentTarget.setPointerCapture(B.pointerId),Ge(B,"pointerdown")))},onPointerMove:B=>{s&&B.preventDefault(),!rt(B)&&Ge(B,"pointermove")},onPointerLeave:B=>{s&&B.pointerType!=="touch"&&(Ge(B,"pointermove"),Qe(),ne())},onPointerUp:B=>{s&&(At(B)||(B.preventDefault(),B.stopPropagation(),Ge(B,"pointerup"),B.currentTarget.hasPointerCapture(B.pointerId)&&B.currentTarget.releasePointerCapture(B.pointerId)))},onPointerCancel:B=>{O(B)||(s&&(B.preventDefault(),B.stopPropagation(),Ge(B,"pointerup")),B.currentTarget.hasPointerCapture(B.pointerId)&&B.currentTarget.releasePointerCapture(B.pointerId))},onWheel:B=>{s&&(B.preventDefault(),k(t.deviceId,{type:"wheel",monitorIndex:L,...Ve(B),deltaX:B.deltaX,deltaY:B.deltaY,...Je(B)}))},onContextMenu:B=>s&&B.preventDefault(),onDoubleClick:B=>{s&&(B.preventDefault(),B.stopPropagation())}},`${t.deviceId}:monitor:${L}`)}),!ve&&o.jsx("span",{className:"empty-screen",children:o.jsx(nr,{size:26})}),u&&o.jsx("span",{className:"wall-device-title",title:er(t),children:er(t)}),Ae&&o.jsxs("span",{className:"wall-presentation-loading",role:"status","aria-live":"polite",children:[o.jsx("span",{className:"wall-presentation-spinner","aria-hidden":"true"}),o.jsx("strong",{children:"Preparing video"})]}),J&&o.jsxs("span",{className:"wall-presentation-loading permission-required",role:"status","aria-live":"polite",children:[o.jsx(Ea,{size:24,"aria-hidden":"true"}),o.jsx("strong",{children:"Screen Recording permission required"}),o.jsx("small",{children:"Allow the terminal app on this Mac, then restart LiveDesk."})]}),T&&o.jsxs("span",{className:`wall-update-status state-${T.state}`,role:"status","aria-live":"polite",title:T.error||T.label,children:[T.state==="updated"?o.jsx(tr,{size:20,"aria-hidden":"true"}):T.state==="failed"?o.jsx(vr,{size:22,"aria-hidden":"true"}):T.state==="offline"?o.jsx(bh,{size:22,"aria-hidden":"true"}):o.jsx("span",{className:"wall-update-spinner","aria-hidden":"true"}),o.jsx("strong",{children:T.label}),T.error?o.jsx("small",{children:T.error}):null]}),l&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:`tile-health-pill state-${ee.state}`,children:ee.label}),o.jsx("span",{className:"tile-metrics","aria-label":`${er(t)} status`,children:U.map(B=>o.jsxs("span",{className:`tile-metric state-${B.state}`,children:[o.jsx("b",{children:B.label}),o.jsx("em",{children:B.value}),B.ratio!==void 0&&o.jsx("i",{style:{width:`${Math.round(B.ratio*100)}%`}})]},B.id))})]}),N&&o.jsx(hC,{items:N,mode:P}),le&&o.jsxs("span",{className:"monitor-cycle","aria-label":`${er(t)} display ${L+1} of ${h}`,onPointerDown:B=>B.stopPropagation(),onClick:B=>B.stopPropagation(),onDoubleClick:B=>B.stopPropagation(),children:[o.jsx("button",{className:"monitor-cycle-button previous",onClick:B=>{B.preventDefault(),B.stopPropagation(),b(-1),B.currentTarget.blur()},title:"Previous display",type:"button",children:o.jsx(M0,{size:18})}),o.jsxs("span",{className:"monitor-cycle-count",children:["Screen ",L+1,"/",h]}),o.jsx("button",{className:"monitor-cycle-button next",onClick:B=>{B.preventDefault(),B.stopPropagation(),b(1),B.currentTarget.blur()},title:"Next display",type:"button",children:o.jsx(qv,{size:18})})]})]})})}function SP({visible:t}){const n=iL;return d.useEffect(()=>{},[n]),null}function CP({runtimeBaseUrl:t=""}){const{session:n,loading:r}=NT();SA(n?{accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:n.expires_at,user:{id:n.user.id,email:n.user.email}}:null);const{target:s,error:l,refresh:u}=ET(n),f=d.useMemo(()=>{if(!s?.active)return null;const m=s.expires_at?Date.parse(s.expires_at):Number.POSITIVE_INFINITY;return Number.isFinite(m)&&m<=Date.now()?null:s},[s]),h=d.useMemo(()=>Zb(f),[f]),g=ih(),y=t.trim().replace(/\/+$/,""),w=d.useMemo(()=>[...new Set((g?h:[y,...h,Vn]).filter(Boolean))],[g,h,y]),[b,S]=d.useState(null),[k]=d.useState(XI),[A,T]=d.useState(!1),[j,I]=d.useState(()=>typeof window>"u"?!1:!!window.navigator.standalone||window.matchMedia("(display-mode: standalone), (display-mode: fullscreen)").matches),[N,P]=d.useState(()=>typeof window<"u"&&Ow(window.matchMedia(Pw).matches,j,window.matchMedia("(pointer: coarse)").matches));d.useEffect(()=>{if(!g){S(null);return}const m=window.matchMedia("(display-mode: standalone), (display-mode: fullscreen)"),x=()=>I(m.matches||!!window.navigator.standalone),C=E=>{E.preventDefault(),S(E)},R=()=>{S(null),I(!0)};return x(),m.addEventListener("change",x),window.addEventListener("beforeinstallprompt",C),window.addEventListener("appinstalled",R),()=>{m.removeEventListener("change",x),window.removeEventListener("beforeinstallprompt",C),window.removeEventListener("appinstalled",R)}},[g]);const H=d.useCallback(async()=>{const m=b;if(!m){k.isIos&&T(!0);return}S(null);try{await m.prompt(),(await m.userChoice).outcome==="accepted"&&I(!0)}catch(x){S(m),console.warn("[LiveDesk] PWA install prompt failed.",x)}},[k.isIos,b]);d.useEffect(()=>{const m=window.matchMedia(Pw),x=window.matchMedia("(pointer: coarse)"),C=()=>P(Ow(m.matches,j,x.matches));return C(),m.addEventListener("change",C),x.addEventListener("change",C),()=>{m.removeEventListener("change",C),x.removeEventListener("change",C)}},[j]),d.useLayoutEffect(()=>{const m=document.documentElement,x=()=>{m.classList.remove("livedesk-mobile-console-active"),m.style.removeProperty("--livedesk-mobile-viewport-height"),m.style.removeProperty("--livedesk-mobile-viewport-top"),m.style.removeProperty("--livedesk-mobile-viewport-width"),m.style.removeProperty("--livedesk-mobile-viewport-left"),m.style.removeProperty("--livedesk-mobile-ios-top-guard")};if(!N){x();return}m.classList.add("livedesk-mobile-console-active");const C=window.visualViewport,R=document.createElement("div");R.setAttribute("aria-hidden","true"),R.style.cssText="position:fixed;visibility:hidden;pointer-events:none;padding-top:env(safe-area-inset-top);",document.body.appendChild(R);let E=0;const X=()=>{E=0;const te=Math.max(window.innerHeight,document.documentElement.clientHeight),oe=SN(C,te,window.innerWidth,j||k.isIos,j||k.isIos||k.isAndroid),ie=Number.parseFloat(window.getComputedStyle(R).paddingTop),nt=xN({isIos:k.isIos,standalone:j,safeAreaTop:ie,screenHeight:window.screen.height,layoutViewportHeight:te});m.style.setProperty("--livedesk-mobile-viewport-height",`${oe.height}px`),m.style.setProperty("--livedesk-mobile-viewport-top",`${oe.offsetTop}px`),m.style.setProperty("--livedesk-mobile-viewport-width",`${oe.width}px`),m.style.setProperty("--livedesk-mobile-viewport-left",`${oe.offsetLeft}px`),m.style.setProperty("--livedesk-mobile-ios-top-guard",`${nt}px`)},Q=()=>{E||(E=window.requestAnimationFrame(X))};return X(),C?.addEventListener("resize",Q),C?.addEventListener("scroll",Q),window.addEventListener("resize",Q),window.addEventListener("orientationchange",Q),window.addEventListener("pageshow",Q),()=>{E&&window.cancelAnimationFrame(E),C?.removeEventListener("resize",Q),C?.removeEventListener("scroll",Q),window.removeEventListener("resize",Q),window.removeEventListener("orientationchange",Q),window.removeEventListener("pageshow",Q),R.remove(),x()}},[k.isAndroid,k.isIos,N,j]);const[F,$]=d.useState(HL),D=d.useMemo(()=>w.some(m=>!!om(m)),[w]),K=g?!!n:!D||F,{status:z,devices:q,error:W,refresh:Y,hubBaseUrl:V}=RT(w,K,n?.access_token||""),[he,ee]=d.useState(!1);d.useEffect(()=>{if(!z?.started){ee(!1);return}const m=new AbortController;return lt("/api/settings",{signal:m.signal},V).then(x=>{ee(x.settings?.connection?.showThisComputer===!0)}).catch(x=>{m.signal.aborted||(ee(!1),console.warn("[LiveDesk] Computer visibility setting could not be loaded.",x))}),()=>m.abort()},[V,z?.started]);const{entitlement:U,licensed:L,loading:le,error:ve,refresh:J}=jT(n),[Ae,ce]=d.useState([]),[Te,Fe]=d.useState(""),[$e,Ze]=d.useState(""),[de,Be]=d.useState(""),[Ve,Je]=d.useState(""),[Qe,yt]=d.useState(""),[ne,me]=d.useState("idle"),[Ge,Se]=d.useState(!1),[ge,Ue]=d.useState(""),[Me,rt]=d.useState(null),At=d.useRef(null),[O,qe]=d.useState(""),B=d.useRef("");B.current=Ve;const[Oe,We]=d.useState(!1),[et,it]=d.useState([]),ye=d.useRef(null),Ne=d.useRef(null),He=d.useRef(null),pe=d.useRef(!1),ae=d.useRef({key:"",source:"",at:0}),[fe,Ee]=d.useState(!1),[je,De]=d.useState(!1),Et=d.useRef(""),at=d.useRef(new Map),ft=d.useRef(0),jt=d.useRef(!1),Ut=d.useRef(""),wt=d.useRef(null);wt.current||(wt.current=kN());const Wt=d.useRef(document.visibilityState==="visible"),[gt,yn]=d.useState({}),mt=d.useRef({}),ha=d.useRef(new Set),hn=d.useRef(new Map),na=d.useRef(new Map),[za,G]=d.useState({}),ot=d.useMemo(()=>new Set(Object.keys(gt)),[gt]),Pt=d.useCallback((m,x)=>{if(!m)return;const C={...mt.current};x?C[m]=x:delete C[m],mt.current=C,yn(C)},[]),an=d.useCallback((m,x)=>{m&&G(C=>{if(!!C[m]===x)return C;const R={...C};return x?R[m]=!0:delete R[m],R})},[]),Dr=d.useCallback((m,x)=>{m&&na.current.set(m,{paused:x,expiresAt:Date.now()+bL})},[]),[_t,vn]=d.useState(""),[se,ze]=d.useState(""),[st,Lt]=d.useState(!1),Sn=d.useRef(null),on=d.useRef(null);d.useEffect(()=>{_t==="auth"&&n?.access_token&&vn("")},[_t,n?.access_token]);const[xt,Jt]=d.useState(""),[In,zn]=d.useState(null),Cn=d.useRef(null),bn=d.useRef(0),kn=d.useCallback((m,x,C)=>{const R=String(m||"").trim();if(Jt(R),Cn.current!==null&&(window.clearTimeout(Cn.current),Cn.current=null),!R){zn(null);return}const E=++bn.current;if(zn({id:E,message:R,tone:x}),!C)return;const X=window.setTimeout(()=>{zn(Q=>Q?.id===E?null:Q),Cn.current===X&&(Cn.current=null)},5e3);Cn.current=X},[]),Ce=d.useCallback((m,x="info")=>{kn(m,x,!0)},[kn]),Ln=d.useCallback(m=>{kn(m,"progress",!1)},[kn]);d.useEffect(()=>()=>{Cn.current!==null&&window.clearTimeout(Cn.current)},[]);const[En,$n]=d.useState(()=>typeof window<"u"&&window.location.pathname.startsWith("/support")?"support":"wall");d.useEffect(()=>{const m=()=>{$n(window.location.pathname.startsWith("/support")?"support":x=>x==="support"?"wall":x)};return window.addEventListener("popstate",m),()=>window.removeEventListener("popstate",m)},[]);const[Un,go]=d.useState(tP),jn=zN(Un),ri=d.useCallback(m=>{const x=xm(m);go(x),nP(x)},[]),vo=d.useCallback(m=>{ri(m==="list"?mh:m==="medium"?FN:xu)},[ri]),si=$N(Un),Ri=d.useMemo(()=>({"--wall-tile-min-width":`${si}px`}),[si]),yr=jn==="list"?"List view":`${jn==="medium"?"Small":"Large"} tiles, ${si} pixel minimum width`,[Da,vs]=d.useState(XL),br=Iv(Da),[_s,ii]=d.useState(JL),[ln,Ei]=d.useState(!1),[nn,oi]=d.useState(!1),[wr,Os]=d.useState(!1),[xr,Fs]=d.useState(!1),[rl,qr]=d.useState(Date.now),Ir=d.useRef(null);d.useEffect(()=>()=>{Ir.current!==null&&window.clearTimeout(Ir.current)},[]);const[Bs,hc]=d.useState(vP),[Wr,gc]=d.useState(!1),[yo,Lr]=d.useState(!1),[ys,Cu]=d.useState(!1),[bs,Hs]=d.useState(BL),[Ct]=d.useState(VL),sl=N?_s:Ct.showScreenStatus,[Kn]=d.useState(QL),[bo]=d.useState(WL),[Kt,$a]=d.useState(bo.selections),wo=d.useRef({...bo.topologyFingerprints}),Gr=d.useRef({}),Vr=d.useRef({...bo.selections}),[$t,Ua]=d.useState(null),[Pr,ji]=d.useState({}),Di=d.useRef(new Set),[il,Pn]=d.useState([]),[Qn,li]=d.useState(br),[Kr,ku]=d.useState(""),[ol,vc]=d.useState(0),[xo,Ii]=d.useState(0),[yc,Li]=d.useState(0),[$d,bc]=d.useState(()=>new Set),gn=d.useRef(new Map),ir=d.useRef(new Map),ci=d.useRef(new Map),qn=d.useRef(new Map),So=d.useRef(null),Co=d.useRef(new Map),zs=d.useRef(new Set),Pi=d.useRef(new Map),ll=d.useRef(new Map),ko=d.useRef(new Map),$s=d.useRef(new Map),cl=d.useRef(new WeakMap),Mu=d.useRef(new WeakMap),_i=d.useRef(""),Sr=d.useRef(null),Ud=d.useRef(Promise.resolve()),Au=d.useRef(0),ul=d.useRef(null),_r=d.useRef(null),wc=d.useRef(""),qa=d.useRef(new Map),dl=d.useRef(null),xc=d.useRef(0),ui=d.useRef(new Map),Tu=d.useRef(typeof window<"u"&&new URLSearchParams(window.location.search).get("livedeskTransmissionProbe")==="1"),fl=d.useRef(new Map),Mo=d.useRef([]),km=d.useRef(0),[Sc,Nu]=d.useState({}),di=d.useRef(new Map),[Cc,kc]=d.useState({}),fi=d.useRef(null),[qd,or]=d.useState(!1),Ru=d.useRef(null),Mm=d.useRef(0),Us=d.useRef(null),ml=d.useRef(new Map),lr=d.useRef(null),Qr=d.useRef(null),Wa=d.useRef(null),pl=d.useRef(!1),Wd=d.useRef(0),Wn=d.useRef(0),ga=d.useRef(""),Gd=d.useRef(Promise.resolve()),Ao=d.useRef(""),Rt=d.useRef(null),Yr=d.useRef(""),To=d.useRef(null),hl=d.useRef(0),Mc=d.useRef(""),Oi=d.useRef(new Map),la=d.useRef(new Map),Fi=d.useRef(performance.now()),No=d.useRef(new Map),ws=d.useRef(new Map),Bi=d.useRef(new Map),Hi=d.useRef(new Map),zi=d.useRef(new Map),Ro=d.useRef(new Map),Ga=d.useRef(document.visibilityState==="visible"),Xr=d.useRef(1),Eo=d.useRef([]),[Ia,Am]=d.useState(document.visibilityState==="visible"),[Zr,gl]=d.useState(0),jo=d.useRef(0),Ac=d.useRef(0),qs=d.useRef(0),Tc=d.useRef(0),Eu=d.useRef(0),ju=d.useRef(new Map),Nc=d.useRef([]),Tm=d.useRef(new Map),Nm=d.useRef(new Map),Ws=d.useRef(new Map),Rc=d.useRef(new Set),$i=d.useCallback(m=>H1(cl.current,m),[]),Va=d.useCallback(m=>Yv(Mu.current,m),[]),Gs=d.useCallback((m,x)=>fw(Mu.current,m,x),[]),cn=d.useCallback(m=>{const x=dw(cl.current,m);return dw(Mu.current,m),x},[]),xs=d.useCallback((m,x)=>fw(cl.current,m,x),[]),Du=d.useCallback(m=>_r.current===m||So.current===m?!0:[gn.current,ir.current,ci.current,qn.current,qa.current].some(C=>Array.from(C.values()).some(R=>R===m)),[]),va=d.useCallback(m=>{m&&(cn(m),Rc.current.add(m),U1(m,{isCurrent:Du,dispose:Md,schedule:x=>queueMicrotask(()=>{try{x()}finally{Rc.current.delete(m)}})}))},[Du,cn]),ya=d.useCallback(m=>(cn(m),Th(m,Md)),[cn]),Iu=d.useCallback(()=>{const m=_r.current,x=So.current,C=[...Rc.current];_r.current=null,So.current=null,Rc.current.clear(),cl.current=new WeakMap,Mu.current=new WeakMap,$s.current.clear(),wc.current="",$1([gn.current,ir.current,ci.current,qn.current,qa.current],[m,x,...C],Md),dl.current=null,xc.current=0,Co.current.clear(),zs.current.clear(),Pi.current.clear(),ll.current.clear(),ko.current.clear(),ui.current.clear(),fl.current.clear(),Mo.current.length=0,di.current.clear(),ha.current.clear()},[]);d.useEffect(()=>()=>{Iu()},[Iu]);const _n=d.useCallback((m,x)=>{const C=ma(m,x),R=performance.now();Oi.current.delete(C),la.current.delete(C),No.current.delete(C),ws.current.delete(C),Ro.current.delete(C),Ws.current.delete(C),di.current.delete(C),ui.current.delete(C),kc(E=>{if(!Object.prototype.hasOwnProperty.call(E,C))return E;const X={...E};return delete X[C],X}),Nu(E=>{if(!Object.prototype.hasOwnProperty.call(E,C))return E;const X={...E};return delete X[C],X}),m==="control"?(Bi.current.delete(C),Hi.current.set(C,R)):zi.current.set(C,R)},[]),[Ui,Ss]=d.useState(null),[vl,Vd]=d.useState(!1),[Jr,Kd]=d.useState([]),[Cr,Rm]=d.useState("all"),[mi,pi]=d.useState([]),[Em,Lh]=d.useState(!1),[jm,Dm]=d.useState(!0),Or=d.useRef(null),Do=d.useRef(null),yl=d.useRef(null),Lu=d.useRef(null),Ec=d.useRef(!1),kr=d.useRef(!1),cr=d.useRef(0),Ka=d.useRef(0),ba=d.useRef(0),ca=d.useRef(0),es=d.useRef(0),jc=d.useRef(""),Io=En==="settings",Pu=En==="pricing",Qd=En==="doc",wa=En==="support",rn=En==="share-files",Vt=En==="agents",Fr=!Io&&!Pu&&!Qd&&!wa&&!rn&&!Vt,ct=En==="control",_u=TN(En),xa=Ia&&En==="wall",Yd=d.useRef(xa);Yd.current=xa;const Im=_u&&Nc.current.length>0,ts=Ia&&(En==="wall"||ct||Im),ns=d.useRef(ts);ns.current=ts;const bl=Ia&&(ct||xa),qi=Ia&&(bl||_u&&(ne==="connecting"||ne==="active")),hi=d.useRef({active:ts,epoch:Xr.current});hi.current.active!==ts&&(Xr.current+=1,hi.current={active:ts,epoch:Xr.current}),d.useEffect(()=>{Fr||(Ei(!1),oi(!1),Os(!1))},[Fr]);const Ht=Ct.frameMode==="mode4-h264-atlas",ua=Qe||Kn.frameMode,Br=ua!=="mode3-h264-hw"?Math.min(30,Kn.fps):Kn.fps,Wi=q.find(m=>m.deviceId===$e),Xd=Wi?.platform,wl=Wi?Ls(Wi,Kt[Wi.deviceId]):0,Lo=Wi?by(Wi,wl):null,Gi=xP(Xd)?{maxWidth:1280,maxHeight:720}:Kx,Sa=ua!=="mode3-h264-hw"?{maxWidth:1920,maxHeight:1080}:Kx,Po={maxWidth:Math.min(Sa.maxWidth,Gi.maxWidth,Kn.maxWidth),maxHeight:Math.min(Sa.maxHeight,Gi.maxHeight,Kn.maxHeight)},Cs={maxWidth:Lo?.width?Math.min(Po.maxWidth,Lo.width):Po.maxWidth,maxHeight:Lo?.height?Math.min(Po.maxHeight,Lo.height):Po.maxHeight};d.useEffect(()=>{if(z?.started){if(!n?.access_token){lt("/api/remote/license",{method:"DELETE"},V).catch(()=>{});return}lt("/api/remote/license/sync",{method:"POST",headers:{Authorization:`Bearer ${n.access_token}`}},V).catch(m=>{console.warn("[LiveDesk] Hub license sync failed",m)})}},[U?.updated_at,V,n?.access_token,z?.started]),d.useEffect(()=>{!n?.access_token||!z?.started||z.runtimeRole!=="hub"||!z.deviceId||(async()=>{try{const{data:m,error:x}=await zt.rpc("register_livedesk_device",{p_device_id:z.deviceId,p_device_name:z.deviceName||z.deviceId,p_role:"hub",p_assigned_hub_id:null,p_platform:navigator.platform||navigator.userAgent,p_os_version:navigator.userAgent,p_app_version:z.managerVersion||z.managerPackage||""}),C=Array.isArray(m)?m[0]:m;(x||C?.ok===!1)&&console.warn("[LiveDesk] Hub device role registration failed",x||C?.reason||"unknown-error")}catch(m){console.warn("[LiveDesk] Hub device role registration failed",m)}})()},[n?.access_token,z?.deviceId,z?.deviceName,z?.managerPackage,z?.managerVersion,z?.runtimeRole,z?.started]);const Zd=z?.runtimeRole==="hub"?String(z.deviceId||"").trim():"",St=d.useMemo(()=>q.filter(m=>m.connected&&(N||he||!Zd||m.deviceId!==Zd)),[q,Zd,N,he]);d.useEffect(()=>{const m={...mt.current},x=Date.now();let C=!1;G(R=>{const E={...R};let X=!1;for(const Q of q){const te=String(Q.liveCapturePause?.token||"").trim(),oe=na.current.get(Q.deviceId);if(oe)if((oe.paused?!!te:!te)||oe.expiresAt<=x)na.current.delete(Q.deviceId);else continue;const ie=!!te&&(Q.liveCapturePause?.captureStopConfirmed!==!0||Q.liveCapturePause?.phase==="stop-unconfirmed");!!E[Q.deviceId]!==ie&&(X=!0,ie?E[Q.deviceId]=!0:delete E[Q.deviceId])}return X?E:R});for(const R of q){const E=String(R.liveCapturePause?.token||"").trim(),X=String(m[R.deviceId]||""),Q=na.current.get(R.deviceId);if(Q)if((Q.paused?!!E:!E)||Q.expiresAt<=x)na.current.delete(R.deviceId);else continue;E&&E!==X?(m[R.deviceId]=E,C=!0):!E&&X&&(delete m[R.deviceId],hn.current.delete(R.deviceId),C=!0)}C&&(mt.current=m,yn(m))},[q]);const Lm=Cr==="all"?St.length:mi.filter(m=>St.some(x=>x.deviceId===m)).length,aa=d.useMemo(()=>St.reduce((m,x)=>Math.max(m,l0(x.slotNumber)),0),[St]),Dc=Math.max(ZI,St.length,aa),ks=d.useMemo(()=>{const m=Array(Dc).fill(null),x=[];for(const C of St){const R=l0(C.slotNumber);R>0&&R<=Dc&&!m[R-1]?m[R-1]=C:x.push(C)}for(const C of x){const R=m.findIndex(E=>!E);R<0?m.push(C):m[R]=C}return m},[St]),xl=d.useMemo(()=>ks.flatMap((m,x)=>m?[{device:m,slotNumber:x+1}]:[]),[ks]),Sl=d.useMemo(()=>St.map(m=>m.deviceId),[St]),as=d.useMemo(()=>new Set(Ae),[Ae]),Yn=d.useMemo(()=>St.filter(m=>as.has(m.deviceId)),[St,as]),Cl=d.useMemo(()=>q.find(m=>m.deviceId===Te)||Yn[0]||null,[q,Te,Yn]),Ca=d.useMemo(()=>q.find(m=>m.deviceId===$e)||null,[$e,q]),Ms=Ca?Ls(Ca,Kt[Ca.deviceId]):0,Pe=ct?Ca:Cl,Vi=d.useMemo(()=>new Set(mi),[mi]),Jd=d.useMemo(()=>Cr==="all"?St.map(m=>m.deviceId):St.filter(m=>Vi.has(m.deviceId)).map(m=>m.deviceId),[St,Vi,Cr]),Fu=Pe?nh(Pe,"control"):!1,Bu=fo(Pe?.platform)&&(Pe?.capabilities?.controlPermission===!1||Pe?.capabilities?.accessibilityPermission===!1),Qa=Pe?nh(Pe,"audio")||nh(Pe,"remoteAudio"):!1,Vs=(Array.isArray(Pe?.capabilities?.agentTools)?Pe.capabilities.agentTools.map(String):[]).includes("system.power"),On=L?U?.plan==="pro"?"pro":"ltd":"free",ef=ou[On],Hu=ef.limit,Ya=d.useMemo(()=>new Set(jN(St,Hu)),[Hu,St]),_o=!Pe||Ya.has(Pe.deviceId),_m=On==="free",sn=_o,As=On==="ltd"?`Plus includes up to ${em} Clients. Upgrade to Pro for commercial use and larger walls.`:`Free includes up to ${Jf} Clients. Upgrade to Plus for ${em} devices and no ads.`,Ic=On==="free",Mr=sn&&!!Pe&&Fu,Oo=sn&&!!Pe&&Qa,Ki=d.useMemo(()=>ct?Pe?[Pe]:[]:Yn.length>0?Yn:Pe?[Pe]:[],[Pe,Yn,ct]),ur=d.useMemo(()=>Ki.filter(m=>Ya.has(m.deviceId)),[Ya,Ki]),Ks=ur.some(m=>String(gt[m.deviceId]||"").startsWith("pending:")||za[m.deviceId]===!0),Xa=!(ur.length>0&&ur.every(m=>{const x=String(gt[m.deviceId]||"");return!!x&&!x.startsWith("pending:")&&za[m.deviceId]!==!0}))||Ks,kl=d.useMemo(()=>ks.filter(m=>!!m?.connected).slice(0,aP(jn)).map(m=>m.deviceId),[ks,jn]),Ml=d.useMemo(()=>ts?xa?Ht||jn==="list"?Sl:Ct.visibleOnlyLive?il.length>0?il:kl:Sl:Nc.current.length>0?Nc.current:Sl:[],[kl,Ht,il,Ct.visibleOnlyLive,Sl,ts,xa,jn]),da=d.useMemo(()=>av(Ml.filter(m=>Ya.has(m))),[Ya,Ml]);Nc.current=da;const La=d.useMemo(()=>da.filter(m=>m!==Kr&&!ot.has(m)),[ot,da,Kr]),Qi=d.useMemo(()=>new Map(St.map(m=>[m.deviceId,m.platform])),[St]),Fo=d.useMemo(()=>Object.fromEntries(St.map(m=>[m.deviceId,String(m.sessionId||"").trim()])),[St]),rs=DN(Ht,da.length),ka=d.useMemo(()=>Ht?La.filter(m=>Wf({mode4Enabled:Ht,directMode4WallEnabled:rs,isMac:fo(Qi.get(m))})==="atlas"):[],[rs,Ht,Qi,La]),Pa=d.useMemo(()=>La.filter(m=>Wf({mode4Enabled:Ht,directMode4WallEnabled:rs,isMac:fo(Qi.get(m))})==="direct"),[rs,Ht,Qi,La]),tf=d.useMemo(()=>{const m=Ct.autoStartLive?La.map(x=>ma("wall",x)):[];return qi&&sn&&de&&Ya.has(de)&&(ne==="connecting"||ne==="active"||ne==="warm")&&m.push(ma("control",de)),[...new Set(m)].sort()},[qi,de,ne,sn,Ya,Ct.autoStartLive,La]);d.useEffect(()=>{const m=new Set(da);bc(x=>{let C=!1;const R=new Set;for(const E of x)m.has(E)?R.add(E):C=!0;return C?R:x})},[da]);const Om=d.useMemo(()=>{const m=E=>St.find(X=>X.deviceId===E)||null,x=E=>{const X=m(E);return X?Ls(X,Kt[E]):0},C=(E,X=x(E))=>E===de&&(ne==="connecting"||ne==="active"||ne==="warm")?qn.current.get(E)||ir.current.get(E)||null:Ht?qa.current.get(E)||gn.current.get(E)||null:gn.current.get(E)||null,R=(E,X=x(E))=>{const Q=m(E);return`${Q?er(Q):E} · Monitor ${X+1}`};return{resolveCurrentTarget(){if(ct&&Ca){const oe=Ms;return{type:"control",deviceIds:[Ca.deviceId],monitorIndex:oe,label:`${er(Ca)} · Monitor ${oe+1}`,sourceCanvas:C(Ca.deviceId,oe),signature:`control:${Ca.deviceId}:${oe}:${Kn.frameMode}`}}const E=Yn.map(oe=>oe.deviceId).filter(oe=>La.includes(oe)),X=Cl&&La.includes(Cl.deviceId)?Cl.deviceId:"",Q=E.length>0?E:X?[X]:La,te=E.length===0&&!X;if(Q.length===0)return null;if(Q.length===1){const oe=Q[0],ie=x(oe);return{type:te?"wall":E.length>1?"selection":"device",deviceIds:Q,monitorIndex:ie,label:te?"Wall":R(oe,ie),sourceCanvas:te?null:C(oe,ie),signature:`${te?"wall":"device"}:${oe}:${ie}:${Ht?"atlas":"direct"}`}}return{type:E.length>1?"selection":"wall",deviceIds:Q,label:E.length>1?`${Q.length} selected Clients`:"Wall",sourceCanvas:null,signature:`${E.length>1?"selection":"wall"}:${Q.join(",")}:${jn}`}},getDeviceCanvas:C,composeWall(E,X={}){return BI(E.map(Q=>{const te=x(Q);return{deviceId:Q,label:R(Q,te),canvas:C(Q,te)}}),X)}}},[St,Ca,de,ne,Kn.frameMode,gn,Ht,Kt,Ms,Yn,ct,La,Cl,jn]),Bo=YI({hubUrl:V,sourceRegistry:Om,onToast:Ce}),gi=d.useMemo(()=>NN({captureOwnershipActive:qi,localFeatureAccess:sn,controlSessionDeviceId:de,planAllowed:Ya.has(de),sessionState:ne,controlFocusVisible:ct,presentationCanvasMounted:ge===de,wallPresentationVisible:xa,wallPresentationCanvasMounted:gn.current.has(de)||qa.current.has(de),decoderOwnerExists:qn.current.has(de)})?[de]:[],[qi,de,ne,sn,ge,Ya,ct,xa]),zu=d.useMemo(()=>av([...da,...gi]),[gi,da]),Al=d.useMemo(()=>r0(Ct,jn),[Ct,jn]),Yi=d.useMemo(()=>r0(Ct,"large"),[Ct]),Za=IN({mode4Enabled:Ht,directMode4WallEnabled:rs,adaptiveFps:Qn,directDeviceCount:Pa.length,adaptive:Ct.adaptiveLoadShedding}),wn=bN({fps:Za,maxWidth:Yi.maxWidth,maxHeight:Yi.maxHeight,quality:Ct.quality},N),Qs=_N({deviceCount:ka.length,targetFps:Qn,adaptive:Ct.adaptiveLoadShedding});Ht&&ka.length>0;const Ts=d.useCallback((m,x,C)=>{if(m.width<=0||m.height<=0)return!1;if(m===x)return!0;const R=C?Math.min(1,C.maxWidth/m.width,C.maxHeight/m.height):1,E=Math.max(1,Math.round(m.width*R)),X=Math.max(1,Math.round(m.height*R));(x.width!==E||x.height!==X)&&(x.width=E,x.height=X);const Q=x.getContext("2d",{alpha:!1});return Q?(Q.imageSmoothingEnabled=!0,Q.imageSmoothingQuality="low",Q.drawImage(m,0,0,m.width,m.height,0,0,x.width,x.height),!0):!1},[]),Lc=d.useCallback((m,x)=>{const C=Math.max(0,Number(x.clientWidth||0)),R=Math.max(0,Number(x.clientHeight||0)),E=Math.max(1,Number(window.devicePixelRatio||1)),X=C>0&&R>0?{maxWidth:Math.ceil(C*E),maxHeight:Math.ceil(R*E)}:void 0;return Ts(m,x,X)},[Ts]),Hr=d.useCallback((m,x,C)=>{if(!Tu.current)return;const R=`${m}:${x.deviceId}`,E=fl.current.get(R)||{bindingKey:"",totalPaints:0,lastPaintAt:0,lastFrameSeq:0};E.bindingKey=lo(x),E.totalPaints+=1,E.lastPaintAt=performance.now(),E.lastFrameSeq=Number(x.frameSeq||0),fl.current.set(R,E);const X=++km.current,Q={sequence:X,scope:m,deviceId:x.deviceId,bindingKey:E.bindingKey,frameSeq:E.lastFrameSeq,paintedAt:E.lastPaintAt,sourceGapMs:Number(x.sourceGapMs||0),agentSendGapMs:Number(x.agentSendGapMs||0),agentSendDurationMs:Number(x.agentSendDurationMs||0),agentSendDurationFrameSeq:Number(x.agentSendDurationFrameSeq||0),agentFrameAgeMs:Number(x.agentFrameAgeMs||0),timestampUs:Number(x.timestampUs||0),queuedForMs:Number(C?.queuedForMs||0),decodedForMs:Number(C?.decodedForMs||0),scheduledForMs:Number(C?.scheduledForMs||0),interactiveBurstOutputWindowMs:Number(C?.interactiveBurstOutputWindowMs||0),interactiveBurstTailHoldCount:Number(C?.interactiveBurstTailHoldCount||0)};Mo.current[(X-1)%SL]=Q},[]),Gn=d.useCallback(m=>{m&&bc(x=>{if(x.has(m))return x;const C=new Set(x);return C.add(m),C})},[]),un=d.useCallback(m=>{m&&bc(x=>{if(!x.has(m))return x;const C=new Set(x);return C.delete(m),C})},[]),Ys=d.useCallback((m,x)=>{if(!x||x.width<=0||x.height<=0)return!1;const C=document.createElement("canvas");if(C.width=x.width,C.height=x.height,!Ts(x,C))return va(C),!1;const R=ci.current.get(m);return ci.current.set(m,C),R&&R!==C&&ya(R),Gn(m),!0},[Gn,Ts,ya,va]),Mn=d.useCallback(m=>{z1(ci.current,m,Md)},[]),Ot=d.useCallback((m,x)=>{const C=ci.current.get(m),R=gn.current.get(m)===x||qa.current.get(m)===x;return mt.current[m]?(Mn(m),!1):!C||!R||C.width<=0||C.height<=0?!1:Ts(C,x)?!0:(Mn(m),!1)},[Ts,Mn]),Qt=d.useCallback((m,x=!1,C)=>{if(mt.current[m]||!zs.current.has(m))return!1;const R=Math.max(1,Math.min(br,ta.controlWallReuseMaxFps,Br)),E=performance.now(),X=ll.current.get(m)||0,Q=qn.current.get(m)||ir.current.get(m),te=gn.current.get(m)||qa.current.get(m);if(!Q||!te||!te.isConnected)return!1;const oe=EN({cadenceCredit:Pi.current.get(m)||0,targetFps:R,sourceFps:Br,elapsedSincePaintMs:X>0?E-X:0,nowMs:E,scheduledPaintAtMs:ko.current.get(m)||0,force:x});if(!oe.shouldPaint)return Pi.current.set(m,oe.nextCadenceCredit),!1;const ie=Math.max(0,Number(te.clientWidth||0)),nt=Math.max(0,Number(te.clientHeight||0)),Ye=Math.max(1,Number(window.devicePixelRatio||1)),Ie=ie>0&&nt>0?{maxWidth:Math.min(Al.maxWidth,Math.ceil(ie*Ye)),maxHeight:Math.min(Al.maxHeight,Math.ceil(nt*Ye))}:Al;return Ts(Q,te,Ie)?(Pi.current.set(m,oe.nextCadenceCredit),oe.nextScheduledPaintAtMs>0&&ko.current.set(m,oe.nextScheduledPaintAtMs),ll.current.set(m,performance.now()),oe.sourceCadencePassthrough&&(Pi.current.delete(m),ko.current.delete(m)),C&&Hr("wall-reuse-visible",C),Gn(m),Mn(m),!0):!1},[Br,Al,Gn,Ts,Hr,Mn,br]);d.useEffect(()=>{_i.current=Kr},[Kr]);const Fn=d.useCallback((m,x)=>{const C=Us.current;if(!C||C.deviceId!==m)return;const R=Date.now();ml.current.set(m,{...C,source:x,completedAtEpochMs:R,durationMs:Math.max(0,performance.now()-C.startedAt)}),Us.current=null},[]),Pc=d.useCallback((m,x)=>{const C=gn.current.get(m);if(x&&C&&C!==x&&Ys(m,C),x){if(gn.current.set(m,x),C&&C!==x&&va(C),mt.current[m]){Mn(m),ya(x),un(m);return}ci.current.get(m)&&Ot(m,x)&&Gn(m),Qt(m,!0);return}if(C&&ns.current&&Nc.current.includes(m)){Ys(m,C),gn.current.delete(m),va(C);return}gn.current.delete(m),Mn(m),va(C),un(m)},[un,Gn,Qt,Ot,Ys,ya,Mn,va]),Tl=d.useCallback((m,x)=>{const C=ir.current.get(m);if(x){ir.current.set(m,x),Ue(m),C&&C!==x&&va(C);const R=de===m&&Ge?qn.current.get(m):null;R&&Lc(R,x)&&m===$e&&(Fn(m,"warm-reuse"),or(!0)),R&&R!==x&&RN({decodeWidth:R.width,decodeHeight:R.height,presentationCssWidth:x.getBoundingClientRect().width,presentationCssHeight:x.getBoundingClientRect().height,devicePixelRatio:window.devicePixelRatio,sourceWidth:Cs.maxWidth,sourceHeight:Cs.maxHeight})&&(qn.current.set(m,x),va(R));return}ir.current.delete(m),Ue(R=>R===m?"":R),va(C)},[Fn,$e,de,Ge,Cs.maxHeight,Cs.maxWidth,Lc,va]),Xs=d.useCallback((m,x,C)=>{const R=performance.now(),E=ma(m,C.deviceId);let X=C;if(m==="control"&&C.visualChanged){const oe=String(x.inputFeedbackEventId||""),ie=Number(x.inputFeedbackInputSeq||0),nt=Number(x.inputFeedbackIssuedAtEpochMs||0),Ye=Number(x.browserReceivedEpochMs||0),Ie=Tm.current.get(C.deviceId)||"",Nt=nt>0?Math.max(0,Date.now()-nt):Number.POSITIVE_INFINITY;if(oe.length>0&&ie>0&&oe!==Ie&&Nt<=tv){const tt=Nm.current.get(C.deviceId)||[];tt.push(Nt),tt.length>Hx&&tt.splice(0,tt.length-Hx),Nm.current.set(C.deviceId,tt),X={...C,inputFeedbackSeq:ie,inputFeedbackMs:Nt,inputFeedbackAt:R,inputFeedbackExact:!0,inputFeedbackEventId:oe,inputFeedbackInputType:x.inputFeedbackInputType,inputFeedbackInputToFrameMs:Ye>0?Math.max(0,Ye-nt):void 0,inputFeedbackFrameToPaintMs:Ye>0?Math.max(0,Date.now()-Ye):void 0,inputFeedbackAgentApplyMs:x.inputFeedbackAgentApplyMs,inputFeedbackApplyToCaptureMs:x.inputFeedbackApplyToCaptureMs,inputFeedbackSampleCount:tt.length,inputFeedbackP50Ms:Qf(tt,.5),inputFeedbackP95Ms:Qf(tt,.95)},Tm.current.set(C.deviceId,oe),ju.current.set(C.deviceId,ie)}else if(!oe){const tt=FT(C.deviceId),ut=ju.current.get(C.deviceId)||0,pt=tt?R-tt.sentAt:Number.POSITIVE_INFINITY;tt&&tt.inputSeq>ut&&pt<=tv&&(X={...C,inputFeedbackSeq:tt.inputSeq,inputFeedbackMs:Math.max(0,pt),inputFeedbackAt:R,inputFeedbackExact:!1},ju.current.set(C.deviceId,tt.inputSeq))}}la.current.set(E,R),Ro.current.delete(E),Ws.current.delete(E);const Q=ui.current.get(E)||{totalFrames:0,totalChangedFrames:0,sampleFrames:0,sampleChangedFrames:0,sampleStartedAt:R,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleDecoderInputBase:0,sampleDecoderOutputBase:0},te=lo(x);Q.bindingKey!==te&&(Q.bindingKey=te,Q.lastAt=void 0,Q.lastFrameSeq=void 0,Q.sampleChangedFrames=0,Q.sampleDecoderInputBase=Number(C.decoderInputCount||0),Q.sampleDecoderOutputBase=Number(C.decoderOutputCount||0),Wp(Q,R)),m==="control"&&X.inputFeedbackMs===void 0&&Q.lastInfo?.inputFeedbackMs!==void 0&&Q.lastInfo.inputFeedbackAt!==void 0&&R-Q.lastInfo.inputFeedbackAt<=tv&&(X={...X,inputFeedbackSeq:Q.lastInfo.inputFeedbackSeq,inputFeedbackMs:Q.lastInfo.inputFeedbackMs,inputFeedbackAt:Q.lastInfo.inputFeedbackAt,inputFeedbackExact:Q.lastInfo.inputFeedbackExact,inputFeedbackEventId:Q.lastInfo.inputFeedbackEventId,inputFeedbackInputType:Q.lastInfo.inputFeedbackInputType,inputFeedbackInputToFrameMs:Q.lastInfo.inputFeedbackInputToFrameMs,inputFeedbackFrameToPaintMs:Q.lastInfo.inputFeedbackFrameToPaintMs,inputFeedbackAgentApplyMs:Q.lastInfo.inputFeedbackAgentApplyMs,inputFeedbackApplyToCaptureMs:Q.lastInfo.inputFeedbackApplyToCaptureMs,inputFeedbackSampleCount:Q.lastInfo.inputFeedbackSampleCount,inputFeedbackP50Ms:Q.lastInfo.inputFeedbackP50Ms,inputFeedbackP95Ms:Q.lastInfo.inputFeedbackP95Ms}),Q.totalFrames+=1,Q.sampleFrames+=1,Qx(Q,R,X.frameSeq),X.visualChanged&&(Q.totalChangedFrames+=1,Q.sampleChangedFrames+=1),Q.lastInfo=X,ui.current.set(E,Q)},[]),Ho=d.useCallback((m,x)=>{if(mt.current[m.deviceId]||_i.current===m.deviceId)return;Xs("wall",m,x);const C=Ge&&de===m.deviceId,R=gn.current.get(m.deviceId)||qa.current.get(m.deviceId);Tu.current&&!ct&&!C&&R?.isConnected&&Hr("wall-visible",m,x),m.kind==="live"&&(Gn(m.deviceId),Mn(m.deviceId)),_i.current!==m.deviceId&&!C&&(zs.current.delete(m.deviceId),Pi.current.delete(m.deviceId),ll.current.delete(m.deviceId),ko.current.delete(m.deviceId))},[de,Ge,Gn,Xs,Hr,Mn,ct]),Nl=d.useCallback((m,x)=>{if(mt.current[m.deviceId]||Jn(Wa.current,Rt.current)||!Hg(m,Rt.current))return;Xs("control",m,x),qe(Q=>Q&&"");const C=qn.current.get(m.deviceId),R=ir.current.get(m.deviceId);let E=!1;C&&C.width>0&&C.height>0&&(R&&ct&&m.deviceId===$e&&(E=Lc(C,R),E&&Hr("control-visible",m,x)),Co.current.set(m.deviceId,du(m)),zs.current.add(m.deviceId),m.deviceId===de&&(Se(!0),me(Q=>Q==="connecting"?"active":Q)),Qt(m.deviceId,!1,m));const X=Ru.current;!X||!wL(X,m)||!E||(Fn(m.deviceId,"fresh-frame"),or(!0))},[Fn,$e,de,Qt,Lc,Xs,Hr,ct]),ss=d.useCallback((m,x)=>{const C=performance.now(),R=ma(m,x.deviceId);Oi.current.set(R,C),ws.current.delete(R),m==="control"?Bi.current.delete(R):zi.current.delete(R);const E=di.current.get(R)||{totalFrames:0,sampleFrames:0,sampleStartedAt:C,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleBytes:0,sampleH264Frames:0,sampleTinyFrames:0,sampleRepeatedFrames:0,sourceSendIntervalsMs:[]},X=lo(x);if(E.bindingKey!==X&&(E.bindingKey=X,E.lastAt=void 0,E.lastFrameSeq=void 0,E.lastContentHash=void 0,E.sampleBytes=0,E.sampleH264Frames=0,E.sampleTinyFrames=0,E.sampleRepeatedFrames=0,E.sourceSendIntervalsMs.length=0,Wp(E,C)),E.totalFrames+=1,E.sampleFrames+=1,E.sampleBytes+=Math.max(0,Number(x.byteLength||0)),String(x.frameMode||x.mode||x.codec||x.mimeType||"").toLowerCase().includes("h264")){E.sampleH264Frames+=1,Number(x.byteLength||0)<=hL&&(E.sampleTinyFrames+=1);const ie=String(x.contentHash||"");ie&&E.lastContentHash===ie&&(E.sampleRepeatedFrames+=1),E.lastContentHash=ie}const oe=Number(x.agentSendGapMs||0);oe>0&&oe<1e3&&DC(E.sourceSendIntervalsMs,oe),E.lastFrame=du(x),Qx(E,C,x.frameSeq),di.current.set(R,E)},[]);d.useEffect(()=>{const m=new Set(tf);for(const R of ui.current.keys())m.has(R)||ui.current.delete(R);for(const R of di.current.keys())m.has(R)||di.current.delete(R);const x=R=>{const E=Object.entries(R).filter(([X])=>m.has(X));return E.length===Object.keys(R).length?R:Object.fromEntries(E)};if(Nu(x),kc(x),m.size===0)return;const C=window.setInterval(()=>{const R=performance.now(),E={},X={};for(const Q of m){const te=ui.current.get(Q);if(te){const Ye=Math.max(1,R-te.sampleStartedAt);E[Q]={bindingKey:te.bindingKey||"",totalFrames:te.totalFrames,totalChangedFrames:te.totalChangedFrames,framesPerSecond:te.sampleFrames*1e3/Ye,changedFramesPerSecond:te.sampleChangedFrames*1e3/Ye,averageIntervalMs:te.intervalCount>0?te.intervalSumMs/te.intervalCount:0,minIntervalMs:Number.isFinite(te.minIntervalMs)?te.minIntervalMs:0,maxIntervalMs:te.maxIntervalMs,p95IntervalMs:Qf(te.intervalSamplesMs,.95),intervalCount:te.intervalCount,seqGapCount:te.seqGapCount,maxSeqGap:te.maxSeqGap,decoderInputFps:Math.max(0,(Number(te.lastInfo?.decoderInputCount||0)-te.sampleDecoderInputBase)*1e3/Ye),decoderOutputFps:Math.max(0,(Number(te.lastInfo?.decoderOutputCount||0)-te.sampleDecoderOutputBase)*1e3/Ye),sampleMs:Ye,lastInfo:te.lastInfo},te.sampleDecoderInputBase=Number(te.lastInfo?.decoderInputCount||0),te.sampleDecoderOutputBase=Number(te.lastInfo?.decoderOutputCount||0),te.sampleChangedFrames=0,Wp(te,R)}const oe=di.current.get(Q);if(!oe)continue;const ie=Math.max(1,R-oe.sampleStartedAt),nt=oe.lastFrame?du(oe.lastFrame):void 0;oe.lastFrame=nt,X[Q]={totalFrames:oe.totalFrames,framesPerSecond:oe.sampleFrames*1e3/ie,averageIntervalMs:oe.intervalCount>0?oe.intervalSumMs/oe.intervalCount:0,minIntervalMs:Number.isFinite(oe.minIntervalMs)?oe.minIntervalMs:0,maxIntervalMs:oe.maxIntervalMs,p95IntervalMs:Qf(oe.intervalSamplesMs,.95),intervalCount:oe.intervalCount,seqGapCount:oe.seqGapCount,maxSeqGap:oe.maxSeqGap,averageFrameBytes:oe.sampleFrames>0?oe.sampleBytes/oe.sampleFrames:0,tinyFrameRatio:oe.sampleH264Frames>0?oe.sampleTinyFrames/oe.sampleH264Frames:0,repeatedFrameRatio:oe.sampleH264Frames>0?oe.sampleRepeatedFrames/oe.sampleH264Frames:0,sourceSendAverageMs:oe.sourceSendIntervalsMs.length>0?oe.sourceSendIntervalsMs.reduce((Ye,Ie)=>Ye+Ie,0)/oe.sourceSendIntervalsMs.length:0,sourceSendP95Ms:Qf(oe.sourceSendIntervalsMs,.95),sourceSendSampleCount:oe.sourceSendIntervalsMs.length,sampleMs:ie,lastFrame:nt},oe.sampleBytes=0,oe.sampleH264Frames=0,oe.sampleTinyFrames=0,oe.sampleRepeatedFrames=0,oe.sourceSendIntervalsMs.length=0,Wp(oe,R)}Nu(E),kc(X)},1e3);return fi.current=C,()=>{window.clearInterval(C),fi.current===C&&(fi.current=null)}},[tf]);const Fm=d.useCallback(m=>{const x=m.deviceId,C=lo(m);if(mt.current[x]||_i.current===x||m.currentGenerationVerified!==!0||$s.current.get(x)!==C)return;ss("wall",m);const R=gn.current.get(x);if(!R)return;const E=$i(R),X=Va(R),Q=()=>gn.current.get(x)!==R||!xs(R,E)||!!mt.current[x]||_i.current===x||$s.current.get(x)!==C,te=()=>Q()||!Gs(R,X),oe=ON(Ht,Ct.h264DecodeAcceleration);_g(R,m,te,Ho,oe.acceleration,oe.latencyMode,Q).catch(()=>{})},[$i,Gs,xs,Va,Ho,Ht,ss,Ct.h264DecodeAcceleration]),Bn=d.useCallback(m=>{const x=m.deviceId;if(mt.current[x]||Jn(Wa.current,Rt.current)||!Hg(m,Rt.current))return;let C=qn.current.get(x);if(!C){const Ie=ir.current.get(x),Nt=So.current;C=Ie||Nt||document.createElement("canvas"),Ie&&Nt&&Nt!==Ie&&ya(Nt),So.current=null,C!==Ie&&C.setAttribute("aria-hidden","true"),qn.current.set(x,C)}const R=C,E=m,X=$i(R),Q=Va(R),te=()=>qn.current.get(x)!==R||!xs(R,X)||!!mt.current[x]||!Hg(E,Rt.current),oe=()=>te()||!Gs(R,Q),ie=B.current,nt=String(m.frameMode||m.mode||m.codec||m.mimeType||"").toLowerCase().includes("h264");nt||ss("control",m);const Ye=_g(R,m,oe,Nl,Kn.h264DecodeAcceleration,"interactive",te);nt&&ss("control",m),Ye.catch(Ie=>{B.current!==ie||qn.current.get(x)!==R||!Gs(R,Q)||te()||de!==x||qe(Ie instanceof Error?Ie.message:String(Ie||"Control H.264 decode failed"))})},[$i,Gs,xs,Va,de,Kn.h264DecodeAcceleration,Nl,ss,ya]),nf=d.useCallback(m=>{const x=_r.current;_r.current=m,x&&x!==m&&va(x),jo.current=0,Ac.current=0,qs.current=0,Tc.current=0,Eu.current=0,xc.current=0},[va]),Xi=d.useCallback(()=>{const m=new Set,x=_r.current,C=dl.current;if(!x||!C||x.width<=0||x.height<=0||xc.current!==C.layoutVersion)return m;for(const R of C.tiles){if(mt.current[R.deviceId])continue;const E=qa.current.get(R.deviceId);if(!E||R.width<=0||R.height<=0)continue;const X=Math.max(1,Math.round(R.width)),Q=Math.max(1,Math.round(R.height)),te=gL,oe=vL;(E.width!==te||E.height!==oe)&&(E.width=te,E.height=oe);const ie=E.getContext("2d",{alpha:!1});if(ie){ie.imageSmoothingEnabled=!0,ie.imageSmoothingQuality="high";try{ie.drawImage(x,Math.round(R.x),Math.round(R.y),X,Q,0,0,te,oe),m.add(R.deviceId)}catch{}}}return m},[]),Bm=d.useCallback((m,x)=>{const C=qa.current.get(m);if(x&&C&&C!==x&&Ys(m,C),x){if(qa.current.set(m,x),C&&C!==x&&va(C),mt.current[m]){Mn(m),ya(x),un(m);return}ci.current.get(m)&&Ot(m,x)&&Gn(m),window.requestAnimationFrame(()=>{Xi().has(m)&&Mn(m)}),window.requestAnimationFrame(()=>Qt(m,!0));return}qa.current.delete(m),Mn(m),va(C),un(m)},[un,Gn,Xi,Qt,Ot,Ys,ya,Mn,va]),af=d.useCallback((m,x)=>{qs.current=performance.now(),xc.current=Number(m.layoutVersion||0),Xi();const C=dl.current?.tiles||[],R=C.length>0?Math.round(m.byteLength/C.length):m.byteLength;for(const E of C){if(mt.current[E.deviceId])continue;const X={...m,deviceId:E.deviceId,width:E.width,height:E.height,sourceWidth:E.width,sourceHeight:E.height,byteLength:R};Ho(X,{...x,deviceId:E.deviceId,width:E.width,height:E.height,byteLength:R}),_i.current===E.deviceId&&Qt(E.deviceId,!0)}},[Ho,Xi,Qt]),_h=d.useCallback(m=>{const x=performance.now();jo.current<=0&&(jo.current=x),Ac.current=x;const C=_r.current;if(!C)return;const R=lo(m);wc.current!==R&&(wc.current=R,cn(C));const E=$i(C),X=Va(C),Q=()=>_r.current!==C||wc.current!==R||!xs(C,E),te=()=>Q()||!Gs(C,X),oe=dl.current?.tiles||[],ie=oe.length>0?Math.round(m.byteLength/oe.length):m.byteLength;for(const nt of oe)mt.current[nt.deviceId]||ss("wall",{...m,deviceId:nt.deviceId,width:nt.width,height:nt.height,sourceWidth:nt.width,sourceHeight:nt.height,byteLength:ie});_g(C,m,te,af,void 0,"smooth",Q).catch(()=>{})},[$i,Gs,xs,Va,af,ss,cn]),$u=d.useCallback(m=>{if(m.streamPurpose!=="wall"||mt.current[m.deviceId])return;const x=lo(m);$s.current.get(m.deviceId)!==x&&($s.current.set(m.deviceId,x),cn(gn.current.get(m.deviceId)))},[cn]),rf=d.useMemo(()=>({fps:wn.fps,maxWidth:wn.maxWidth,maxHeight:wn.maxHeight,quality:wn.quality,mode:Ht?"mode3-h264-hw":Ct.frameMode,frameMode:Ht?"mode3-h264-hw":Ct.frameMode,streamPurpose:"wall",configurationRefreshMs:sL,forceRestart:Zr>0,forceRestartToken:Zr>0?`document-presentation-resume-${Zr}`:"",restartReason:Zr>0?"document-presentation-resume":"",connectionSessionIds:Fo,monitorSelections:Kt,onFrame:Fm,onStreamReady:$u}),[Fo,Zr,Fm,$u,Ht,Kt,Ct.frameMode,wn.fps,wn.maxHeight,wn.maxWidth,wn.quality]),Uu=d.useCallback(m=>{const x=Rt.current;if(mt.current[m.deviceId]||!x||Jn(Wa.current,x)||x.deviceId!==m.deviceId||m.deviceId!==de||m.streamPurpose!=="control"||m.monitorIndex!==Ms)return;const C=St.find(E=>E.deviceId===m.deviceId);if(!C?.sessionId||C.sessionId!==m.sessionId)return;const R=At.current;(!R||lo(R)!==lo(m))&&cn(qn.current.get(m.deviceId)),Rt.current=Bg(x.deviceId,x.transitionGeneration,m),At.current=m,rt(m),me(E=>E==="connecting"?"active":E)},[St,de,cn,Ms]);d.useEffect(()=>{cn(qn.current.get(de)),At.current=null,rt(null)},[de,Ve,ua,cn,Ms]);const Ma=Ve?`${Ve}-monitor-${Ms}`:"",Xn=d.useMemo(()=>({fps:Br,maxWidth:Cs.maxWidth,maxHeight:Cs.maxHeight,quality:Kn.quality,mode:ua,frameMode:ua,streamPurpose:"control",forceRestart:Ma!=="",forceRestartToken:Ma,restartReason:Ma?"control-session-or-monitor-change":"",connectionSessionIds:Fo,monitorSelections:Kt,onFrame:Bn,onStreamReady:Uu}),[Fo,Ma,Kn.quality,Bn,Br,ua,Cs.maxHeight,Cs.maxWidth,Uu,Kt]),{frames:_c,state:vi,error:Oc,stats:yi,restartLive:is,reconnectLive:Fc}=ww(Pa,Ct.autoStartLive&&Pa.length>0,V,rf);d.useEffect(()=>{const m=new Set(Pa);for(const x of $s.current.keys())m.has(x)||($s.current.delete(x),cn(gn.current.get(x)))},[Pa,cn]);const{frame:Zi,layout:bi,state:qu,stats:Hm,refreshInputs:sf}=UT(ka,Ht&&Ct.autoStartLive&&ka.length>0,V,{fps:ta.atlasOutputFps,inputFps:Qs,width:1920,height:1080,tileWidth:Yi.maxWidth,tileHeight:Yi.maxHeight,captureDeviceIds:ka,connectionSessionIds:Fo,monitorSelections:Kt,onFrame:_h});d.useEffect(()=>{dl.current=bi,bi&&window.requestAnimationFrame(Xi)},[bi,Xi]),d.useEffect(()=>{if(!Ht||qu!=="open"){jo.current=0,Ac.current=0,qs.current=0;return}const m=window.setInterval(()=>{const x=_r.current,C=performance.now();if(!x||document.visibilityState!=="visible"||C-Fi.current<ev)return;const R=Ac.current,E=jo.current;if(R<=0||E<=0||C-R>500)return;const X=qs.current||E,Q=C-X;if(Q>=uL&&C-Eu.current>=fL){Ad(x)&&(Eu.current=C,Tc.current=C);return}Q>=cL&&C-Tc.current>=dL&&L1(x)&&(Tc.current=C)},250);return()=>window.clearInterval(m)},[qu,Ht]);const{frames:Rl,state:Wu,error:El,stats:of,restartLive:Bc,reconnectLive:Hc}=ww(gi,gi.length>0,V,Xn);d.useEffect(()=>{const m=Vr.current,x=new Set([...Object.keys(m),...Object.keys(Kt)]);for(const C of x){const R=Math.max(0,Math.floor(Number(m[C])||0)),E=Math.max(0,Math.floor(Number(Kt[C])||0));R!==E&&($s.current.delete(C),cn(gn.current.get(C)),cn(qn.current.get(C)),cn(qa.current.get(C)),_n("wall",C),_n("control",C),Ad(gn.current.get(C)||null),Ad(qn.current.get(C)||null))}x.size>0&&(cn(_r.current),Ad(_r.current)),Vr.current={...Kt}},[Kt,_n,cn]);const zo=d.useMemo(()=>{const m=(C,R)=>{const E=St.find(Q=>Q.deviceId===C),X=E?Ls(E,Kt[C]):0;return!Number.isFinite(Number(R.monitorIndex))||Number(R.monitorIndex)===X},x=new Map;for(const[C,R]of _c.entries())m(C,R)&&x.set(C,R);if(Ht&&Zi&&ka.length>0){const C=new Map((bi?.tiles||[]).map(E=>[E.deviceId,E])),R=Math.max(1,C.size);for(const E of ka){const X=C.get(E);X&&x.set(E,{...Zi,deviceId:E,width:X.width,height:X.height,sourceWidth:X.width,sourceHeight:X.height,byteLength:Math.round(Zi.byteLength/R)})}}for(const[C,R]of Rl.entries())m(C,R)&&x.set(C,R);for(const C of Ml){if(!zs.current.has(C)||x.has(C))continue;const R=Co.current.get(C);R&&m(C,R)&&x.set(C,R)}return x},[Zi,bi,St,Rl,ka,Ht,Kt,_c,Ml,yc]),Gu=ct&&gi.length>0?Wu:ka.length>0?qu:vi,zc=ct&&gi.length>0?of:ka.length>0?Hm:yi;d.useCallback((m,x="browser-stale")=>{const C=is(m,x),R=Bc(m,x);return C||R},[Bc,is]),d.useEffect(()=>{Ht&&ka.length>0&&!ct&&sf()},[ka.length,Ht,sf,ct]);const Ji=d.useCallback((m,x,C)=>{const R=x==="control"?qn.current.get(m)||null:gn.current.get(m)||null;if(!R)return!1;Ad(R);const E=performance.now();return Ro.current.set(ma(x,m),E),!0},[]),jl=d.useCallback(m=>{if(ua!=="mode3-h264-hw"||!de||Qe)return!1;const x=St.find(te=>te.deviceId===de)||Ca,C=u0(x?.platform);if(!C)return!1;const R=ma("control",de),E=performance.now();Hi.current.set(R,E),Oi.current.delete(R),la.current.delete(R),No.current.delete(R),Bi.current.delete(R),Ws.current.delete(R),Ad(qn.current.get(de)||null),Hc([de],"control-decode-fallback"),yt(C),Je(`control-${C}-fallback-${de}-${Date.now()}`),Se(!1),or(!1);const X=m==="no first frame"||m==="control-first-frame-timeout",Q=C==="mode1-jpeg"?"Mode 1 JPEG":"Mode 5";return qe(te=>te||(X?`Control frame transport timeout; retrying Control with ${Q} (${m})`:`H.264 decode failed; retrying Control with ${Q} (${m})`)),me("connecting"),!0},[St,Ca,de,Qe,ua,Hc]);d.useEffect(()=>{const m=ct?Ca:null;if(m){Ru.current={deviceId:m.deviceId,monitorIndex:Ms,frameMode:ua,startedAtEpochMs:Date.now()},or(de===m.deviceId&&Ge);return}Ru.current=null,or(!1)},[Ca?.sessionId,$e,de,Ge,ua,Ms,ct]);const lf=d.useCallback(async(m,x)=>{const C=String(x.streamId||"").trim(),R=String(x.streamPurpose||"").trim(),E=String(x.sessionId||"").trim(),X=String(x.commandId||"").trim(),Q=Number(x.captureGeneration||0),te=Number(x.monitorIndex??-1);if(!C||!["wall","atlas"].includes(R)||!E||!X||!Number.isSafeInteger(Q)||Q<=0||!Number.isSafeInteger(te)||te<0)throw new Error("wall-start-owner-incomplete");const oe=performance.now()+3e3;for(;;){const ie=await lt(`/api/remote/devices/${encodeURIComponent(m)}/live/stop`,{method:"POST",body:JSON.stringify({streamId:C,streamPurpose:R,expectedSessionId:E,expectedCommandId:X,expectedCaptureGeneration:Q,expectedMonitorIndex:te,requireNoPresentationOwner:!0,reason:"wall-start-presentation-revoked"})},V);if(ie?.ok===!1)throw new Error(ie.error||"revoked-wall-start-stop-failed");if(ie?.captureStopConfirmed===!0||ie?.alreadyStopped===!0||ie?.staleOwner===!0)return ie;if(ie?.presentationOwnerActive===!0||ie?.retainedForPresentation===!0){if(Ga.current&&ns.current)return ie;if(performance.now()<oe){await new Promise(nt=>window.setTimeout(nt,50));continue}throw new Error("revoked-wall-start-presentation-owner-did-not-release")}throw new Error("revoked-wall-start-stop-unconfirmed")}},[V]),eo=d.useCallback(async m=>{if(mt.current[m])throw new Error("LIVE_CAPTURE_PAUSED");if(!Ga.current||!ns.current)return{ok:!0,skipped:!0,reason:"wall-capture-owner-hidden"};const x=Xr.current,C=q.find(Q=>Q.deviceId===m);Wf({mode4Enabled:Ht,directMode4WallEnabled:rs,isMac:fo(C?.platform)});const R=C?Ls(C,Kt[m]):0,E={fps:wn.fps,maxWidth:wn.maxWidth,maxHeight:wn.maxHeight,quality:wn.quality,mode:Ht?"mode3-h264-hw":Ct.frameMode,frameMode:Ht?"mode3-h264-hw":Ct.frameMode,streamPurpose:"wall",monitorIndex:R},X=await lt(`/api/remote/devices/${encodeURIComponent(m)}/live/start`,{method:"POST",body:JSON.stringify(E)},V);if(X?.ok===!1)throw new Error(X.error||"wall-stream-start-failed");return x!==Xr.current||!Ga.current||!ns.current?(await lf(m,X),{...X,skipped:!0,reason:"wall-presentation-owner-revoked",compensated:!0}):X},[Qs,q,rs,V,Ht,Kt,lf,Ct.frameMode,Yi.maxHeight,Yi.maxWidth,wn.fps,wn.maxHeight,wn.maxWidth,wn.quality]),cf=d.useCallback(async m=>{const x=q.find(R=>R.deviceId===m);Wf({mode4Enabled:Ht,directMode4WallEnabled:rs,isMac:fo(x?.platform)});const C=await lt(`/api/remote/devices/${encodeURIComponent(m)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"wall",reason:"control-active"})},V);if(C?.ok===!1)throw new Error(C.error||"wall-stream-stop-failed");return C},[q,rs,V,Ht]),uf=d.useCallback(async(m,x="control-session-stop")=>{const C=await lt(`/api/remote/devices/${encodeURIComponent(m)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"control",reason:x})},V);if(C?.ok===!1)throw new Error(C.error||"control-stream-stop-failed");return C},[V]),Ar=d.useCallback((m,x={})=>{Wa.current?.deviceId===m&&(Wa.current=null);const C=qn.current.get(m);if(C){const E=ci.current.has(m)||gn.current.has(m)||qa.current.has(m);x.preservePresentation!==!1&&!E&&Ys(m,C),qn.current.delete(m),ya(C),!(ir.current.get(m)||gn.current.get(m)||qa.current.get(m))&&!So.current&&(So.current=C)}const R=ir.current.get(m);R&&Md(R),Co.current.delete(m),zs.current.delete(m),Pi.current.delete(m),ll.current.delete(m),ko.current.delete(m)},[Ys,ya]),$c=d.useCallback(m=>{const x=[ma("wall",m),ma("control",m)];for(const C of x){const R=di.current.get(C);R?.lastFrame&&(R.lastFrame=du(R.lastFrame))}kc(C=>{let R=!1;const E={...C};for(const X of x){const Q=C[X];!Q?.lastFrame||Q.lastFrame.payload.byteLength===0||(E[X]={...Q,lastFrame:du(Q.lastFrame)},R=!0)}return R?E:C})},[]),to=d.useCallback(m=>{$s.current.delete(m),Mn(m),Ar(m,{preservePresentation:!1});const x=new Set;for(const C of[ir.current.get(m),gn.current.get(m),qa.current.get(m)])C&&x.add(C);for(const C of x)ya(C);un(m),de===m&&(Ru.current=null,or(!1),Se(!1)),ha.current.add(m),$c(m)},[un,de,ya,Ar,$c,Mn]);d.useEffect(()=>{const m=new Set(Object.keys(gt));for(const x of m)ha.current.has(x)||to(x);for(const x of ha.current)m.has(x)||ha.current.delete(x)},[to,gt]);const $o=d.useCallback(m=>{const x=Lw(Ud.current,m);return Ud.current=x.tail,x.result},[]),dr=d.useCallback(m=>{const x=Lw(Gd.current,m);return Gd.current=x.tail,x.result},[]),fr=d.useCallback(m=>{Sr.current=m,Au.current=0;const x=m?.deviceId||"";_i.current=x,ku(x),x&&zs.current.add(x)},[]),Uo=d.useCallback(m=>$o(async()=>{if(mt.current[m.deviceId])return!1;const x=Sr.current;return!Jn(x,m)||!jp(m.deviceId,m,Rt.current)?!1:(await eo(m.deviceId),Jn(Sr.current,m)&&fr(null),!0)}),[fr,$o,eo]),Vu=d.useCallback((m,x,C)=>$o(async()=>{const R=Sr.current;if(Jn(R,m))return C.stoppedWallDeviceId=m.deviceId,!0;if(R)if(mt.current[R.deviceId])Jn(Sr.current,R)&&fr(null);else{if(!jp(R.deviceId,R,Rt.current))return!1;await eo(R.deviceId),Jn(Sr.current,R)&&fr(null)}if(!x())return!1;if(await cf(m.deviceId),C.stoppedWallDeviceId=m.deviceId,!x()){if(jp(C.stoppedWallDeviceId,m,Rt.current))try{await eo(C.stoppedWallDeviceId)}catch(E){throw fr(m),E}finally{C.stoppedWallDeviceId=""}return!1}return Md(gn.current.get(m.deviceId)||null),fr(m),!0}),[fr,$o,eo,cf]),Ku=d.useCallback(async(m,x)=>{if(x.stoppedWallDeviceId){if(Jn(Sr.current,m)){try{await Uo(m)}catch(C){Ce(C instanceof Error?C.message:String(C))}finally{x.stoppedWallDeviceId=""}return}await $o(async()=>{if(!x.stoppedWallDeviceId||!jp(x.stoppedWallDeviceId,m,Rt.current))return;const C=x.stoppedWallDeviceId;try{await eo(C)}catch(R){fr(m),Ce(R instanceof Error?R.message:String(R))}finally{x.stoppedWallDeviceId=""}})}},[fr,$o,Uo,Ce,eo]),zr=d.useCallback(async(m,x,C={})=>{const R=C.allowStopFailure===!0,E=C.resumeWall!==!1;try{await uf(m.deviceId,x)}catch(X){if(!R)throw X}if(!Jn(Rt.current,m))return!1;if(Rt.current=null,At.current=null,rt(null),Ar(m.deviceId),Se(!1),Je(""),yt(""),qe(""),Be(X=>X===m.deviceId?"":X),!E)return Jn(Sr.current,m)&&fr(null),!0;try{await Uo(m)}catch(X){Ce(X instanceof Error?X.message:String(X))}return!0},[fr,Ar,Uo,Ce,uf]),df=(Ia&&ct&&sn&&$e&&!ot.has($e)&&St.find(m=>m.deviceId===$e)||null)?.deviceId||"";d.useEffect(()=>{Ao.current=df},[df]),d.useEffect(()=>{const m=$e&&St.find(X=>X.deviceId===$e)||null;if(!Ia||!ct||!sn||!m){ga.current&&(++Wn.current,ga.current="");return}if(mt.current[m.deviceId]){ga.current&&(++Wn.current,ga.current=""),de===m.deviceId&&me("paused");return}if(Yr.current){if(Yr.current===m.deviceId)return;Yr.current=""}if(de===m.deviceId&&(ne==="active"||ne==="warm"||ne==="connecting")){me(X=>X==="warm"?"active":X);return}if(ga.current===m.deviceId)return;const x=++Wn.current,C=Bg(m.deviceId,x,{sessionId:m.sessionId,monitorIndex:Ms});ga.current=m.deviceId;const R={stoppedWallDeviceId:""},E=()=>x===Wn.current&&Ao.current===C.deviceId;dr(async()=>{if(!E())return;const X=Rt.current;if(X){me("stopping");try{await zr(X,"control-session-switch")}catch(oe){E()&&(me("error"),Ce(oe instanceof Error?oe.message:String(oe)));return}if(!E()){Rt.current||me("idle");return}}try{if(!await Vu(C,E,R)||!E()){await Ku(C,R),Rt.current||me("idle");return}}catch(oe){await Ku(C,R),E()&&(me("error"),Ce(oe instanceof Error?oe.message:String(oe)));return}if(!E()){await Ku(C,R);return}Rt.current=C,Wa.current=null,Yr.current="",To.current=null,hl.current=0,Mc.current="",R.stoppedWallDeviceId="";const Q=ma("control",C.deviceId),te=`control-session-${x}-${C.deviceId}`;Hi.current.set(Q,performance.now()),Oi.current.delete(Q),la.current.delete(Q),Ws.current.delete(Q),Bi.current.delete(Q),yt(""),qe(""),Je(te),Be(C.deviceId),Se(!1),me("connecting")}).catch(X=>{E()&&(me("error"),Ce(X instanceof Error?X.message:String(X)))}).finally(()=>{Wn.current===x&&ga.current===C.deviceId&&(ga.current="")})},[St,$e,de,ne,Ia,dr,sn,Vu,Ku,Ms,Ce,ct,zr,gt]),d.useEffect(()=>{if(!de||St.some(C=>C.deviceId===de))return;const m=de;++Wn.current,ga.current="";const x=Rt.current;me("stopping"),dr(async()=>{x&&x.deviceId===m?await zr(x,"control-device-disconnected",{allowStopFailure:!0}):(Ar(m),Be(C=>C===m?"":C)),Rt.current||me("idle")})},[St,de,dr,Ar,zr]),d.useEffect(()=>{if(Qr.current!==null&&(window.clearTimeout(Qr.current),Qr.current=null),!xa||ct||!de||mt.current[de]||ne!=="connecting"&&ne!=="active"&&ne!=="warm")return;const m=de,x=Rt.current;if(!x||x.deviceId!==m)return;const C=window.setTimeout(()=>{Qr.current===C&&(Qr.current=null);const R=Rt.current;if(Ao.current||mt.current[m]||!Jn(R,x))return;Wa.current=x;const E=++Wn.current;ga.current="",me("stopping"),dr(async()=>{if(E!==Wn.current||Ao.current||!Jn(Rt.current,x)){Jn(Wa.current,x)&&(Wa.current=null),Jn(Rt.current,x)&&Ao.current===m&&me("active");return}try{await zr(x,"control-session-wall-downshift")}catch(X){Jn(Wa.current,x)&&(Wa.current=null),E===Wn.current&&!Ao.current&&Jn(Rt.current,x)&&(me("active"),Ce(X instanceof Error?X.message:String(X)));return}Wa.current=null,E===Wn.current&&!Rt.current&&me("idle")})},pL);return Qr.current=C,()=>{Qr.current===C&&(window.clearTimeout(C),Qr.current=null)}},[de,ne,dr,Ce,ct,zr,gt,xa]);const Uc=d.useCallback(m=>{if(Wd.current===m)return;Wd.current=m;const x=Rt.current,C=x?.deviceId||de,R=++Wn.current;ga.current="",At.current=null,pl.current=!0,rt(null),Se(!1),or(!1),C&&(_n("control",C),Ar(C,{preservePresentation:!1}),me("stopping"),dr(async()=>{if(x&&x.deviceId===C)try{await zr(x,"control-session-document-hidden",{resumeWall:!1})}catch(E){!Ga.current&&Xr.current===m&&(me("error"),Ce(E instanceof Error?E.message:String(E)));return}else Ar(C,{preservePresentation:!1}),Be(E=>E===C?"":E);!Rt.current&&Wn.current===R&&me("idle")}))},[de,dr,Ar,_n,Ce,zr]);d.useEffect(()=>{if(lr.current!==null&&(window.clearTimeout(lr.current),lr.current=null),!de||ne==="idle"||ne==="paused"||ne==="error")return;if(!Ia){Uc(Xr.current);return}if(ne==="stopping"||qi){de&&bl&&ne==="connecting"&&(pl.current=!1),de&&bl&&pl.current&&(ne==="warm"||ne==="active")&&(pl.current=!1,At.current=null,rt(null),Se(!1),or(!1),_n("control",de),Je(`control-presentation-resume-${Date.now()}-${de}`),me("connecting"));return}At.current=null,pl.current=!0,rt(null),Se(!1),or(!1),me(x=>x==="idle"||x==="stopping"?x:"warm");const m=de;return Ar(m,{preservePresentation:!1}),lr.current=window.setTimeout(()=>{lr.current=null,++Wn.current,ga.current="";const x=Rt.current;me("stopping"),dr(async()=>{if(x&&x.deviceId===m)try{await zr(x,"control-session-warm-timeout")}catch(C){me("error"),Ce(C instanceof Error?C.message:String(C));return}else Ar(m),Be(C=>C===m?"":C);Rt.current||me("idle")})},mL),()=>{lr.current!==null&&(window.clearTimeout(lr.current),lr.current=null)}},[qi,bl,de,ne,Ia,dr,Ar,Uc,_n,Ce,zr]),d.useEffect(()=>()=>{lr.current!==null&&window.clearTimeout(lr.current),Qr.current!==null&&(window.clearTimeout(Qr.current),Qr.current=null),Wa.current=null},[]);const qc=d.useCallback(()=>{const m=new Set(Eo.current),x=Rt.current?.deviceId||"";de&&m.add(de),x&&m.add(x),Eo.current=[];for(const R of m){$s.current.delete(R),Mn(R),Ar(R,{preservePresentation:!1});for(const E of[gn.current.get(R),ir.current.get(R),qa.current.get(R)])E&&ya(E);un(R),_n("wall",R),_n("control",R),$c(R)}const C=_r.current;C&&ya(C),wc.current="",dl.current=null,xc.current=0},[un,de,ya,Ar,$c,Mn,_n]);d.useEffect(()=>{if(Ia){Eo.current=[...zu];return}qc()},[Ia,zu,qc]),d.useEffect(()=>{const m=Sr.current,x=Rt.current;if(!xa||!m||mt.current[m.deviceId]||x&&x.deviceId===m.deviceId){Au.current=0;return}const C=Au.current,R=Math.min(5e3,500*2**Math.min(C,4)),E=window.setTimeout(()=>{ul.current===E&&(ul.current=null);const X=Sr.current;!Yd.current||!X||mt.current[X.deviceId]||!Jn(X,m)||(Au.current=C+1,Uo(X).catch(Q=>{Ce(Q instanceof Error?Q.message:String(Q)),Jn(Sr.current,X)&&!Rt.current&&vc(te=>te+1)}))},R);return ul.current=E,()=>{window.clearTimeout(E),ul.current===E&&(ul.current=null)}},[ne,Uo,Ce,xa,ol,Kr]);const qo=de&&St.find(m=>m.deviceId===de)||null,Wc=!!(ct&&Oe&&ne==="active"&&Ge&&qo?.sessionId&&Me?.deviceId===qo.deviceId&&Me.sessionId===qo.sessionId&&Me.streamPurpose==="control"&&Me.commandId&&Me.captureGeneration>0&&Me.monitorIndex===Ms),{state:Qu,sendInput:Yu,stats:Ns,error:ff}=qT(Ia&&Mr&&Wc,V),mf=qo?.deviceId||"",Gc=qo?.sessionId||"",Xu=Me?.commandId||"",Zu=Number(Me?.captureGeneration||0),Ju=Number(Me?.monitorIndex||0),Dl=d.useCallback((m,x)=>!Ga.current||!Wc||!mf||!Gc||!Xu||Zu<=0||m!==mf?!1:Yu(m,{...x,monitorIndex:Ju,controlSessionId:Gc,controlCommandId:Xu,captureGeneration:Zu}),[Wc,Zu,Xu,mf,Ju,Gc,Yu]),Rs=Ia&&Ga.current&&Wc&&Qu==="open",pf={shiftKey:et.includes("ShiftLeft"),ctrlKey:et.includes("ControlLeft"),altKey:et.includes("AltLeft"),metaKey:et.includes("MetaLeft")},Es=d.useCallback(m=>wt.current.enqueueStop(m),[]),no=d.useCallback(m=>wt.current.enqueueStart(m),[]),ra=d.useCallback((m,x=Ut.current)=>(jt.current=m,Ut.current=m?String(x||""):"",ft.current+=1,ft.current),[]),$r=d.useCallback((m,x,C)=>MN({generation:m,currentGeneration:ft.current,enabled:jt.current,deviceId:x,currentDeviceId:Ut.current,documentVisible:Ga.current,presentationVisible:Wt.current,streamId:C,currentStreamId:at.current.get(x)||""}),[]),mr=d.useCallback(async(m,x,C)=>{if(!x)return{ok:!0,alreadyStopped:!0,captureStopConfirmed:!0,noExactOwner:!0};const E=await(Q=>lt(`/api/remote/devices/${encodeURIComponent(m)}/audio/stop`,{method:"POST",body:JSON.stringify({...Q?{streamId:Q}:{},reason:C})},V))(x),X=AN(E);if(X.staleOwner)return E;if(!X.confirmed)throw new Error(E?.error||"Remote audio capture stop was not confirmed.");return E},[V]),ed=d.useCallback(async(m,x)=>{const C=await lt(`/api/remote/devices/${encodeURIComponent(m)}/audio/stop`,{method:"POST",body:JSON.stringify({reason:x})},V);if(C?.ok===!1||C?.captureStopConfirmed!==!0&&C?.alreadyStopped!==!0)throw new Error(C?.error||"Remote audio stop-all was not confirmed.");return C},[V]),zm=d.useCallback(m=>{const x=ft.current,C=at.current.get(m)||"";return Es(()=>mr(m,C,"remote-audio-automatic-restart")).then(()=>no(async()=>{if(x!==ft.current||!jt.current||Ut.current!==m||!Ga.current||!Wt.current||!sn||!Qa||(Et.current||Pe?.deviceId||"")!==m)return"";const R=`audio-restart-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;if(at.current.set(m,R),!$r(x,m,R))return at.current.delete(m),"";const E=await lt(`/api/remote/devices/${encodeURIComponent(m)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:R,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},V);if(E?.ok===!1)throw at.current.get(m)===R&&at.current.delete(m),new Error(E.error||"Remote audio restart failed.");return $r(x,m,R)?R:(await mr(m,R,"remote-audio-stale-restart-compensation"),at.current.get(m)===R&&at.current.delete(m),"")}))},[no,Es,sn,V,$r,Qa,Pe?.deviceId,mr]),Il=Pe?.deviceId&&at.current.get(Pe.deviceId)||"",$m=d.useCallback(async(m,x,C)=>{ra(!1),De(!1),await Es(()=>mr(m,x,C)),at.current.get(m)===x&&at.current.delete(m)},[Es,ra,mr]),{state:Vc,lastFrame:td,stats:An,error:Kc}=VT(Pe?.deviceId||"",Ia&&Oo&&je,V,Zr,ln||nn||Tu.current,Il,zm,$m),Ll=d.useRef(new Map);d.useEffect(()=>{const m=[["hub",W],["registry",l],["license",ve],["wall-stream",Oc],["control-stream",El],["control-decode",O],["remote-input",ff],["remote-audio",Kc]];for(const[x,C]of m){const R=String(C||"").trim(),E=Rt.current;if(x==="wall-stream"&&R==="CONTROL_CAPTURE_OWNS_DEVICE"&&!!E&&_i.current===E.deviceId){Ll.current.delete(x);continue}if(x==="hub"&&$t?.requiresHubRestart&&$t.stage==="updating"){Ll.current.delete(x);continue}if(!R){Ll.current.delete(x);continue}Ll.current.get(x)!==R&&(Ll.current.set(x,R),Ce(R))}},[Kc,O,El,W,ff,ve,l,Ce,Oc,$t]);const Qc=Pe?.deviceId||"",ao=Pe?Ls(Pe,Kt[Qc]):0;d.useEffect(()=>{if(!Oe||!Mr||!Rs||!Qc)return;const m=iN(),x=Qc,C=ao,R=Ie=>{if(!Ie)return!1;const Nt=Dl(x,{...Ie,monitorIndex:C});return!Nt&&Ie.type!=="keyboard.reset"&&(m.reset("browser-input-send-rejected"),it([])),Nt},E=(Ie,Nt)=>{const Yt=Ie.target,tt=Yt?.tagName?.toLowerCase(),ut=Yt?.isContentEditable||tt==="input"||tt==="textarea"||tt==="select",pt=m.isPressed(Ie);if(ut&&(Nt==="keydown"||!pt))return;const It=m.event(Ie,Nt);It&&(Ie.preventDefault(),Ie.stopPropagation(),R(It))},X=Ie=>E(Ie,"keydown"),Q=Ie=>E(Ie,"keyup"),te=(Ie,Nt=!1)=>{const Yt=m.reset(Ie,Nt);Yt&&(R(Yt),it([]))};ye.current=Ie=>{const Nt=m.snapshot().latchedCodes.includes(Ie),Yt=m.modifier(Ie,!Nt);Yt&&(R(Yt),it(tt=>Nt?tt.filter(ut=>ut!==Ie):[...tt.filter(ut=>ut!==Ie),Ie]))};const oe=Ie=>{const Nt=Ep(Ie);if(!Nt)return!1;const Yt=m.snapshot(),tt={...Nt,shiftKey:Yt.shiftKey,ctrlKey:Yt.ctrlKey,altKey:Yt.altKey,metaKey:Yt.metaKey},ut=m.event(tt,"keydown");if(!ut||!R(ut))return!1;const pt=m.event(tt,"keyup");return!!pt&&R(pt)};Ne.current={sendKey:oe,sendText:Ie=>{let Nt=!1;const Yt=String(Ie??"").split(/(\r\n|\r|\n)/);for(const tt of Yt)if(tt){if(tt==="\r"||tt===`
189
- `||tt===`\r
190
- `){if(!oe("Enter"))return!1;Nt=!0;continue}for(const ut of rN(tt)){const pt=m.snapshot();if(!R({type:"text",text:ut,repeat:!1,pressedCodes:pt.pressedCodes,shiftKey:pt.shiftKey,ctrlKey:pt.ctrlKey,altKey:pt.altKey,metaKey:pt.metaKey}))return!1;Nt=!0}}return Nt}};const ie=()=>te("browser-window-blur"),nt=()=>te("browser-page-hidden"),Ye=()=>{document.visibilityState==="hidden"&&te("browser-document-hidden")};return window.addEventListener("keydown",X,!0),window.addEventListener("keyup",Q,!0),window.addEventListener("blur",ie),window.addEventListener("pagehide",nt),document.addEventListener("visibilitychange",Ye),()=>{window.removeEventListener("keydown",X,!0),window.removeEventListener("keyup",Q,!0),window.removeEventListener("blur",ie),window.removeEventListener("pagehide",nt),document.removeEventListener("visibilitychange",Ye),ye.current=null,Ne.current=null,te("control-keyboard-owner-changed",!0)}},[Mr,Rs,Qc,ao,Oe,Dl]);const hf=(m,x)=>{const C=Ep(m);if(!C)return!1;const R=performance.now(),E=ae.current;return E.key===C.key&&E.source!==x&&R-E.at<80?!0:(ae.current={key:C.key,source:x,at:R},Ne.current?.sendKey(C.key)??!1)},gf=d.useCallback(m=>{Wt.current=m;const x=Et.current||Pe?.deviceId||"";if(!je||!x)return;const C=ra(jt.current,x);if(!m){const E=at.current.get(x)||"";Es(async()=>{await mr(x,E,"remote-audio-document-hidden")}).catch(X=>{(Et.current||Pe?.deviceId||"")===x&&(ra(!1),at.current.delete(x),De(!1),Ce(X instanceof Error?X.message:String(X)))});return}const R=`audio-presentation-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;at.current.set(x,R),no(async()=>{if(!$r(C,x,R)||!sn||!Qa||(Et.current||Pe?.deviceId||"")!==x)return;const E=await lt(`/api/remote/devices/${encodeURIComponent(x)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:R,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},V);if(E?.ok===!1)throw new Error(E.error||"Remote audio presentation resume failed.");$r(C,x,R)||(await mr(x,R,"remote-audio-stale-presentation-compensation"),at.current.get(x)===R&&at.current.delete(x))}).catch(E=>{Ga.current&&C===ft.current&&(ra(!1),at.current.delete(x),De(!1),Ce(E instanceof Error?E.message:String(E)))})},[je,no,Es,ra,sn,V,$r,Qa,Pe?.deviceId,Ce,mr]);d.useEffect(()=>{const m=E=>{const X=Ga.current;E!==X&&(Ga.current=E,Xr.current+=1,hi.current={active:E&&ns.current,epoch:Xr.current},E||(qc(),Uc(Xr.current)),gf(E),Am(E),E&&!X&&(gl(Q=>Q+1),Fi.current=performance.now()))},x=()=>{m(document.visibilityState==="visible")},C=()=>m(!1),R=()=>x();return document.addEventListener("visibilitychange",x),window.addEventListener("pagehide",C),window.addEventListener("pageshow",R),()=>{document.removeEventListener("visibilitychange",x),window.removeEventListener("pagehide",C),window.removeEventListener("pageshow",R)}},[qc,Uc,gf]),d.useEffect(()=>{if(!de||ne!=="connecting"&&ne!=="active"&&ne!=="warm"||Wu!=="open")return;const m=de,x=ma("control",m),C=window.setInterval(()=>{const R=performance.now();if(document.visibilityState!=="visible"||R-Fi.current<ev)return;const E=Oi.current.get(x)||0,X=la.current.get(x)||0,Q=No.current.get(x)||0,te=Hi.current.get(x)||R;Hi.current.has(x)||Hi.current.set(x,te);const oe=E<=0,ie=oe?R-te>TL:R-E>Jx,nt=Bw({lastReceivedAt:E,lastPaintedAt:X,now:R,staleAfterMs:Jx}),Ye=Fw({paintStale:nt,lastRecoveryAt:Ro.current.get(x)||0,now:R,recoveryCooldownMs:t0,transportRecoveryAfterMs:n0});if(!ie&&Ye==="reset-decoder"&&Ji(m,"control","decoder-paint-stale")||!ie&&Ye==="wait")return;if(!(ie||Ye==="recover-transport")){nt&&Ji(m,"control","decoder-paint-stale"),oe&&R-te>AL&&!ws.current.has(x)&&Hc([m],"control-frame-socket-recovery")&&ws.current.set(x,R);return}const Nt=ws.current.get(x)||0;if(Nt<=0){Hc([m],"control-frame-socket-recovery")&&ws.current.set(x,R);return}if(R-Nt<e0)return;const Yt=Bi.current.get(x)||0;if(Yt>0){if(R-Yt<RL)return;Bi.current.delete(x)}const tt=Ws.current.get(x)||0,ut=St.find(en=>en.deviceId===m)||Ca,pt=u0(ut?.platform);if(!ie&&Ye==="recover-transport"&&pt==="mode1-jpeg"&&jl("mac-control-paint-timeout"))return;if(tt>=EL){if(jl(oe?"no first frame":"stale stream"))return;Se(!1),or(!1),Yr.current=m,me("error");return}if(R-Q<a0(NL,tt))return;Bc([m],oe?"control-first-frame-timeout":Ye==="recover-transport"?"control-paint-timeout":"control-receive-stale")&&(ws.current.delete(x),Ro.current.delete(x),No.current.set(x,R),Bi.current.set(x,R),Hi.current.set(x,R),Ws.current.set(x,tt+1))},650);return()=>window.clearInterval(C)},[St,Ca,Wu,de,ne,jl,Hc,Ji,Bc]),d.useEffect(()=>{!O||de&&mt.current[de]||ua!=="mode3-h264-hw"||jl(O)||(Se(!1),or(!1),Yr.current=Rt.current?.deviceId||"",me("error"))},[O,de,ua,jl]),d.useEffect(()=>{!ct||!de||mt.current[de]||!El||(Yr.current=de,me(m=>m==="error"?m:"error"))},[El,de,ct]),d.useEffect(()=>{if(ne!=="error")return;const m=Rt.current;if(!m)return;Yr.current=m.deviceId,Jn(To.current,m)||(To.current=m,hl.current=0);const x=hl.current,C=x===0?0:Math.min(5e3,500*2**Math.min(x-1,4)),R=window.setTimeout(()=>{Jn(Rt.current,m)&&(++Wn.current,ga.current="",me("stopping"),dr(async()=>{if(Jn(Rt.current,m))try{if(!await zr(m,"control-session-terminal-error"))return;To.current=null,hl.current=0,Mc.current===m.deviceId?(Mc.current="",Yr.current="",me("idle")):me("error")}catch(E){if(!Jn(Rt.current,m))return;hl.current+=1,Ce(E instanceof Error?E.message:String(E)),me("error"),Ii(X=>X+1)}}))},C);return()=>window.clearTimeout(R)},[ne,xo,dr,Ce,zr]);const Pl=d.useCallback(m=>{if(!m||Yr.current!==m)return!1;const x=Rt.current;return++Wn.current,ga.current="",hl.current=0,x&&x.deviceId===m?(Mc.current=m,To.current=null,me("error"),Ii(C=>C+1),!0):(Mc.current="",Yr.current="",To.current=null,me("idle"),!0)},[]);d.useEffect(()=>{if(vi!=="open"||!Ct.autoStartLive||Pa.length===0)return;const m=window.setInterval(()=>{const x=performance.now();if(document.visibilityState!=="visible"||x-Fi.current<ev)return;const C=1e3/Math.max(1,Za||br||1),R=Math.max(IL,Math.ceil(C*4)),E=[],X=[];for(const Q of Pa){if(X.length+E.length>=_L)break;const te=ma("wall",Q),oe=Oi.current.get(te)||0,ie=oe<=0,nt=zi.current.get(te)||x;zi.current.has(te)||zi.current.set(te,nt);const Ye=No.current.get(te)||0,Ie=la.current.get(te)||0,Nt=ie||x-oe>R,Yt=Bw({lastReceivedAt:oe,lastPaintedAt:Ie,now:x,staleAfterMs:R}),tt=Fw({paintStale:Yt,lastRecoveryAt:Ro.current.get(te)||0,now:x,recoveryCooldownMs:t0,transportRecoveryAfterMs:n0});if(!Nt&&tt==="reset-decoder"&&Ji(Q,"wall","decoder-paint-stale")||!Nt&&tt==="wait")continue;if(!(Nt||tt==="recover-transport")){Yt&&Ji(Q,"wall","decoder-paint-stale");continue}const pt=ws.current.get(te)||0;if(pt<=0&&(!ie||x-nt>jL)){E.push(Q);continue}if(ie&&x-nt<=DL||pt>0&&x-pt<e0)continue;const It=Ws.current.get(te)||0;x-Ye>=a0(LL,It)&&X.push(Q)}if(E.length>0&&Fc(E,"wall-frame-socket-recovery"))for(const Q of E)ws.current.set(ma("wall",Q),x);if(X.length>0&&is(X,X.some(Q=>(Oi.current.get(ma("wall",Q))||0)<=0)?"wall-first-frame-timeout":"wall-frame-stale"))for(const Q of X){const te=ma("wall",Q);ws.current.delete(te),Ro.current.delete(te),No.current.set(te,x),zi.current.set(te,x),Oi.current.delete(te),la.current.delete(te),Ws.current.set(te,(Ws.current.get(te)||0)+1)}},PL);return()=>window.clearInterval(m)},[Za,Pa,Fc,Ji,is,Ct.autoStartLive,br,vi]),d.useEffect(()=>{li(br),cr.current=Date.now(),Ka.current=0,ba.current=0,ca.current=0,es.current=0,jc.current=""},[br,Ct.frameMode,Ct.adaptiveLoadShedding]),d.useEffect(()=>{g1({h264DecodeAcceleration:Ct.h264DecodeAcceleration})},[Ct.h264DecodeAcceleration]),d.useEffect(()=>{if(!sn||ct||jn==="list"||!Ct.visibleOnlyLive){Pn([]);return}const m=Or.current;if(!m||typeof IntersectionObserver>"u"){Pn(kl);return}const x=Array.from(m.querySelectorAll("[data-live-device-id]"));if(x.length===0){Pn([]);return}const C=new Map,R=wN(m,N),E=()=>{const Q=av(x.map(te=>String(te.dataset.liveDeviceId||"")).filter(te=>(C.get(te)||0)>0));Pn(te=>nv(te,Q)?te:Q)},X=new IntersectionObserver(Q=>{for(const te of Q){const oe=String(te.target.dataset.liveDeviceId||"");oe&&C.set(oe,te.isIntersecting?te.intersectionRatio||.01:0)}E()},{root:R,rootMargin:N?mN:Mi.visibleRootMargin,threshold:[0,.01,.2,.6,1]});return x.forEach(Q=>X.observe(Q)),E(),()=>X.disconnect()},[kl,sn,N,ct,ks,Ct.visibleOnlyLive,jn]),d.useEffect(()=>{if(!Ct.adaptiveLoadShedding||!Ct.autoStartLive||Pa.length===0){ba.current=0,ca.current=0,es.current=0,jc.current="";return}const m=br;if(vi!=="open"||yi.sampleMs<500||yi.lastUpdatedAt<=0||es.current===yi.lastUpdatedAt)return;es.current=yi.lastUpdatedAt;const x=Date.now(),C=Pa.map(Ye=>({deviceId:Ye,receive:Cc[ma("wall",Ye)],paint:Sc[ma("wall",Ye)]}));if(!C.every(({receive:Ye,paint:Ie})=>{const Nt=Ye?.lastFrame,Yt=Math.max(0,Number(Nt?.requestedFps||0)),tt=Nt?lo(Nt):"";return PN({receiveSampleMs:Number(Ye?.sampleMs||0),paintSampleMs:Number(Ie?.sampleMs||0),currentGenerationVerified:Nt?.currentGenerationVerified===!0,frameRequestedFps:Yt,adaptiveFps:Qn})&&Ie?.bindingKey===tt})){ba.current=0,ca.current=0,Ka.current=0;return}const E=[Qn,...C.map(({deviceId:Ye,receive:Ie})=>`${Ye}:${lo(Ie.lastFrame)}`).sort()].join("|");if(jc.current!==E){jc.current=E,ba.current=x,ca.current=0,Ka.current=0;return}if(!ba.current){ba.current=x,ca.current=0;return}if(x-ba.current<Mi.downshiftStableSampleMs)return;const X=C.reduce((Ye,{receive:Ie})=>Ye+Math.max(0,Number(Ie?.framesPerSecond||0)),0),Q=C.reduce((Ye,{receive:Ie})=>Ye+Math.max(0,Number(Ie?.framesPerSecond||0))*Math.max(0,Number(Ie?.averageFrameBytes||0)),0),te=C.reduce((Ye,{paint:Ie})=>Ye+Math.max(0,Number(Ie?.framesPerSecond||0)),0),oe=Math.max(0,...C.map(({receive:Ye})=>Number(Ye?.maxIntervalMs||0))),ie=Math.max(0,...C.map(({paint:Ye})=>Number(Ye?.p95IntervalMs||0))),nt=LN({directDeviceCount:Pa.length,requestedFps:Qn,measuredFramesPerSecond:X,measuredPaintFramesPerSecond:te,measuredBytesPerSecond:Q,maxBytesPerSecond:Mi.maxWallBytesPerSecond,worstReceiveGapMs:oe,worstPaintP95Ms:ie,maxFrameGapMs:Mi.maxFrameGapMs});if(nt.overloaded){if(Ka.current=0,ca.current+=1,ca.current<Mi.downshiftConsecutiveSamples)return;const Ye=Mi.minFps;if(x-cr.current>=Mi.downshiftCooldownMs&&Qn>Ye){const Ie=Math.max(Ye,rP(Qn,Ye));Ie<Qn&&(li(Ie),cr.current=x,ba.current=0,ca.current=0)}return}if(ca.current=0,!nt.healthyForRecovery||Qn>=m){nt.healthyForRecovery||(Ka.current=0);return}if(!Ka.current){Ka.current=x;return}if(x-Ka.current>=Mi.recoveryCooldownMs){const Ye=Math.min(m,sP(Qn,m));Ye>Qn&&(li(Ye),cr.current=x,Ka.current=0,ba.current=0,ca.current=0)}},[Qn,Pa.length,Pa,Sc,Cc,vi,yi.lastUpdatedAt,yi.sampleMs,Ct.adaptiveLoadShedding,Ct.autoStartLive,Ct.frameMode,br]),d.useEffect(()=>{const m=new URLSearchParams(window.location.search).get("checkout");if(m==="success"){Ce("Checkout returned. Waiting for Dodo confirmation."),J();const x=window.setInterval(()=>{J()},4e3),C=window.setTimeout(()=>{window.clearInterval(x)},45e3);return()=>{window.clearInterval(x),window.clearTimeout(C)}}m==="cancelled"&&Ce("Checkout cancelled.")},[J]),d.useEffect(()=>{!sn&&Oe&&We(!1),!sn&&je&&(ra(!1),De(!1))},[je,Oe,ra,sn]),d.useEffect(()=>{je&&(!Pe||!Qa)&&(ra(!1),De(!1))},[je,ra,Qa,Pe]),d.useEffect(()=>{const m=Pe?.deviceId||"",x=Et.current;if(Et.current=m,!x||x===m)return;const C=ra(je,m),R=m?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:"";m&&je&&at.current.set(m,R);let E=!0;const X=at.current.get(x)||"";return(async()=>{try{await Es(async()=>{await mr(x,X,"remote-audio-device-switch"),at.current.delete(x)}),await no(async()=>{if(!E||!$r(C,m,R)||!m||!sn||!Qa)return;const Q=await lt(`/api/remote/devices/${encodeURIComponent(m)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:R,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},V);if(Q.ok===!1)throw new Error(Q.error||"Remote audio start failed.");$r(C,m,R)||(await mr(m,R,"remote-audio-stale-device-switch-compensation"),at.current.get(m)===R&&at.current.delete(m))})}catch(Q){E&&(ra(!1),at.current.delete(m),De(!1),Ce(Q instanceof Error?Q.message:String(Q)))}})(),()=>{E=!1}},[je,no,Es,ra,sn,V,$r,Qa,Pe?.deviceId,mr]),d.useEffect(()=>{const m=St.map(E=>E.deviceId),x=new Set(m),C=new Map(St.map(E=>[E.deviceId,E])),R=new Map;for(const E of St){const X=$L(E);if(!X)continue;const Q=Ti(E.status),te=[E.lastStatusAt,Q.capturedAt,Q.collectedAt,Q.timestamp,Q.updatedAt].find(ie=>typeof ie=="string"&&ie.trim()),oe=lN(Gr.current[E.deviceId],X,te);oe&&(Gr.current[E.deviceId]=oe,R.set(E.deviceId,oe),TS({platform:E.platform,topologyFingerprint:X,consecutiveTopologySamples:oe.consecutiveSamples})&&(wo.current[E.deviceId]=X))}for(const E of Object.keys(Gr.current))x.has(E)||delete Gr.current[E];ce(E=>{const X=E.filter(Q=>x.has(Q));return nv(E,X)?E:X}),Fe(E=>E&&x.has(E)?E:""),Ze(E=>E&&x.has(E)?E:""),$a(E=>{let X=!1;const Q={};for(const[te,oe]of Object.entries(E)){const ie=C.get(te);if(!ie){Q[te]=oe;continue}const nt=R.get(te)||Gr.current[te],Ye=cN({requestedIndex:oe,monitorCount:uo(ie),platform:ie.platform,topologyFingerprint:nt?.fingerprint||"",consecutiveTopologySamples:nt?.consecutiveSamples||0});Q[te]=Ye,Ye!==oe&&(X=!0)}return X?Q:E}),pi(E=>{const X=E.filter(Q=>x.has(Q));return nv(E,X)?E:X})},[St,Dc]),d.useEffect(()=>{Kd([]),Dm(!1)},[Qt]),d.useEffect(()=>{!rn||Cr!=="selected"||mi.length>0||Yn.length===0||pi(Yn.map(m=>m.deviceId))},[Yn,mi.length,Cr,rn]),d.useEffect(()=>{try{localStorage.setItem(AC,bs)}catch{}},[bs]),d.useEffect(()=>{KL(Ct)},[Ct]),d.useEffect(()=>{YL(Kn)},[Kn]),d.useEffect(()=>{GL(Kt,wo.current)},[St,Kt]);const Wo=d.useCallback(async()=>{const m=new Set(w);m.add(Vn);try{const X=await lt("/api/remote/status",void 0,Vn);Zb({endpoint:X.agentEndpoint,endpoint_candidates:[...X.agentEndpointCandidates||[],...X.hostTargetEndpointCandidates||[]]}).forEach(Q=>m.add(Q))}catch{}const x=[...m].sort((X,Q)=>{const te=oe=>{const ie=om(oe);return ie==="local"?0:ie==="loopback"?1:2};return te(X)-te(Q)||X.localeCompare(Q)});let C=!1,R="",E=!1;try{for(const X of x){const Q=om(X);try{if(await lt("/api/health",void 0,X),Q==="local")return $(!0),Ed(!0),X;Q==="loopback"&&(C=!0,R=X)}catch{Q==="local"&&(E=!0)}}return C?(E&&Ce("LiveDesk Hub is reachable on this PC, but not through the LAN address yet. Restart LiveDesk Hub to bind 5179 on the network."),$(!0),Ed(!0),R||Vn):($(!1),Ed(!1),"")}catch{return $(!1),Ed(!1),""}},[w]),Go=async()=>{if(vn("auth"),Lr(!1),window.liveDesk?.auth?.signInWithGoogle){const R=window.liveDesk.auth.signInWithGoogle();Wo();const E=await R;E?.ok===!1&&(Ce(E.error||"LiveDesk could not open the system browser for Google sign-in."),vn(""));return}const m=zt.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}/callback`}});Wo();const{data:x,error:C}=await m;C&&(Ce(C.message),vn(""))},vf=async()=>{vn("auth"),Lr(!1),window.liveDesk?.auth?.signOut||await lt("/api/auth/session",{method:"DELETE"},V||Vn).catch(()=>{}),await zt.auth.signOut(),(await window.liveDesk?.auth?.signOut?.())?.runtimeCleared===!1&&Ce("Signed out locally. The LiveDesk runtime could not be reached to clear its session."),vn("")};d.useEffect(()=>{if(!yo)return;const m=C=>{C.target instanceof Element&&(C.target.closest(".account-popover, .rail-account")||Lr(!1))},x=C=>{C.key==="Escape"&&Lr(!1)};return window.addEventListener("pointerdown",m),window.addEventListener("keydown",x),()=>{window.removeEventListener("pointerdown",m),window.removeEventListener("keydown",x)}},[yo]);const yf=d.useCallback(async(m={})=>{const x=m.silent===!0,C=m.takeover===!0,R=m.requestLocalAccess===!0;if(!n?.user){x||Ce("Sign in before publishing this host.","error");return}if(!kr.current){kr.current=!0,x||(vn("host"),Ln("Hub · 1/4 · Checking the local runtime…"));try{const X=(R?await Wo():"")||V||Vn;if(!(z||await lt("/api/remote/status",void 0,X)).started)throw new Error("Start LiveDesk on this computer before syncing the server.");x||Ln("Hub · 2/4 · Sending the signed-in session to the Hub…");const te=await lt("/api/auth/session",{method:"POST",body:JSON.stringify({accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:n.expires_at,user:{id:n.user.id,email:n.user.email}})},X);if(!te.ok||!te.authenticated)throw new Error(te.error||"hub-session-sync-failed");x||Ln("Hub · 3/4 · Claiming the Hub role and publishing its endpoint…");const oe=await lt("/api/hub/sync",{method:"POST",body:JSON.stringify({takeover:C})},X);if(!oe.ok)throw new Error(oe.error||"host-target-failed");if(!x){Ln("Hub · 4/4 · Verifying the endpoint and lease renewal…");const ie=await lt("/api/hub/status",void 0,X);if(!ie.hostTargetActive)throw new Error(ie.hostTargetLease?.lastError||"host-target-not-active-after-sync");const nt=ie.hostTargetEndpoint||ie.agentEndpoint||"endpoint ready",Ye=Number(ie.connectedDeviceCount||0),Ie=Ye>0?`${Ye} client${Ye===1?"":"s"} connected.`:"No clients connected yet; reconnect the laptop Client.";Ce(`Hub ready · ${nt} · lease auto-renewal active. ${Ie}`,"success"),(R||D)&&($(!0),Ed(!0)),Y()}u()}catch(E){if(!x){const X=E instanceof Error?E.message:String(E);X.includes("local network access")&&($(!1),Ed(!1)),Ce(`Hub setup failed · ${X}`,"error")}}finally{kr.current=!1,x||vn("")}}},[V,D,Y,u,Wo,n,Ce,Ln,z]),_l=d.useCallback((m=!0)=>{_t!=="host"&&(Lt(!1),m&&window.requestAnimationFrame(()=>on.current?.focus()))},[_t]),Fh=d.useCallback(()=>{_t!=="host"&&(on.current=document.activeElement instanceof HTMLElement?document.activeElement:null,Lr(!1),Lt(!0))},[_t]),bf=d.useCallback(()=>{Lt(!1),yf({takeover:!0,requestLocalAccess:!0})},[yf]);d.useEffect(()=>{if(!st)return;const m=window.requestAnimationFrame(()=>Sn.current?.focus()),x=R=>{R.target instanceof Element&&R.target.closest(".client-hub-switch-popover, .hub-sync-trigger")||_l(!1)},C=R=>{R.key==="Escape"&&_l()};return window.addEventListener("pointerdown",x),window.addEventListener("keydown",C),()=>{window.cancelAnimationFrame(m),window.removeEventListener("pointerdown",x),window.removeEventListener("keydown",C)}},[_l,st]);const Zn=d.useCallback(async()=>{if(!(!z?.update?.canApply||_t==="update")){vn("update");try{const m=await lt("/api/update/apply",{method:"POST",body:JSON.stringify({})},V||Vn);if(!m.ok)throw new Error(m.error||"LiveDesk update could not be started.");const x=[...new Set((m.targets||[]).map(E=>String(E.deviceId||"").trim()).filter(Boolean))],C=!!(m.managerUpdateAvailable||m.clientPackageUpdateAvailable),R=m.state==="hub-restart-requested"?Date.now():void 0;(x.length>0||C)&&Ua({operationId:String(m.operationId||`wall-update-${Date.now()}`),targetIds:x,stage:m.state==="clients-updated"?"updated":"updating",requiresHubRestart:C,initialHostInstanceId:String(z.hostInstanceId||""),targetManagerVersion:String(m.latestVersion||z.update?.latestVersion||""),targetClientVersion:String(m.latestClientVersion||z.update?.latestClientVersion||""),restartRequestedAt:R,restartDeadlineAt:R?R+qp:void 0}),Ln(m.state==="hub-restart-requested"?Up:qx),Y()}catch(m){Ce(m instanceof Error?m.message:String(m),"error")}finally{vn("")}}},[_t,V,Y,Ce,Ln,z]);d.useEffect(()=>{const m=$t,x=z?.update;if(!m||m.stage!=="updating"||!x)return;const C=x.restartResult?.operationId===m.operationId?x.restartResult:null;if(C?.outcome==="restored"){const oe=C.error||`The requested Hub ${C.targetVersion||m.targetManagerVersion||"version"} failed verification.`;Ua(ie=>ie?.operationId===m.operationId?{...ie,stage:"restored",error:oe}:ie),Ce(`LiveDesk update did not complete. Hub ${C.fallbackVersion||C.appVersion||"the previous version"} was restored. ${oe}`,"error");return}if(C?.outcome==="failed"){const oe=C.error||"No verified LiveDesk Hub replacement could be started.";Ua(ie=>ie?.operationId===m.operationId?{...ie,stage:"failed",error:oe}:ie),Ce(`LiveDesk Hub update failed. ${oe}`,"error");return}if(x.operationId===m.operationId&&x.state==="failed"){const oe=x.error||"LiveDesk update failed before the Hub replacement completed.";Ua(ie=>ie?.operationId===m.operationId?{...ie,stage:"failed",error:oe}:ie),Ce(oe,"error");return}if(x.operationId===m.operationId){if(x.state==="hub-restart-requested"&&!m.restartDeadlineAt){const oe=Date.now();Ua(ie=>ie?.operationId===m.operationId?{...ie,restartRequestedAt:oe,restartDeadlineAt:oe+qp}:ie),Ln(Up)}!m.requiresHubRestart&&x.state==="clients-updated"&&(Ua(oe=>oe?.operationId===m.operationId?{...oe,stage:"updated"}:oe),Ce("LiveDesk clients updated and reconnected successfully.","success"));return}if(!m.requiresHubRestart)return;const R=z.started===!0&&(!m.initialHostInstanceId||z.hostInstanceId&&z.hostInstanceId!==m.initialHostInstanceId),E=!!x.checkedAt,X=Vx(x.currentVersion,m.targetManagerVersion),Q=!m.targetClientVersion||Vx(x.currentClientVersion,m.targetClientVersion),te=E&&x.state==="idle"&&x.updateAvailable===!1&&X&&Q;R&&te&&(Ua(oe=>oe?.operationId===m.operationId?{...oe,stage:"updated"}:oe),Ce(`LiveDesk Hub ${x.currentVersion||C?.appVersion||m.targetManagerVersion} restarted and passed version verification.`,"success"))},[Ce,Ln,z,$t]),d.useEffect(()=>{const m=$t;if(!m||m.stage!=="updating"||!m.requiresHubRestart||m.restartDeadlineAt)return;const x=()=>{const R=Date.now();Ua(E=>E?.operationId===m.operationId&&E.stage==="updating"&&!E.restartDeadlineAt?{...E,restartRequestedAt:R,restartDeadlineAt:R+qp}:E),Ln(Up)};if(z?.update?.state==="hub-restart-requested"){x();return}if(!W)return;const C=window.setTimeout(x,yL);return()=>window.clearTimeout(C)},[W,Ln,z?.update?.state,$t]),d.useEffect(()=>{const m=$t;if(!m||m.stage!=="updating"||!m.requiresHubRestart||!m.restartDeadlineAt)return;const x=Math.max(0,m.restartDeadlineAt-Date.now()),C=m.operationId,R=window.setTimeout(()=>{const E=`LiveDesk Hub did not return and verify ${m.targetManagerVersion||"the requested version"} within ${Math.round(qp/6e4)} minutes. Check the Hub terminal or restart log, then run livedesk@latest manually if the Hub is still offline.`;Ua(X=>X?.operationId===C&&X.stage==="updating"?{...X,stage:"failed",error:E}:X),Ce(E,"error")},x);return()=>window.clearTimeout(R)},[Ce,$t]),d.useEffect(()=>{if(!$t||$t.stage!=="updated")return;const m=$t.operationId,x=window.setTimeout(()=>{Ua(C=>C?.operationId===m?null:C)},Wx);return()=>window.clearTimeout(x)},[$t]),d.useEffect(()=>{Di.current.clear(),ji({})},[$t?.operationId]),d.useEffect(()=>{if(!$t||z?.update?.operationId!==$t.operationId)return;const m=(z.update.targets||[]).filter(C=>C.state==="completed").map(C=>Gx($t.operationId,C)).filter(C=>!Di.current.has(C));if(m.length===0)return;const x=Date.now()+Wx;for(const C of m)Di.current.add(C);ji(C=>({...C,...Object.fromEntries(m.map(R=>[R,x]))}))},[z?.update,$t]),d.useEffect(()=>{const m=Math.min(...Object.values(Pr));if(!Number.isFinite(m))return;const x=window.setTimeout(()=>{const C=Date.now();ji(R=>Object.fromEntries(Object.entries(R).filter(([,E])=>E>C)))},Math.max(0,m-Date.now()));return()=>window.clearTimeout(x)},[Pr]),d.useEffect(()=>{if(xt!==qx&&xt!==Up)return;const m=z?.update;if(String(m?.state||"")==="failed"){Ce(m?.error||"LiveDesk update failed.","error");return}$t?.stage==="updated"&&Ce("")},[xt,Ce,z?.update?.error,z?.update?.state,$t?.stage]);const _a=d.useCallback(async()=>{if(!_t){vn("pin");try{const x=await lt("/api/remote/pairing-pin",{method:"POST"},V||Vn);if(!x.ok)throw new Error(x.error||"pin-rotation-failed");await Y(),Ce("New PIN published.")}catch(m){Ce(m instanceof Error?m.message:String(m))}finally{vn("")}}},[_t,V,Y]),nd=d.useCallback(m=>{m&&(Fe(m),ce(x=>x.includes(m)?x:[...x,m]))},[]),ad=d.useCallback(m=>{if(!m)return;const x=as.has(m);Fe(C=>x?C===m?"":C:m),ce(C=>x?C.filter(R=>R!==m):C.includes(m)?C:[...C,m])},[as]),Ol=d.useCallback(()=>{ce([]),Fe("")},[Ts]),wf=d.useCallback(()=>{ce(St.map(m=>m.deviceId)),Fe("")},[St]),Vo=d.useCallback((m,x)=>{const C=St.find(E=>E.deviceId===m);if(!C)return;const R=uo(C);if(!(R<=1)&&($a(E=>{const X=tm(E[m],R),Q=(X+x+R)%R;return Q===X?E:{...E,[m]:Q}}),_n("wall",m),_n("control",m),bc(E=>{if(!E.has(m))return E;const X=new Set(E);return X.delete(m),X}),Co.current.delete(m),zs.current.delete(m),ct)){const E=Pl(m);Se(!1),E||me("connecting"),or(!1),Ze(m)}},[St,_n,Pl,ct]);d.useEffect(()=>{const m=x=>{if(Oe&&Mr&&Rs)return;const C=x.target,R=C?.tagName?.toLowerCase();C?.isContentEditable||R==="input"||R==="textarea"||R==="select"||((x.ctrlKey||x.metaKey)&&x.key.toLowerCase()==="a"&&(x.preventDefault(),wf()),x.key==="Escape"&&Ol())};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[Mr,Ol,Rs,Oe,wf]);const Um=(m,x)=>{const C=St.find(Q=>Q.deviceId===m),R=C?uo(C):1,E=tm(Kt[m],R),X=tm(x,R);if(E!==X&&($a(Q=>({...Q,[m]:X})),bc(Q=>{if(!Q.has(m))return Q;const te=new Set(Q);return te.delete(m),te}),Co.current.delete(m),zs.current.delete(m),Pi.current.delete(m),ll.current.delete(m),ko.current.delete(m),_n("wall",m),_n("control",m)),ct){const Q=Pl(m);E!==X&&(Se(!1),Q||me("connecting")),or(!1),Ze(m)}else nd(m)},rd=m=>{const x=Et.current||Pe?.deviceId||"",C=[...new Set([x,m].filter(Boolean))],R=je||C.some(E=>at.current.has(E));ra(!1),De(!1);for(const E of C)at.current.delete(E);C.length!==0&&(async()=>{for(const E of C)await Es(()=>ed(E,"remote-audio-control-entry"))})().catch(E=>{R&&Ce("Remote audio was muted locally, but Client capture stop was not confirmed: "+(E instanceof Error?E.message:String(E)),"error")})},ro=async m=>{const x={requestId:++Mm.current,deviceId:m,startedAt:performance.now(),startedAtEpochMs:Date.now()};if(Us.current=x,!Ya.has(m)){Us.current?.requestId===x.requestId&&(Us.current=null),We(!1),Ce(As);return}const C=St.find(E=>E.deviceId===m);if(fo(C?.platform)&&(C?.capabilities?.controlPermission===!1||C?.capabilities?.accessibilityPermission===!1)){Us.current?.requestId===x.requestId&&(Us.current=null),We(!1),Ce("Mac remote control needs Accessibility permission. Allow it for the terminal app that starts LiveDesk, then restart the Mac client.","error");return}rd(m),Pl(m),or(!1),Ze(m),$n("control"),We(!0),Ce(`Opening remote control${C?` for ${er(C)}`:""}.`,"success")},qm=async()=>{if(!Pe){Ce("Select a Client before playing audio.");return}if(!sn){Ce(As);return}if(!Qa){Ce("Selected Client does not report remote audio support yet.");return}if(se)return;const m=!je,x=m?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:at.current.get(Pe.deviceId),C=ra(m,Pe.deviceId);m&&x?at.current.set(Pe.deviceId,x):m||at.current.delete(Pe.deviceId),ze("audio"),De(m);try{m?(await Es(()=>ed(Pe.deviceId,"remote-audio-user-enable-reconcile")),await no(async()=>{if(!x||!$r(C,Pe.deviceId,x))return;const R=await lt(`/api/remote/devices/${encodeURIComponent(Pe.deviceId)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:x,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},V);if(R?.ok===!1)throw new Error(R.error||"Remote audio start failed.");$r(C,Pe.deviceId,x)||await mr(Pe.deviceId,x,"remote-audio-stale-user-start-compensation")})):await Es(()=>ed(Pe.deviceId,"remote-audio-user-disabled")),Ce(`${m?"Audio started":"Audio stopped"} for ${er(Pe)}.`,"success")}catch(R){ra(!1),m&&at.current.delete(Pe.deviceId),De(!1),Ce(R instanceof Error?R.message:String(R),"error")}finally{ze("")}},sd=async(m,x)=>{const C=m.deviceId,R=er(m),E=String(mt.current[C]||""),X=!!E&&za[C]===!0;if(x&&E&&!X)return{ok:!0,skipped:!0,action:"pause",deviceId:C,title:R};if(!x&&!E)return{ok:!0,skipped:!0,action:"resume",deviceId:C,title:R};if(!x&&E.startsWith("pending:"))return{ok:!1,action:"resume",deviceId:C,title:R,error:"Pause is still pending confirmation."};if(x){const nt=E||`pending:${Date.now()}:${C}`,Ye=Rt.current?.deviceId===C?Rt.current:null,Ie=!!Ye||de===C,Nt=Ie?++Wn.current:0,Yt=()=>Iw({deviceId:C,requestTransitionGeneration:Nt,currentTransitionGeneration:Wn.current,actualControlOwner:Rt.current}),tt=hn.current.get(C);hn.current.set(C,{deviceId:C,monitorIndex:Ls(m,Kt[C]??tt?.monitorIndex),previousControlOwner:Ye||tt?.previousControlOwner||null}),Dr(C,!0),an(C,!1),Pt(C,nt),to(C),Ie&&(ga.current="",me("paused"));try{const ut=await lt(`/api/remote/devices/${encodeURIComponent(C)}/live/pause`,{method:"POST",body:JSON.stringify({reason:"user-video-pause"})},V);if(!ut?.pauseToken)return na.current.delete(C),Pt(C,""),an(C,!1),hn.current.delete(C),Yt()&&(At.current=null,rt(null),Se(!1),Je(`control-pause-rollback-${Date.now()}-${C}`),me("connecting")),{ok:!1,action:"pause",deviceId:C,title:R,error:ut?.error||"video-capture-pause-failed"};const pt=String(mt.current[C]||"");if(pt!==nt&&pt!==ut.pauseToken)return{ok:!1,action:"pause",deviceId:C,title:R,error:"Pause ownership changed before confirmation."};const It=Yt(),en=It&&Rt.current?.deviceId===C?Rt.current:Ye,Ba=hn.current.get(C);return Ba&&(Ba.previousControlOwner=en),It&&Rt.current?.deviceId===C&&(Rt.current=null),It&&(At.current=null,rt(null)),Pt(C,ut.pauseToken),It&&me("paused"),ut.ok===!1||ut.captureStopConfirmed!==!0?(an(C,!0),{ok:!1,unconfirmed:!0,action:"pause",deviceId:C,title:R,error:ut.stopError||ut.error||"Client capture shutdown was not confirmed."}):(an(C,!1),{ok:!0,action:"pause",deviceId:C,title:R})}catch(ut){return an(C,!0),{ok:!1,unconfirmed:!0,action:"pause",deviceId:C,title:R,error:ut instanceof Error?ut.message:String(ut)}}}const Q=hn.current.get(C),te=Q?.previousControlOwner||null,oe=de===C&&(te!==null||Sr.current?.deviceId===C||ne==="paused"),ie=oe?Wn.current:0;try{Dr(C,!1);const nt=await lt(`/api/remote/devices/${encodeURIComponent(C)}/live/resume`,{method:"POST",body:JSON.stringify({pauseToken:E})},V);if(nt?.ok===!1)throw new Error(nt.error||"video-capture-resume-failed");if(String(mt.current[C]||"")!==E)return{ok:!1,action:"resume",deviceId:C,title:R,error:"Resume ownership changed before confirmation."};const Ye=hn.current.get(C)||Q,Ie=Ye?.previousControlOwner||te,Nt=oe&&Iw({deviceId:C,requestTransitionGeneration:ie,currentTransitionGeneration:Wn.current,actualControlOwner:Rt.current});if(Pt(C,""),an(C,!1),hn.current.delete(C),Nt){const Yt=++Wn.current;ga.current="";const tt=Bg(C,Yt,{sessionId:m.sessionId||Ie?.sessionId,monitorIndex:Ls(m,Kt[C]??Ye?.monitorIndex)});Rt.current=tt,fr(tt),Yr.current="",To.current=null,At.current=null,rt(null),yt(""),qe(""),Se(!1),_n("control",C);const ut=`control-video-resume-${Yt}-${C}`;Je(ut),Be(C),me("connecting")}else _n("wall",C);return{ok:!0,action:"resume",deviceId:C,title:R}}catch(nt){return na.current.delete(C),{ok:!1,action:"resume",deviceId:C,title:R,error:nt instanceof Error?nt.message:String(nt)}}},id=async()=>{if(Ki.length===0){Ce("Select one or more Clients before pausing video.");return}if(ur.length===0){Ce(As);return}if(se)return;const m=ur.some(C=>{const R=String(mt.current[C.deviceId]||"");return!R||R.startsWith("pending:")||za[C.deviceId]===!0}),x=ur.filter(C=>{const R=String(mt.current[C.deviceId]||"");return m?!R||R.startsWith("pending:")||za[C.deviceId]===!0:!!R});if(x.length===0){Ce(m?"Selected Clients are already paused.":"Selected Clients are already playing.");return}ze("video");try{const C=await Promise.all(x.map(ie=>sd(ie,m)));Y();const R=C.filter(ie=>ie.ok&&!ie.skipped),E=C.filter(ie=>!ie.ok&&ie.unconfirmed),X=C.filter(ie=>!ie.ok&&!ie.unconfirmed),Q=ur.length-x.length+C.filter(ie=>ie.skipped).length,te=Ki.length-ur.length,oe=m?"pause":"resume";if(X.length>0||E.length>0){const ie=X.slice(0,2).map(nt=>`${nt.title}: ${nt.error||"unknown error"}`).join(" · ");Ce([`Video ${oe} completed for ${R.length}/${x.length} Clients.`,E.length>0?`${E.length} Client capture stop${E.length===1?"":"s"} remain unconfirmed.`:"",ie,te>0?`${te} selected Client${te===1?"":"s"} were outside the current plan limit.`:""].filter(Boolean).join(" "),"error");return}Ce([`Video ${m?"paused":"resumed"} for ${R.length} Client${R.length===1?"":"s"}.`,Q>0?`${Q} already ${m?"paused":"playing"}.`:"",te>0?`${te} outside the current plan limit.`:""].filter(Boolean).join(" "),"success")}finally{ze("")}},Wm=m=>{const x=m instanceof Error?m.message:String(m);return/remote-actions-disabled|remote-access-blocked-by-settings/i.test(x)?"Remote access is blocked. Change Settings > Remote Access > Access mode first.":/power-actions-disabled|allowPowerActions-blocked-by-settings/i.test(x)?"Power actions are off. Turn on Settings > Remote Access > Power actions first.":/agent-tool-capability-unavailable|unsupported-agent-operation/i.test(x)?"This Client needs a newer LiveDesk Client for power actions.":/device-not-connected|404 device-not-found/i.test(x)?"The Client disconnected before the action could be sent.":x},Yc=async m=>{if(!Pe||se)return;const x=Pe,R={sleep:"Sleep",restart:"Restart",shutdown:"Shut down"}[m];if(window.confirm(`${R} ${er(x)}? Unsaved work on that computer may be lost.`)){ze(m),Ce(`Sending ${R.toLowerCase()} request to ${er(x)}...`);try{const E=await lt(`/api/remote/devices/${encodeURIComponent(x.deviceId)}/quick-actions`,{method:"POST",body:JSON.stringify({action:m})},V);if(!E.ok)throw new Error(E.error||"The remote action could not be sent.");Ce(`${R} request sent to ${er(x)}.`,"success"),Y()}catch(E){Ce(Wm(E),"error")}finally{ze("")}}},xf=async(m,x,C="files")=>{const R=m.filter(te=>te.file.size>=0);if(R.length===0)return{files:0,bytes:0};if(!sn)throw new Error(As);if(x.length===0)throw new Error("Select at least one connected Client.");const E=crypto.randomUUID(),X=R.reduce((te,oe)=>te+oe.file.size,0);let Q=0;Ss({id:E,status:"reading",progress:1,message:`Preparing ${R.length} ${C}`});try{for(let te=0;te<R.length;te+=1){const oe=R[te],ie=oe.file,nt=Math.max(1,Math.ceil(ie.size/Jg));for(let Ye=0;Ye<nt;Ye+=1){const Ie=Ye*Jg,Nt=Math.min(ie.size,Ie+Jg),Yt=ie.size===0?new ArrayBuffer(0):await ie.slice(Ie,Nt).arrayBuffer(),tt=Ye===nt-1;Ss({id:E,status:"sending",progress:Math.max(2,Math.min(98,Math.round(Q/Math.max(1,X)*96))),message:`${te+1}/${R.length} ${oe.relativePath}`});const ut=await lt("/api/remote/files/chunk",{method:"POST",body:JSON.stringify({transferId:E,deviceIds:x,remoteDirectory:bs.trim(),name:ie.name,relativePath:oe.relativePath,size:ie.size,type:ie.type,lastModified:ie.lastModified,offset:Ie,totalBytes:ie.size,final:tt,dataBase64:iP(Yt)})},V);if(!ut.ok||ut.queued!==x.length)throw new Error(ut.error||`file-chunk-not-queued-${ut.queued}/${x.length}`);Q+=Yt.byteLength,await new Promise(pt=>window.setTimeout(pt,0))}}return Ss({id:E,status:"queued",progress:100,message:`Sent ${R.length} file${R.length===1?"":"s"} to ${x.length} Client${x.length===1?"":"s"}`}),window.setTimeout(()=>{Ss(te=>te?.id===E&&te.status==="queued"?null:te)},4500),{files:R.length,bytes:X}}catch(te){throw Ss({id:E,status:"failed",progress:100,message:te instanceof Error?te.message:String(te)}),te}},od=async m=>{const x=Yn.length>0?Yn.map(C=>C.deviceId):Pe?[Pe.deviceId]:[];try{await xf(i0(m),x)}catch(C){Ce(C instanceof Error?C.message:String(C))}},ld=async m=>{try{await xf(i0(m),Jd)}catch(x){Ce(x instanceof Error?x.message:String(x))}};d.useEffect(()=>{Ec.current=!1},[]);const Sf=m=>{m.preventDefault(),m.stopPropagation(),Vd(!1),od(m.dataTransfer.files)},cd=async(m="ltd")=>{if(!n){Ce("Sign in with Google before checkout.");return}if(L&&m===On){Ce("LiveDesk license is already active.");return}if(L&&On==="pro"){Ce("LiveDesk Pro is already active.");return}vn("checkout");try{const{data:x,error:C}=await zt.functions.invoke("dodo-checkout",{body:{plan:m}});if(C)throw C;if(!x?.checkout_url)throw new Error("Checkout function did not return a checkout URL.");window.location.assign(x.checkout_url)}catch(x){Ce(x instanceof Error?x.message:String(x)),vn("")}},Fl=OL(),Xc=FL(),Zc=zu.filter(m=>zo.has(m)).length,ud=Gu==="open"&&zc.sampleMs>0?`${zc.framesPerSecond.toFixed(1)} fps`:Gu,Ke=Pe?ct?Rl.get(Pe.deviceId):zo.get(Pe.deviceId):void 0,Jc=Pe?Ls(Pe,Kt[Pe.deviceId]):0,wi=Pe?zL(Pe):[],Cf=typeof Ke?.monitorIndex=="number"?tm(Ke.monitorIndex,Math.max(1,Ke.monitorCount||1)):Jc,dd=(Ke&&Cf===Jc?_C(Ke):null)||(Pe?PC(Pe,Jc):null);dd&&`${dd.width}${dd.height}`;const os=Pe?ma(ct?"control":"wall",Pe.deviceId):"",fa=os?Cc[os]:void 0,Tr=os?Sc[os]:void 0,kt=Tr?.lastInfo,eu=fa&&fa.sampleMs>0?`${fa.framesPerSecond.toFixed(1)} fps`:"waiting";fa&&`${fa.totalFrames}${eu}`,Tr&&Tr.sampleMs>0&&`${Tr.framesPerSecond.toFixed(1)}`,Tr&&Tr.sampleMs>0&&`${Tr.changedFramesPerSecond.toFixed(1)}`,kt&&(`${kt.frameSeq}${kt.decoderLabel}${kt.queueSize}${kt.renderQueueSize}${kt.droppedForLatency}${kt.decoderFlushCount}${kt.decoderTimestampFallbacks}${kt.decoderInputCount}${kt.decoderOutputCount}`,kt.visualChanged),kt&&`${Math.round(kt.queuedForMs)}${Math.round(kt.decodedForMs)}${Math.round(kt.scheduledForMs)}${kt.drawMs.toFixed(1)}`,kt?.targetPaintIntervalMs&&`${kt.targetPaintIntervalMs.toFixed(1)}${(1e3/kt.targetPaintIntervalMs).toFixed(1)}`,Tr&&`${Tr.decoderInputFps.toFixed(1)}${Tr.decoderOutputFps.toFixed(1)}`,kt?.canvasPresentation,kt&&`${kt.interactiveBufferWaitCount}${Math.round(kt.interactiveBufferWaitMs)}${kt.interactiveQueueDrainCount}`,fa&&(Ke?.frameMode==="mode5-lzo-delta"?`${nm(fa.averageFrameBytes)}${Ke.deltaVisualTileCount||0}${Ke.deltaRefreshTileCount||0}${Ke.deltaTotalTiles||0}`:`${nm(fa.averageFrameBytes)}${Math.round(fa.tinyFrameRatio*100)}${Math.round(fa.repeatedFrameRatio*100)}`),fa&&fa.sourceSendSampleCount>0&&`${fa.sourceSendAverageMs.toFixed(1)}${fa.sourceSendP95Ms.toFixed(1)}`,Yx(fa),Yx(Tr),fa&&Tr&&`${Xx(fa)}${Xx(Tr)}`,Ke?Ke.frameMode||Ke.mode||Ke.codec||Ke.mimeType:ct?Kn.frameMode:Ct.frameMode,ct?Kn.frameMode:Ct.frameMode,Ke?`${Ke.width}${Ke.height}${nm(Ke.byteLength)}`:ct?`${Cs.maxWidth}${Cs.maxHeight}`:`${Ct.maxWidth}${Ct.maxHeight}`,Ke&&`${Ke.isKeyFrame?"key":String(Ke.chunkType||"delta")}`,Ke&&Ke.monitorCount&&((Ke.monitorIndex??0)+1,`${Ke.monitorCount}`),Ke&&[`src ${Math.round(Ke.sourceGapMs||0)}ms`,`gap ${Math.round(Ke.agentSendGapMs||0)}ms`,`tx ${Math.round(Ke.agentSendDurationMs||0)}ms`,`pace ${Math.round(Ke.agentPaceMs||0)}ms`,`queue ${Math.round(Ke.agentQueueBeforePaceMs||0)}ms`,`age ${Math.round(Ke.agentFrameAgeMs||0)}ms`,Ke.hubPacketTransitAgeMs!==void 0?`sock ${Math.max(0,Math.round(Ke.hubPacketTransitAgeMs))}ms`:"",Ke.droppedByAgent?`drop ${Ke.droppedByAgent}`:"",Ke.hubIngressDropped?`ingress-drop ${Ke.hubIngressDropped}`:"",Ke.hubClientDropped?`ws-drop ${Ke.hubClientDropped}`:"",Ke.captureStageMs?`capture ${Math.round(Ke.captureStageMs)}ms`:"",Ke.requestedFps?`req ${Math.round(Ke.requestedFps)}fps`:"",Ke.effectiveFps?`eff ${Math.round(Ke.effectiveFps)}fps`:"",Ke.captureAverageMs?`avg ${Math.round(Ke.captureAverageMs)}ms`:"",Ke.captureP95Ms?`p95 ${Math.round(Ke.captureP95Ms)}ms`:"",Ke.slowFrameCount?`slow ${Math.round(Ke.slowFrameCount)}`:"",Ke.captureHelperRestarts?`helper ${Math.round(Ke.captureHelperRestarts)}`:"",Ke.convertMs?`rgb565 ${Math.round(Ke.convertMs)}ms`:"",Ke.compressMs?`lzo ${Math.round(Ke.compressMs)}ms`:"",Ke.captureSourceSerial?`cap #${Ke.captureSourceSerial}`:"",Ke.captureSourceSkipped?`cap skip ${Ke.captureSourceSkipped}`:"",Ke.frameMode==="mode5-lzo-delta"?`tiles ${Ke.deltaVisualTileCount||0}+${Ke.deltaRefreshTileCount||0}/${Ke.deltaTotalTiles||0}@${Ke.deltaTileSize||0}`:"",Ke.platformProfile||Ke.hardwareEncoder||"-",Ke.atlasComposeMs?`atlas ${Ke.atlasComposeMs.toFixed(1)}ms`:"",Ke.atlasPoolStarved?`pool ${Ke.atlasPoolStarved}`:"",Ke.atlasTileCount?`tiles ${Ke.atlasReadyTiles||0}/${Ke.atlasTileCount}`:"",Ke.atlasInputRevision?`input #${Ke.atlasInputRevision}`:"",Ke.atlasSourceMaxAgeMs!==void 0?`input-age ${Math.round(Ke.atlasSourceMaxAgeMs)}ms`:"",kt?.inputFeedbackMs!==void 0&&kt.inputFeedbackAt!==void 0&&performance.now()-kt.inputFeedbackAt<=Bx?`feedback ${Math.round(kt.inputFeedbackMs)}ms`:"",Ke.contentHash?`enc ${Ke.contentHash.slice(0,6)}`:"",kt?.visualHash?`pix ${kt.visualHash.slice(0,6)}`:""].filter(Boolean).join(" / "),Qu==="open"&&[`${Ns.sentPerSecond.toFixed(1)} hz`,Ns.lastInputSeq>0?`rtt ${Math.round(Ns.lastRoundTripMs)}ms`:"",Ns.lastInputSeq>0?`apply ${Ns.lastAgentApplyMs.toFixed(1)}ms`:"",Ns.droppedPerSecond>0?`drop ${Ns.droppedPerSecond.toFixed(1)}/s`:"",Ns.bufferedAmount>0?`buf ${nm(Ns.bufferedAmount)}`:"",Ns.lastInputType||"ready"].filter(Boolean).join(" / "),kt?.inputFeedbackMs!==void 0&&kt.inputFeedbackAt!==void 0&&performance.now()-kt.inputFeedbackAt<=Bx&&[kt.inputFeedbackExact?"exact":"estimated",kt.inputFeedbackInputType||"",`total ${Math.round(kt.inputFeedbackMs)}ms`,kt.inputFeedbackAgentApplyMs!==void 0?`apply ${kt.inputFeedbackAgentApplyMs.toFixed(1)}ms`:"",kt.inputFeedbackApplyToCaptureMs!==void 0?`apply→frame ${Math.round(kt.inputFeedbackApplyToCaptureMs)}ms`:"",kt.inputFeedbackInputToFrameMs!==void 0?`input→browser ${Math.round(kt.inputFeedbackInputToFrameMs)}ms`:"",kt.inputFeedbackFrameToPaintMs!==void 0?`browser→paint ${Math.round(kt.inputFeedbackFrameToPaintMs)}ms`:"",kt.inputFeedbackSampleCount?`p50 ${Math.round(kt.inputFeedbackP50Ms||0)}ms`:"",kt.inputFeedbackSampleCount?`p95 ${Math.round(kt.inputFeedbackP95Ms||0)}ms`:"",kt.inputFeedbackSampleCount?`n=${kt.inputFeedbackSampleCount}`:"",`input #${kt.inputFeedbackSeq||0}`].filter(Boolean).join(" / "),Ke&&`${Ke.frameSeq}${L0(Ke.receivedAt||Ke.capturedAt)}`;const dn=Math.max(0,zc.bytesPerSecond*8/1e6),Gm={activeTool:En,audioError:Kc,audioMode:je,audioState:Vc,audioStats:An,lastAudioFrame:td,selectedAudioCaptureStreamId:Il,controlFrames:Rl,controlInputReady:Rs,controlMode:Oe,controlPresentationReady:qd,controlSessionDeviceId:de,controlSessionFrameReady:Ge,controlSessionState:ne,controlStreamBinding:Me,devices:q,documentPresentationVisible:Ia,focusedDeviceId:Te,frames:zo,localFeatureAccess:sn,quickActionBusy:se,selectedDeviceId:Pe?.deviceId||"",selectedIds:Ae,showControlFocus:ct,videoCaptureStopUnconfirmedByDeviceId:za,videoCapturePausedDeviceIds:ot,wallPresentationReadyDeviceIds:$d},Vm=d.useRef(Gm);Vm.current=Gm,d.useEffect(()=>{if(!Tu.current)return;const m=window,x=te=>{if(!te)return null;const oe=te.sourceGapMs,ie=oe==null||oe===""?null:Number.isFinite(Number(oe))?Number(oe):null,nt=te;return{deviceId:te.deviceId,sessionId:te.sessionId||"",streamId:te.streamId||"",commandId:te.commandId||"",captureGeneration:Number(te.captureGeneration||0),monitorIndex:Number(te.monitorIndex||0),streamPurpose:te.streamPurpose||"",frameSeq:Number(te.frameSeq||0),frameMode:te.frameMode||"",mimeType:te.mimeType||"",currentGenerationVerified:nt.currentGenerationVerified===!0,receivedAt:nt.receivedAt||"",capturedAt:nt.capturedAt||"",sourceGapMs:ie,inputFeedbackEventId:String(te.inputFeedbackEventId||""),inputFeedbackInputSeq:Number(te.inputFeedbackInputSeq||0),inputFeedbackIssuedAtEpochMs:Number(te.inputFeedbackIssuedAtEpochMs||0),inputFeedbackAgentApplyMs:Number(te.inputFeedbackAgentApplyMs||0),inputFeedbackApplyToCaptureMs:Number(te.inputFeedbackApplyToCaptureMs||0)}},C=te=>{if(!te)return null;const oe=window.getComputedStyle(te),ie=te.getBoundingClientRect(),nt=Math.max(0,Math.min(ie.right,window.innerWidth)-Math.max(ie.left,0)),Ye=Math.max(0,Math.min(ie.bottom,window.innerHeight)-Math.max(ie.top,0)),Ie=Number(oe.opacity),Nt=te.isConnected&&oe.display!=="none"&&oe.visibility!=="hidden"&&oe.visibility!=="collapse"&&Number.isFinite(Ie)&&Ie>0&&ie.width>0&&ie.height>0&&nt>0&&Ye>0;return{connected:te.isConnected,userVisible:Nt,width:Math.max(0,Number(te.width||0)),height:Math.max(0,Number(te.height||0)),css:{display:oe.display,visibility:oe.visibility,opacity:Number.isFinite(Ie)?Ie:0},rect:{left:ie.left,top:ie.top,right:ie.right,bottom:ie.bottom,width:ie.width,height:ie.height,viewportIntersectionWidth:nt,viewportIntersectionHeight:Ye},codec:Tp(te)}},R=(te,oe)=>{const ie=ui.current.get(ma(te,oe));return ie?{bindingKey:ie.bindingKey||"",totalFrames:ie.totalFrames,totalChangedFrames:ie.totalChangedFrames,lastFrameSeq:Number(ie.lastFrameSeq||0),lastPaintAgeMs:ie.lastAt===void 0?-1:Math.max(0,performance.now()-ie.lastAt),lastInfo:ie.lastInfo?{frameSeq:Number(ie.lastInfo.frameSeq||0),decoderInputCount:Number(ie.lastInfo.decoderInputCount||0),decoderOutputCount:Number(ie.lastInfo.decoderOutputCount||0),targetPaintIntervalMs:Number(ie.lastInfo.targetPaintIntervalMs||0),droppedForLatency:Number(ie.lastInfo.droppedForLatency||0),visualChanged:ie.lastInfo.visualChanged===!0,inputFeedbackExact:ie.lastInfo.inputFeedbackExact===!0,inputFeedbackMs:Number(ie.lastInfo.inputFeedbackMs||0),inputFeedbackSampleCount:Number(ie.lastInfo.inputFeedbackSampleCount||0),inputFeedbackP50Ms:Number(ie.lastInfo.inputFeedbackP50Ms||0),inputFeedbackP95Ms:Number(ie.lastInfo.inputFeedbackP95Ms||0),inputFeedbackTargetMs:zx,inputFeedbackTargetMinSamples:$x,inputFeedbackOnTarget:ie.lastInfo.inputFeedbackExact===!0&&Number(ie.lastInfo.inputFeedbackSampleCount||0)>=$x&&Number(ie.lastInfo.inputFeedbackP95Ms)<zx}:null}:null},E=(te,oe)=>{if(!te)return null;if(oe==="wall-visible"){const nt=ui.current.get(ma("wall",te));return nt?{bindingKey:nt.bindingKey||"",total:nt.totalFrames,lastFrameSeq:Number(nt.lastFrameSeq||0),lastPaintAgeMs:nt.lastAt===void 0?-1:Math.max(0,performance.now()-nt.lastAt)}:null}if(oe!=="control-visible"&&oe!=="wall-reuse-visible")return null;const ie=fl.current.get(`${oe}:${te}`);return ie?{bindingKey:ie.bindingKey,total:ie.totalPaints,lastFrameSeq:ie.lastFrameSeq,lastPaintAgeMs:Math.max(0,performance.now()-ie.lastPaintAt)}:null},X=(te,oe)=>{const ie=E(te,oe);return ie?{bindingKey:ie.bindingKey,totalPaints:ie.total,lastPaintAgeMs:ie.lastPaintAgeMs,lastFrameSeq:ie.lastFrameSeq}:null},Q={readPresentationCounter(te,oe){return E(String(te||""),oe)},snapshot(te,oe={}){const ie=String(te||""),nt=oe.includeHistory===!0,Ye=Math.max(0,Number(oe.presentationAfterSequence||0)),Ie=Vm.current,Nt=Ie.devices.find(cs=>cs.deviceId===ie)?.liveCapturePause,Yt=String(mt.current[ie]||""),tt=gn.current.get(ie)||null,ut=qn.current.get(ie)||null,pt=ir.current.get(ie)||null,It=MT(),en=AT(),Ba={frameStats:fi.current===null?0:1,wallRecovery:ul.current===null?0:1,controlWarm:lr.current===null?0:1,controlWallDownshift:Qr.current===null?0:1},ei=Us.current?.deviceId===ie?Us.current:null,Yo=ml.current.get(ie)||null;return{capturedAt:Date.now(),deviceId:ie,activeTool:Ie.activeTool,documentPresentationVisible:Ie.documentPresentationVisible,showControlFocus:Ie.showControlFocus,selectedDeviceId:Ie.selectedDeviceId,focusedDeviceId:Ie.focusedDeviceId,selectedDeviceIds:[...Ie.selectedIds],localFeatureAccess:Ie.localFeatureAccess,quickActionBusy:Ie.quickActionBusy,audioMode:Ie.audioMode,audioState:Ie.audioState,audioError:Ie.audioError,audioCaptureStreamId:Ie.selectedAudioCaptureStreamId,audioFrame:Ie.lastAudioFrame?{deviceId:Ie.lastAudioFrame.deviceId,streamId:Ie.lastAudioFrame.streamId,frameSeq:Number(Ie.lastAudioFrame.frameSeq||0),mimeType:Ie.lastAudioFrame.mimeType,sampleRate:Number(Ie.lastAudioFrame.sampleRate||0),channels:Number(Ie.lastAudioFrame.channels||0),byteLength:Number(Ie.lastAudioFrame.byteLength||0)}:null,audioStats:{...Ie.audioStats},videoCapturePausePhase:Yt?Yt.startsWith("pending:")?"pending":"confirmed":"none",videoCaptureStopUnconfirmed:Ie.videoCaptureStopUnconfirmedByDeviceId[ie]===!0,authoritativeLiveCapturePause:Nt?{phase:Nt.phase||"",captureStopConfirmed:Nt.captureStopConfirmed===!0,stopAttemptCount:Math.max(0,Number(Nt.stopAttemptCount||0)),stopError:Nt.stopError||""}:null,controlMode:Ie.controlMode,controlSessionDeviceId:Ie.controlSessionDeviceId,controlSessionState:Ie.controlSessionState,controlSessionFrameReady:Ie.controlSessionFrameReady,controlPresentationReady:Ie.controlPresentationReady,controlInputReady:Ie.controlInputReady,controlConnection:Yo?{...Yo}:null,pendingControlConnection:ei?{...ei,elapsedMs:Math.max(0,performance.now()-ei.startedAt)}:null,videoCapturePaused:Ie.videoCapturePausedDeviceIds.has(ie),wallPresentationReady:Ie.wallPresentationReadyDeviceIds.has(ie),controlBinding:Ie.controlStreamBinding?.deviceId===ie?{...Ie.controlStreamBinding}:null,actualControlOwner:Rt.current?.deviceId===ie?{...Rt.current}:null,wallCapturePauseOwner:Sr.current?.deviceId===ie?{...Sr.current}:null,frameSubscriptions:It,audioSubscriptions:en,presentationTimers:{...Ba,total:Object.values(Ba).reduce((cs,js)=>cs+js,0)},wallFrame:x(Ie.frames.get(ie)),controlFrame:x(Co.current.get(ie)||Ie.controlFrames.get(ie)),wallPaint:R("wall",ie),controlPaint:R("control",ie),controlVisiblePaint:X(ie,"control-visible"),wallReuseVisiblePaint:X(ie,"wall-reuse-visible"),presentationPaintSequence:km.current,presentationPaintEvents:nt?Mo.current.filter(cs=>cs.deviceId===ie&&cs.sequence>Ye).sort((cs,js)=>cs.sequence-js.sequence).map(cs=>({...cs})):[],wallCanvas:C(tt),controlDecodeCanvas:C(ut),controlPresentationCanvas:C(pt),globalCodec:Tp(void 0,{includeLifecycleEvents:nt})}}};return m.__liveDeskTransmissionProbe=Q,()=>{m.__liveDeskTransmissionProbe===Q&&delete m.__liveDeskTransmissionProbe}},[]);const Ko=d.useCallback(()=>{Fs(!0),qr(Date.now()),Y(),Ir.current!==null&&window.clearTimeout(Ir.current),Ir.current=window.setTimeout(()=>{Ir.current=null,qr(Date.now()),Fs(!1)},650)},[Y]),Bl=d.useCallback(()=>{if(ln){Ei(!1);return}oi(!1),Ei(!0),Ko()},[Ko,ln]),xi=d.useCallback(()=>{if(nn){oi(!1);return}Ei(!1),oi(!0),Ko()},[nn,Ko]),kf=d.useCallback(()=>{if(wr){Os(!1);return}Os(!0),Ko()},[wr,Ko]),Mf=ln||nn,Hl=JSON.stringify(St.filter(m=>m.connected).map(m=>m.deviceId).sort());d.useEffect(()=>{if(!Mf)return;const m=JSON.parse(Hl);if(m.length===0){Fs(!1);return}const x=new AbortController,C=[];let R=!1;return Ir.current!==null&&(window.clearTimeout(Ir.current),Ir.current=null),Fs(!0),qr(Date.now()),Promise.allSettled(m.map(E=>lt(`/api/remote/devices/${encodeURIComponent(E)}/status-diagnostic`,{method:"POST",body:JSON.stringify({purpose:"remote-status-current-snapshot"}),signal:x.signal,timeoutMs:1500},V))).then(()=>{R||[500,1800,4500].forEach((E,X,Q)=>{const te=window.setTimeout(()=>{R||(Y(),qr(Date.now()),X===Q.length-1&&Fs(!1))},E);C.push(te)})}),()=>{R=!0,x.abort();for(const E of C)window.clearTimeout(E)}},[V,Y,Hl,Mf]);const pr=new Map,zl=new Map;if(ln||nn||wr)for(const m of St){const x=m.deviceId,C=ct&&de===x,E=ma(C?"control":"wall",x),X=C?Rl.get(x):zo.get(x),Q=C?qn.current.get(x)||ir.current.get(x)||null:gn.current.get(x)||(Ht?_r.current:null),te={device:m,frame:X,receiveStat:Cc[E],paintStat:Sc[E],codec:Q?Tp(Q):{},selectedMonitorIndex:Ls(m,Kt[x]),control:C,controlInputReady:C&&Rs,controlBinding:C&&Me?.deviceId===x?Me:void 0,hubRelay:z?.relay,capturePaused:ot.has(x),capturePauseConfirmed:m.liveCapturePause?.captureStopConfirmed===!0,capturePauseError:m.liveCapturePause?.stopError||"",clientHeartbeatMs:Number(z?.heartbeatMs||5e3),now:Date.now()},oe=["open","playing","silent"].includes(Vc),ie=An.nativeCallbackDiagnosticsAvailable&&(An.nativeRejectedCallbackCount>0||An.nativeCurrentnessDropCount>0),nt=oe&&!ie,Ye=x===Pe?.deviceId&&je?{id:"browser-remote-audio",state:nt?"ok":"warning",label:nt?"Remote audio is healthy":"Remote audio needs attention",detail:An.lastUpdatedAt>0?[Vc,`context ${An.audioContextState}`,`queue ${Math.round(An.queuedMs)}ms`,`packet ${Math.round(An.lastPacketAgeMs)}ms`,`capture ${An.captureHealthy?"healthy":An.captureAwaitingCurrentPcm?"awaiting PCM":"down"}`,An.backendKind?`backend ${An.backendKind}`:"backend unknown",An.helperRequired?`helper ${An.helperAlive&&An.helperPid>0?`pid ${An.helperPid}`:"missing"}`:"helper N/A",`drop ${An.drops}`,`restart ${An.automaticRestarts}`,An.nativeCallbackDiagnosticsAvailable?`native reject ${An.nativeRejectedCallbackCount}`:"native callback diagnostics unknown",An.nativeCallbackDiagnosticsAvailable?`native stale ${An.nativeCurrentnessDropCount}`:"",An.nativeLastDropReason?`native reason ${An.nativeLastDropReason}`:"",td?`frame #${td.frameSeq}`:"waiting for frame"].filter(Boolean).join(" · "):"Browser audio diagnostics are collecting while Remote or Debug status is open."}:null;if(ln||wr){const Ie=_I(te);ln&&Ye&&Ie.push(Ye),pr.set(x,Ie)}if(nn){const Ie=OI(te);Ye&&Ie.push(Ye),zl.set(x,Ie)}}const Af=wr?FI({status:z||{},deviceDiagnostics:[...pr.values()],codec:Tp(),browser:{hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:Number(navigator.deviceMemory||0)},frameStats:zc}):[],Tf=Zi?.atlasReadyTiles??Zc,tu=Zi?.atlasTileCount??Zc,Nf=Tf===tu?`${tu} tiles`:`${Tf}/${tu} tiles`,fd=ka.length>0;ct?`${ud}${dn.toFixed(dn>=10?0:1)}`:fd?`${Nf}${ud}${dn.toFixed(dn>=10?0:1)}`:`${Zc}${ud}${dn.toFixed(dn>=10?0:1)}`;const md=Yn.length,Zs=ct?Pe?er(Pe):"No Client":md===0?"No Client":md>1?`${md} selected`:Pe?er(Pe):"No Client",sa=ct?[Pe?.deviceId].filter(m=>!!m):Yn.map(m=>m.deviceId),Oa=Fd[Bs]||Fd.en,nu=Oa.sync||Fd.en.sync,Aa=r||le?"checking":L?On==="pro"?"Pro LTD active":`Plus LTD ${St.length}/${em}`:_m?`Free ${St.length}/${Jf}`:`Upgrade ${St.length}/${Jf}`,Km=L?On==="pro"?"Pro active":"Upgrade to Pro LTD":n?_t==="checkout"?"Opening checkout":On==="ltd"?"Buy Pro LTD":"Buy Plus LTD":_t==="auth"?"Opening Google":"Sign in to buy",Qm=On==="pro"||_t==="checkout"||_t==="auth"||r||le,Dn=n?.user?.user_metadata,Fa=o0(Dn,"avatar_url","picture"),Ur=o0(Dn,"full_name","name")||n?.user?.email||"Google",Rf=Ur.slice(0,1).toUpperCase(),Ym=z?.started?"Local app ready":"Start LiveDesk",Xm=s?.active?"Published":n?"Not published":"Sign in required",Bh=/^\d{6}$/.test(z?.pairingPin||"")?z?.pairingPin:"------",Js=m=>{if(typeof window<"u"&&(m==="support"?window.history.pushState({},"","/support"):En==="support"&&window.history.pushState({},"","/")),m==="control"){const x=Ca||Cl;if(x&&(Pl(x.deviceId),or(!1),Ze(x.deviceId)),$n(m),!sn){We(!1),Ce(As);return}We(!0);return}m==="wall"&&Li(x=>x+1),$n(m),We(!1)},Hn=_t==="update"||$t?.stage==="updating"||["dispatching","waiting-for-clients","hub-restart-requested"].includes(z?.update?.state||""),ls=!!(z?.update?.updateAvailable&&z.update.canApply||Hn||$t?.error||!z&&$t),so=TA(Bs),Ja=d.useCallback(m=>{if(!$t?.targetIds.includes(m))return;const x=z?.update?.operationId===$t.operationId?z.update.targets?.find(C=>C.deviceId===m):void 0;switch(x?.state){case"completed":return Pr[Gx($t.operationId,x)]?{state:"updated",label:"Updated"}:void 0;case"failed":return{state:"failed",label:"Update failed",error:x.error};case"pending-offline":return{state:"offline",label:"Waiting for reconnect"};case"queued":return $t.stage==="updating"?{state:"queued",label:"Queued"}:void 0;case"waiting":return $t.stage==="updating"?x.candidateSince?{state:"updating",label:"Verifying restart..."}:{state:"updating",label:"Restarting..."}:void 0;default:return $t.stage==="updated"?{state:"updated",label:"Updated"}:$t.stage==="updating"?{state:"updating",label:"Verifying..."}:void 0}},[z?.update,Pr,$t]),pd=N&&!!n&&K&&!z?.started,Si=r?"checking":z?.started?"online":pd?W?"retrying":"connecting":"offline",Qo=r?"Checking Hub":z?.started?`${St.length} online`:pd?W?"Hub offline":"Connecting Hub":n?"Hub offline":"Sign in required",Ci=z?.deviceName||(pd?W?"Retrying automatically…":"Trying saved Hub routes…":W?"Desktop Hub unavailable":"Remote management"),hd=N&&g&&!r&&!n;return o.jsxs("main",{className:`app-shell ${N?"mobile-console-shell":""} ${N&&ct?"mobile-console-control-active":""}`,"data-mobile-auth-required":hd?"true":void 0,"data-mobile-standalone":N&&j?"true":void 0,"data-mobile-ios":N&&k.isIos?"true":void 0,"data-mobile-android":N&&k.isAndroid?"true":void 0,children:[o.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk tools",children:[o.jsx("div",{className:"rail-brand",title:"LiveDesk",children:o.jsx(P0,{size:25})}),o.jsx("nav",{className:"rail-tools",children:mP.map(m=>{const x=m.icon,C=oh(m.tooltip,Bs);return o.jsxs("button",{className:`rail-tool ${m.id==="sync-server"?"sync-server hub-sync-trigger":""} ${En===m.id?"active":""} accent-${m.accent}`,onClick:()=>m.id==="sync-server"?Fh():Js(m.id),"data-tooltip":m.id==="sync-server"&&st?void 0:gv(m.label,m.tooltip,Bs),"aria-label":`${m.label}. ${C}`,type:"button",disabled:m.id==="sync-server"&&_t==="host","aria-busy":m.id==="sync-server"&&_t==="host","aria-expanded":m.id==="sync-server"?st:void 0,"aria-haspopup":m.id==="sync-server"?"dialog":void 0,"aria-controls":m.id==="sync-server"&&st?"hub-sync-popover":void 0,children:[m.id==="sync-server"&&_t==="host"?o.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):o.jsx(x,{size:19}),o.jsx("span",{children:m.id==="sync-server"&&_t==="host"?"Syncing…":m.label})]},m.id)})}),o.jsxs("div",{className:"rail-footer",children:[pP.map(m=>{const x=m.icon;return o.jsxs("button",{className:`rail-tool compact ${En===m.id?"active":""} accent-${m.accent}`,onClick:()=>Js(m.id),title:m.label,type:"button",children:[o.jsx(x,{size:18}),o.jsx("span",{children:m.label})]},m.id)}),o.jsxs("button",{className:`rail-tool compact local-settings ${Io?"active":""}`,onClick:()=>{$n("settings"),typeof window<"u"&&window.history.pushState({},"","/"),Lr(!1),We(!1),gc(!1)},title:"Settings",type:"button",children:[o.jsx(rh,{size:18}),o.jsx("span",{children:"Settings"})]}),o.jsxs("button",{className:`rail-account ${n?"signed-in":""}`,onClick:()=>{Lr(m=>!m)},disabled:r||_t==="auth","aria-expanded":yo,title:n?`Account: ${n.user?.email||Ur}`:"Sign in with Google",type:"button",children:[n?Fa?o.jsx("img",{src:Fa,alt:Ur,referrerPolicy:"no-referrer"}):o.jsx("span",{className:"avatar-fallback",children:Rf}):o.jsx(rc,{size:18}),o.jsx("span",{children:n?"Account":"Google"})]}),yo&&o.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[o.jsxs("div",{className:"account-popover-head",children:[o.jsx("div",{className:"account-popover-avatar",children:n&&Fa?o.jsx("img",{src:Fa,alt:Ur,referrerPolicy:"no-referrer"}):n?o.jsx("span",{children:Rf}):o.jsx(rc,{size:18})}),o.jsxs("div",{children:[o.jsx("strong",{children:n?Ur:"Account"}),o.jsx("p",{children:n?.user?.email||"Not signed in"})]})]}),o.jsxs("dl",{className:"account-popover-facts",children:[o.jsx("dt",{children:"User"}),o.jsx("dd",{children:n?.user?.email||"Not signed in"}),o.jsx("dt",{children:"Network"}),o.jsx("dd",{children:Ym}),o.jsx("dt",{children:"Access"}),o.jsx("dd",{children:Xm}),o.jsx("dt",{children:"Plan"}),o.jsx("dd",{children:Aa}),o.jsx("dt",{children:"Ads"}),o.jsx("dd",{children:On==="free"?"Standard banner":"Removed"})]}),n?o.jsxs("button",{className:"account-popover-action",onClick:vf,disabled:_t==="auth",type:"button",children:[o.jsx(m0,{size:16}),"Logout"]}):o.jsxs("button",{className:"account-popover-action primary",onClick:Go,disabled:_t==="auth",type:"button",children:[o.jsx(rc,{size:16}),"Sign in with Google"]})]})]})]}),N&&A&&o.jsx("div",{className:"mobile-pwa-guide-backdrop",role:"presentation",onClick:()=>T(!1),children:o.jsxs("section",{className:"mobile-pwa-guide",role:"dialog","aria-modal":"true","aria-labelledby":"mobile-pwa-guide-title",onClick:m=>m.stopPropagation(),children:[o.jsxs("header",{children:[o.jsx("span",{className:"mobile-pwa-guide-mark","aria-hidden":"true",children:o.jsx(C0,{size:20})}),o.jsxs("span",{children:[o.jsx("strong",{id:"mobile-pwa-guide-title",children:"Install LiveDesk on iPhone"}),o.jsx("small",{children:"Open without browser bars and tabs"})]}),o.jsx("button",{type:"button",onClick:()=>T(!1),"aria-label":"Close install guide",children:o.jsx(vr,{size:18,"aria-hidden":"true"})})]}),o.jsxs("ol",{children:[o.jsxs("li",{children:["Tap ",k.browserName==="browser"?"the browser":k.browserName,"'s ",o.jsx("strong",{children:"Share"})," button."]}),o.jsxs("li",{children:["Tap ",o.jsx("strong",{children:"Add to Home Screen"}),"."]}),o.jsx("li",{children:k.isSafari?o.jsxs(o.Fragment,{children:["Turn on ",o.jsx("strong",{children:"Open as Web App"}),", then tap ",o.jsx("strong",{children:"Add"}),"."]}):o.jsxs(o.Fragment,{children:["Confirm the app name, then tap ",o.jsx("strong",{children:"Add"}),"."]})})]}),o.jsx("button",{className:"mobile-pwa-guide-done",type:"button",onClick:()=>T(!1),children:"Got it"})]})}),hd&&o.jsxs("section",{className:"mobile-console-auth","aria-labelledby":"mobile-console-auth-title",children:[o.jsx("span",{className:"mobile-console-auth-mark","aria-hidden":"true",children:o.jsx(Ea,{size:26})}),o.jsx("h1",{id:"mobile-console-auth-title",children:r?"Checking your account":"Sign in to LiveDesk"}),o.jsx("p",{children:"Use the same Google account as your LiveDesk Hub."}),o.jsxs("button",{type:"button",onClick:()=>{Go()},disabled:r||_t==="auth","aria-busy":r||_t==="auth",children:[r||_t==="auth"?o.jsx(ps,{className:"spin",size:19,"aria-hidden":"true"}):o.jsx(rc,{size:19,"aria-hidden":"true"}),_t==="auth"?"Opening Google…":r?"Checking sign-in…":"Sign in with Google"]}),o.jsx("small",{children:"After sign-in, LiveDesk returns to this installed app."})]}),st&&o.jsxs("section",{id:"hub-sync-popover",className:"client-hub-switch-popover hub-sync-popover",role:"dialog","aria-modal":"false","aria-labelledby":"hub-sync-title","aria-describedby":"hub-sync-description hub-sync-notice",children:[o.jsxs("header",{className:"client-hub-switch-head",children:[o.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:o.jsx(mo,{size:19})}),o.jsx("span",{className:"client-hub-switch-eyebrow",children:so.eyebrow}),o.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>_l(),"aria-label":so.closeLabel,children:o.jsx(vr,{size:17})})]}),o.jsx("h2",{id:"hub-sync-title",children:so.title}),o.jsx("p",{id:"hub-sync-description",children:so.description}),o.jsxs("p",{id:"hub-sync-notice",className:"client-hub-switch-notice",children:[o.jsx(Ea,{size:16,"aria-hidden":"true"}),o.jsx("span",{children:so.restartNotice})]}),o.jsxs("div",{className:"client-hub-switch-actions",children:[o.jsx("button",{type:"button",onClick:()=>_l(),children:so.cancel}),o.jsxs("button",{ref:Sn,className:"primary",type:"button",onClick:bf,disabled:_t==="host",children:[o.jsx(mo,{size:16}),so.confirm]})]})]}),o.jsxs("section",{className:`desk-stage ${Fr&&!Wr?"dock-open":""} ${ct?"control-stage":""} ${Vt?"agents-stage":""} ${rn?"file-share-stage":""}`,children:[N&&o.jsxs("header",{className:"mobile-console-header",children:[o.jsxs("span",{className:"mobile-console-brand","aria-label":"LiveDesk mobile Console",children:[o.jsx("span",{className:"mobile-console-brand-mark",children:o.jsx(Ld,{size:18})}),o.jsxs("span",{children:[o.jsx("strong",{children:"LiveDesk"}),o.jsx("small",{children:"Mobile Console"})]})]}),o.jsxs("span",{className:`mobile-console-hub state-${Si}`,role:"status","aria-live":"polite",children:[o.jsx("i",{"aria-hidden":"true"}),o.jsxs("span",{children:[o.jsx("strong",{children:Qo}),o.jsx("small",{children:Ci})]})]}),o.jsxs("span",{className:"mobile-console-header-actions",children:[g&&!j&&(b||k.isIos)&&o.jsx("button",{className:"mobile-console-install",onClick:()=>{H()},"aria-label":"Install LiveDesk app",title:"Install LiveDesk app",type:"button",children:o.jsx(Vp,{size:19,"aria-hidden":"true"})}),ls&&o.jsx("button",{className:"mobile-console-update",onClick:()=>{Zn()},disabled:Hn||!z?.update?.canApply,"aria-label":Hn?"LiveDesk update in progress":"Update LiveDesk","aria-busy":Hn,type:"button",children:Hn?o.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):o.jsx(mm,{size:18,"aria-hidden":"true"})})]})]}),o.jsxs("header",{className:"topbar",children:[o.jsx("div",{className:"topbar-leading",children:ls?o.jsxs("button",{className:"topbar-update-button",onClick:()=>{Zn()},title:$t?.error?`LiveDesk Hub update failed: ${$t.error}`:`Update LiveDesk to ${z?.update?.latestVersion||$t?.targetManagerVersion||"latest"}`,"aria-label":$t?.error?`LiveDesk Hub update failed: ${$t.error}`:Hn?"LiveDesk update in progress":`Update LiveDesk to ${z?.update?.latestVersion||$t?.targetManagerVersion||"latest"}`,type:"button",disabled:Hn||!z?.update?.canApply,"aria-busy":Hn,children:[Hn?o.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):o.jsx(mm,{size:19,"aria-hidden":"true"}),Hn&&z?.update?.targetCount?o.jsxs("span",{className:"topbar-update-count","aria-hidden":"true",children:[z.update.completedCount||0,"/",z.update.targetCount]}):null]}):null}),o.jsxs("div",{className:"topbar-tray",children:[rn&&!ct&&o.jsxs("div",{className:"file-share-top-route","aria-label":"File distribution route",children:[o.jsxs("div",{children:[o.jsx(fu,{size:17}),o.jsxs("span",{children:[o.jsx("small",{children:"Source"}),o.jsx("strong",{children:"LiveDesk Hub"})]})]}),o.jsx(Uv,{size:15}),o.jsx(cM,{size:16}),o.jsxs("div",{children:[o.jsx("span",{className:"file-share-top-route-laptops",children:"▣ ▣ ▣"}),o.jsxs("span",{children:[o.jsx("small",{children:"Destination"}),o.jsxs("strong",{children:[Lm," Client",Lm===1?"":"s"]}),o.jsx("em",{children:bs.trim()||"Desktop/LiveDeskFiles"})]})]})]}),Fr&&!ct&&o.jsxs("div",{className:"top-actions",children:[o.jsx(Px,{active:wr,refreshing:wr&&xr,onClick:kf}),o.jsx(Ix,{active:ln,refreshing:ln&&xr,onClick:Bl}),o.jsx(Lx,{active:nn,refreshing:nn&&xr,onClick:xi}),o.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),o.jsx(Dx,{controller:Bo,onError:Ce}),o.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),o.jsx("div",{className:"segmented-control wall-cadence-control","aria-label":"Wall frame speed",children:dP.map(m=>o.jsx("button",{className:Da===m.id?"active":"",onClick:()=>{vs(m.id),li(m.fps),ZL(m.id)},title:m.label+" Wall streaming ("+m.fps+" fps)","aria-pressed":Da===m.id,type:"button",children:m.label},m.id))}),o.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),o.jsxs("div",{className:"wall-view-control",children:[o.jsx("div",{className:"segmented-control","aria-label":"Wall view",children:fP.map(m=>o.jsx("button",{className:jn===m.id?"active":"",onClick:()=>vo(m.id),"aria-pressed":jn===m.id,type:"button",children:m.label},m.id))}),o.jsx("label",{className:"wall-view-slider",htmlFor:"wall-view-scale",children:o.jsx("input",{id:"wall-view-scale",type:"range",min:mh,max:xu,step:1,value:Un,onChange:m=>ri(Number(m.currentTarget.value)),"aria-label":"Wall tile size","aria-valuetext":yr})})]})]}),ct&&o.jsxs("div",{className:"top-actions",children:[o.jsx(Px,{active:wr,refreshing:wr&&xr,onClick:kf}),o.jsx(Ix,{active:ln,refreshing:ln&&xr,onClick:Bl}),o.jsx(Lx,{active:nn,refreshing:nn&&xr,onClick:xi}),o.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),o.jsx(Dx,{controller:Bo,onError:Ce})]})]})]}),wr&&Fr&&o.jsx(AI,{items:Af,collectedAt:rl,onClose:()=>Os(!1)}),Qd?o.jsxs("section",{className:"doc-page",lang:Bs,dir:Bs==="ar"?"rtl":"ltr",children:[o.jsxs("section",{className:"doc-hero",children:[o.jsxs("div",{className:"doc-hero-copy",children:[o.jsxs("span",{className:"pricing-eyebrow",children:[o.jsx(ah,{size:16}),Oa.eyebrow]}),o.jsx("h2",{children:Oa.title}),o.jsx("p",{children:Oa.intro})]}),o.jsxs("label",{className:"doc-language-picker",children:[o.jsxs("span",{children:[o.jsx(uM,{size:17}),Oa.languageLabel]}),o.jsx("select",{value:Bs,onChange:m=>hc(m.target.value),children:gP.map(m=>o.jsx("option",{value:m.id,children:m.label},m.id))})]})]}),o.jsx("section",{className:"doc-grid",children:Oa.sections.map((m,x)=>{const R=[mo,Kp,Ob,Ea,bh][x]||ah;return o.jsxs("article",{className:"doc-card",children:[o.jsx("div",{className:"doc-card-icon",children:o.jsx(R,{size:19})}),o.jsxs("div",{children:[o.jsx("h3",{children:m.title}),o.jsx("p",{children:m.body}),o.jsx("ul",{children:m.points.map(E=>o.jsx("li",{children:E},E))})]})]},m.title)})}),nu&&o.jsxs("section",{className:"doc-sync",children:[o.jsxs("div",{className:"doc-sync-head",children:[o.jsx(Ob,{size:20}),o.jsxs("div",{children:[o.jsx("h3",{children:nu.title}),o.jsx("p",{children:nu.body})]})]}),o.jsx("ul",{children:nu.points.map(m=>o.jsx("li",{children:m},m))})]}),o.jsxs("section",{className:"doc-firewall",children:[o.jsxs("div",{className:"doc-firewall-head",children:[o.jsx(Ea,{size:20}),o.jsxs("div",{children:[o.jsx("h3",{children:Oa.firewall.title}),o.jsx("p",{children:Oa.firewall.body})]})]}),o.jsx("ul",{children:Oa.firewall.points.map(m=>o.jsx("li",{children:m},m))})]}),o.jsxs("section",{className:"doc-command-panel",children:[o.jsxs("div",{className:"doc-command-head",children:[o.jsx(Kp,{size:20}),o.jsxs("div",{children:[o.jsx("h3",{children:Oa.commands.title}),o.jsx("p",{children:Oa.commands.body})]})]}),o.jsxs("div",{className:"doc-command-list",children:[Oa.commands.manager&&o.jsxs("div",{className:"doc-command-row",children:[o.jsx("span",{children:Oa.commands.manager}),o.jsx("code",{children:Xc}),o.jsx("button",{className:"icon-button",onClick:()=>Yp(Xc),title:"Copy command",type:"button",children:o.jsx(wg,{size:16})})]}),o.jsxs("div",{className:"doc-command-row",children:[o.jsx("span",{children:Oa.commands.primary}),o.jsx("code",{children:Fl}),o.jsx("button",{className:"icon-button",onClick:()=>Yp(Fl),title:"Copy command",type:"button",children:o.jsx(wg,{size:16})})]}),o.jsxs("div",{className:"doc-command-row",children:[o.jsx("span",{children:Oa.commands.slot}),o.jsx("code",{children:`${Fl} 3`}),o.jsx("button",{className:"icon-button",onClick:()=>Yp(`${Fl} 3`),title:"Copy command",type:"button",children:o.jsx(wg,{size:16})})]})]})]})]}):Vt?o.jsx(Rx,{hubUrl:V,devices:q}):rn?o.jsx(AD,{hubUrl:V,devices:St,localFeatureAccess:sn,upgradeNotice:As,remoteDirectory:bs,onRemoteDirectoryChange:Hs,targetMode:Cr,selectedTargetIds:mi,onTargetModeChange:Rm,onTargetToggle:m=>pi(x=>x.includes(m)?x.filter(C=>C!==m):[...x,m]),filePickerRef:yl,folderPickerRef:Lu,onBrowserFileImport:m=>{ld(m)},onBrowserFolderImport:m=>{ld(m)},onNotice:Ce,onTransferChange:m=>{if(!m){Ss(null);return}const x=m.state==="failed"||m.state==="partially-failed"||m.state==="cancelled"?"failed":m.state==="completed"?"queued":m.state==="sending"?"sending":"reading";Ss({id:m.id,status:x,progress:m.progress,message:m.message}),["completed","partially-failed","failed","cancelled"].includes(m.state)&&window.setTimeout(()=>Ss(C=>C?.id===m.id?null:C),4500)}}):wa?o.jsx(T0,{session:n,currentProductKey:"livedesk",appVersion:"",onSignIn:Go}):Io?o.jsx(UN,{hubUrl:V,mobileLayout:N,runtimeRole:z?.runtimeRole||"hub",runtimeDeviceId:z?.deviceId||"",sessionAccessToken:n?.access_token||"",showThisComputerSetting:!N&&z?.runtimeRole==="hub",onShowThisComputerChange:ee,pin:o.jsxs(qN,{children:[o.jsx("div",{className:"settings-section-grid",children:o.jsxs("section",{className:"settings-section-card settings-pairing-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Pair a Client"}),o.jsx("h3",{children:"Connect another local PC"})]}),o.jsx(nr,{size:20})]}),o.jsxs("div",{className:"settings-pin-display",children:[o.jsx("span",{children:"Hub PIN"}),o.jsx("strong",{children:Bh}),o.jsxs("button",{className:"text-button ghost compact",onClick:_a,disabled:!z?.started||_t==="pin",type:"button",children:[o.jsx(el,{size:15}),_t==="pin"?"Creating":"New PIN"]})]})]})}),o.jsxs("section",{className:"settings-section-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"File transfer"}),o.jsx("h3",{children:"Client destination folder"})]}),o.jsx(Id,{size:20})]}),o.jsxs("label",{className:"settings-field",children:[o.jsx("span",{children:"Remote folder"}),o.jsx("input",{value:bs,onChange:m=>Hs(m.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),o.jsx("p",{className:"settings-help",children:"Blank uses Desktop/LiveDeskFiles on each Client."})]})]}),desktopUpdate:o.jsx(N0,{}),agent:o.jsx(GN,{hubUrl:V,showToast:Ce}),captureGallery:o.jsx(MI,{hubUrl:V,onToast:Ce})}):Pu?o.jsxs("section",{className:"pricing-page",children:[o.jsxs("header",{className:"pricing-header",children:[o.jsxs("div",{children:[o.jsxs("span",{className:"pricing-eyebrow",children:[o.jsx(fv,{size:15})," LiveDesk plans"]}),o.jsx("h2",{children:"Choose the plan that fits your wall"}),o.jsx("p",{children:"Start free with a local screen wall. Upgrade when you need ad-free monitoring, more Clients, or commercial controls."})]}),o.jsx("button",{className:"pricing-close",onClick:()=>Js("wall"),title:"Close pricing",type:"button",children:o.jsx(vr,{size:18})})]}),o.jsxs("div",{className:"pricing-status","aria-live":"polite",children:[o.jsx("span",{children:"Current plan"}),o.jsx("strong",{children:ef.name}),o.jsxs("small",{children:[St.length,"/",ML(Hu)," connected devices"]})]}),o.jsxs("div",{className:"pricing-cards","aria-label":"LiveDesk plans",children:[o.jsxs("article",{className:`pricing-plan-card ${On==="free"?"current":""}`,children:[o.jsxs("div",{className:"pricing-plan-topline",children:[o.jsx("span",{className:"pricing-plan-badge free",children:"Free"}),o.jsx("strong",{children:"$0"})]}),o.jsx("p",{className:"pricing-plan-audience",children:ou.free.audience}),o.jsx("h3",{children:"Monitor your local wall"}),o.jsx("p",{children:ou.free.note}),o.jsxs("ul",{children:[o.jsxs("li",{children:[o.jsx(tr,{size:16})," Up to ",Jf," devices"]}),o.jsxs("li",{children:[o.jsx(tr,{size:16})," Live view and local control"]}),o.jsxs("li",{children:[o.jsx(tr,{size:16})," Standard ad-supported banner"]})]}),o.jsx("span",{className:"pricing-current-label",children:On==="free"?"Current plan":"Included for everyone"})]}),o.jsxs("article",{className:`pricing-plan-card featured ${On==="ltd"?"current":""}`,children:[o.jsxs("div",{className:"pricing-plan-topline",children:[o.jsxs("span",{className:"pricing-plan-badge plus",children:[o.jsx(dM,{size:14})," Plus"]}),o.jsx("strong",{children:"$5"})]}),o.jsx("p",{className:"pricing-plan-audience",children:ou.ltd.audience}),o.jsx("h3",{children:"Ad-free monitoring"}),o.jsx("p",{children:"More room for personal computers without the standard banner."}),o.jsxs("ul",{children:[o.jsxs("li",{children:[o.jsx(tr,{size:16})," Up to ",em," devices"]}),o.jsxs("li",{children:[o.jsx(tr,{size:16})," No standard ad banner"]}),o.jsxs("li",{children:[o.jsx(tr,{size:16})," ",ou.ltd.ltd]})]}),o.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>cd("ltd"):Go,disabled:On!=="free"||_t==="checkout"||_t==="auth"||r||le,type:"button",children:[o.jsx(rm,{size:16}),On==="free"?n?"Choose Plus":"Sign in for Plus":"Plus active"]})]}),o.jsxs("article",{className:`pricing-plan-card pro ${On==="pro"?"current":""}`,children:[o.jsxs("div",{className:"pricing-plan-topline",children:[o.jsxs("span",{className:"pricing-plan-badge pro",children:[o.jsx(Ea,{size:14})," Pro"]}),o.jsx("strong",{children:"$15"})]}),o.jsx("p",{className:"pricing-plan-audience",children:ou.pro.audience}),o.jsx("h3",{children:"For serious operations"}),o.jsx("p",{children:"Commercial-ready monitoring for larger studios, offices, and teams."}),o.jsxs("ul",{children:[o.jsxs("li",{children:[o.jsx(tr,{size:16})," 30+ Client walls"]}),o.jsxs("li",{children:[o.jsx(tr,{size:16})," Commercial use included"]}),o.jsxs("li",{children:[o.jsx(tr,{size:16})," ",ou.pro.ltd]})]}),o.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>cd("pro"):Go,disabled:On==="pro"||_t==="checkout"||_t==="auth"||r||le,type:"button",children:[o.jsx(rm,{size:16}),On==="pro"?"Pro active":n?"Choose Pro":"Sign in for Pro"]})]})]}),o.jsxs("section",{className:"pricing-includes",children:[o.jsxs("div",{children:[o.jsx(nr,{size:17}),o.jsx("span",{children:"Screen wall"}),o.jsx("strong",{children:"120+ slots"})]}),o.jsxs("div",{children:[o.jsx(Yf,{size:17}),o.jsx("span",{children:"Focused control"}),o.jsx("strong",{children:"Local-first"})]}),o.jsxs("div",{children:[o.jsx(xg,{size:17}),o.jsx("span",{children:"Remote audio"}),o.jsx("strong",{children:"Available"})]}),o.jsxs("div",{children:[o.jsx(Id,{size:17}),o.jsx("span",{children:"File transfer"}),o.jsx("strong",{children:"Included"})]})]}),o.jsxs("p",{className:"pricing-note",children:[o.jsx(tr,{size:15})," Commercial use requires Pro. Plus LTD is for personal, creator, and homelab use."]}),o.jsxs("button",{className:"pricing-primary-cta",onClick:n?()=>cd(On==="ltd"?"pro":"ltd"):Go,disabled:Qm,type:"button",children:[o.jsx(rm,{size:18}),Km]})]}):o.jsx(o.Fragment,{children:o.jsxs("section",{className:`monitor-layout ${Wr?"dock-collapsed":""}`,children:[o.jsxs("section",{ref:Or,className:`screen-wall-panel ${vl?"drop-active":""}`,onClick:m=>{m.currentTarget===m.target&&Ol()},onDragEnter:m=>{m.preventDefault(),Vd(!0)},onDragOver:m=>{m.preventDefault(),m.dataTransfer.dropEffect="copy"},onDragLeave:m=>{m.currentTarget===m.target&&Vd(!1)},onDrop:Sf,children:[ka.length>0&&o.jsx("canvas",{ref:nf,className:"atlas-source-canvas",width:bi?.width||1920,height:bi?.height||1080,"aria-hidden":"true"}),N&&Fr&&!ct&&o.jsxs("section",{className:"mobile-console-selection","aria-label":"Selected computer actions",children:[o.jsxs("div",{className:"mobile-console-selection-copy",children:[o.jsx("span",{children:"Selected computer"}),o.jsx("strong",{children:Zs}),o.jsx("small",{children:Pe?`${Pe.platform||"Client"} · ${uo(Pe)} display${uo(Pe)===1?"":"s"}`:"Tap a computer below, then choose an action."})]}),o.jsxs("div",{className:"mobile-console-actions",role:"toolbar","aria-label":"Selected computer quick actions",children:[o.jsxs("button",{onClick:()=>Pe&&void ro(Pe.deviceId),disabled:!Mr||!!se,type:"button",children:[o.jsx(Yf,{size:17}),o.jsx("span",{children:"Control"})]}),o.jsxs("button",{className:je?"active":"",onClick:()=>{qm()},disabled:!Oo||!!se,"aria-pressed":je,type:"button",children:[se==="audio"?o.jsx(ps,{className:"spin",size:17}):o.jsx(xg,{size:17}),o.jsx("span",{children:"Audio"})]}),o.jsxs("button",{className:Xa?"":"active",onClick:()=>{id()},disabled:ur.length===0||!!se,"aria-pressed":!Xa,type:"button",children:[se==="video"?o.jsx(ps,{className:"spin",size:17}):Xa?o.jsx(Fb,{size:17}):o.jsx(Bb,{size:17}),o.jsx("span",{children:Xa?"Pause":"Resume"})]}),o.jsxs("button",{onClick:()=>{Yc("restart")},disabled:!Pe||!sn||!!se||!Vs,type:"button",children:[se==="restart"?o.jsx(ps,{className:"spin",size:17}):o.jsx(dv,{size:17}),o.jsx("span",{children:"Restart"})]})]})]}),ct?o.jsx("section",{className:"control-focus",children:o.jsxs("div",{className:"control-wall",children:[Pe&&o.jsxs("div",{className:"control-monitor-tabs","aria-label":`Select monitor for ${er(Pe)}`,children:[o.jsx("strong",{className:"control-computer-name",title:er(Pe),children:er(Pe)}),wi.map(m=>o.jsxs("button",{className:m.index===Jc?"active":"",onClick:()=>Um(Pe.deviceId,m.index),title:UL(m),type:"button",children:[o.jsx("span",{children:m.name||`Display ${m.index+1}`}),m.width>0&&m.height>0&&o.jsxs("small",{children:[m.width,"x",m.height]})]},m.index))]}),Pe&&Rs&&o.jsxs("div",{className:"control-modifier-bar","aria-label":"Hold remote modifier keys",children:[N&&o.jsxs(o.Fragment,{children:[o.jsx("button",{className:`remote-keyboard-button ${fe?"active":""}`,type:"button","aria-pressed":fe,"aria-label":"Open remote keyboard",title:"Open the phone keyboard for the remote computer",onClick:()=>{const m=He.current;m&&(m.focus({preventScroll:!0}),m.setSelectionRange(m.value.length,m.value.length))},children:o.jsx(fM,{size:15,"aria-hidden":"true"})}),o.jsx("textarea",{ref:He,className:"remote-keyboard-input","aria-label":"Type on the remote computer",autoComplete:"off",autoCorrect:"off",autoCapitalize:"sentences",enterKeyHint:"enter",spellCheck:!1,rows:1,onFocus:()=>Ee(!0),onBlur:()=>{pe.current=!1,Ee(!1)},onCompositionStart:()=>{pe.current=!0},onCompositionEnd:m=>{pe.current=!1;const x=m.currentTarget.value;m.currentTarget.value="",Ne.current?.sendText(x)},onInput:m=>{if(pe.current)return;const x=m.currentTarget.value;m.currentTarget.value="",Ne.current?.sendText(x)},onKeyDown:m=>{m.nativeEvent.isComposing||!Ep(m.key)||(m.preventDefault(),m.stopPropagation(),hf(m.key,"keydown"))},onBeforeInput:m=>{const x=m.nativeEvent.inputType||"";Ep(x)&&(m.preventDefault(),m.stopPropagation(),hf(x,"beforeinput"))}})]}),oL.map(m=>{const x=m.code==="MetaLeft"&&fo(Pe.platform)?"Cmd":m.label,C=et.includes(m.code);return o.jsx("button",{className:C?"active":"",type:"button","aria-pressed":C,title:`Hold ${x} on the remote computer`,onClick:()=>ye.current?.(m.code),children:x},m.code)})]}),Pe?o.jsx(ov,{device:Pe,frame:Ke,selected:!1,controlEnabled:Mr&&Oe&&Rs,showStatus:Kn.showScreenStatus,showDeviceTitle:!1,monitorIndex:Ls(Pe,Kt[Pe.deviceId]),monitorCount:uo(Pe),onSelect:()=>{},onFocusDevice:()=>Ze(Pe.deviceId),onOpenControl:()=>ro(Pe.deviceId),onCycleMonitor:m=>Vo(Pe.deviceId,m),onCanvasReady:Tl,sendInput:Dl,remoteModifierState:pf,presentationReady:qd,remoteDiagnostics:nn?zl.get(Pe.deviceId):ln?pr.get(Pe.deviceId):void 0,diagnosticsMode:nn?"debug":"remote"},Pe.deviceId):o.jsxs("div",{className:"control-empty",children:[o.jsx(nr,{size:30}),o.jsx("strong",{children:"No Client"}),o.jsx("span",{children:"Open a Client from the Wall."})]}),Pe&&Bu&&o.jsxs("div",{className:"control-connection-overlay",role:"alert",children:[o.jsx(Ea,{size:22,"aria-hidden":"true"}),o.jsx("strong",{children:"Accessibility permission required"}),o.jsx("small",{children:"On the Mac, allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client."})]}),Pe&&!Bu&&!qd&&o.jsxs("div",{className:"control-connection-overlay",role:"status","aria-live":"polite",children:[ne!=="error"&&o.jsx("span",{className:"control-connection-spinner","aria-hidden":"true"}),o.jsx("strong",{children:ne==="error"?"Connection failed":"Connecting"}),o.jsx("small",{children:ne==="error"?"See the notification for details. Reopen Control to retry.":El||O?"Control stream is recovering. See the notification for details.":Gu==="open"?"Preparing the first control frame":"Opening the Control stream"})]})]})}):jn==="list"?o.jsxs("div",{className:"wall-device-list",role:"grid","aria-label":"Computer status list",children:[o.jsxs("div",{className:"wall-device-list-head",role:"row",children:[o.jsx("span",{role:"columnheader",children:"Computer"}),o.jsx("span",{role:"columnheader",children:"Status"}),o.jsx("span",{role:"columnheader",children:"CPU"}),o.jsx("span",{role:"columnheader",children:"GPU"}),o.jsx("span",{role:"columnheader",children:"RAM"}),o.jsx("span",{role:"columnheader",children:"VRAM"}),o.jsx("span",{role:"columnheader",children:"Network"}),o.jsx("span",{role:"columnheader",children:"HDD"}),o.jsx("span",{role:"columnheader",children:"Temp"})]}),xl.length>0?xl.map(({device:m,slotNumber:x})=>o.jsx(bP,{device:m,slotNumber:x,selected:as.has(m.deviceId),updateIndicator:Ja(m.deviceId),remoteDiagnostics:nn?zl.get(m.deviceId):ln?pr.get(m.deviceId):void 0,diagnosticsMode:nn?"debug":"remote",onSelect:()=>ad(m.deviceId),onOpenControl:()=>ro(m.deviceId)},m.deviceId)):o.jsxs("div",{className:"wall-device-list-empty",children:[o.jsx(nr,{size:24,"aria-hidden":"true"}),o.jsx("strong",{children:"No connected computers"})]})]}):Ht?o.jsx("div",{className:`screen-wall atlas-slot-wall size-${jn}`,style:Ri,onClick:m=>{m.currentTarget===m.target&&Ol()},children:ks.map((m,x)=>m?o.jsx(ov,{device:m,frame:zo.get(m.deviceId),selected:as.has(m.deviceId),controlEnabled:!1,showStatus:sl,monitorIndex:Ls(m,Kt[m.deviceId]),monitorCount:uo(m),onSelect:()=>ad(m.deviceId),onFocusDevice:()=>nd(m.deviceId),onOpenControl:()=>ro(m.deviceId),onCycleMonitor:C=>Vo(m.deviceId,C),onCanvasReady:Wf({mode4Enabled:Ht,directMode4WallEnabled:rs,isMac:fo(m.platform)})==="direct"?Pc:Bm,sendInput:Dl,remoteModifierState:pf,updateIndicator:Ja(m.deviceId),presentationReady:Ct.autoStartLive&&da.includes(m.deviceId)?$d.has(m.deviceId):void 0,showPresentationSpinner:Ct.autoStartLive&&da.includes(m.deviceId),remoteDiagnostics:nn?zl.get(m.deviceId):ln?pr.get(m.deviceId):void 0,diagnosticsMode:nn?"debug":"remote"},m.deviceId):o.jsx(c0,{index:x},`slot-${x}`))}):o.jsx("div",{className:`screen-wall size-${jn}`,style:Ri,onClick:m=>{m.currentTarget===m.target&&Ol()},children:ks.map((m,x)=>m?o.jsx(ov,{device:m,frame:zo.get(m.deviceId),selected:as.has(m.deviceId),controlEnabled:Mr&&Oe&&Rs&&Pe?.deviceId===m.deviceId,showStatus:sl,monitorIndex:Ls(m,Kt[m.deviceId]),monitorCount:uo(m),onSelect:()=>ad(m.deviceId),onFocusDevice:()=>nd(m.deviceId),onOpenControl:()=>ro(m.deviceId),onCycleMonitor:C=>Vo(m.deviceId,C),onCanvasReady:Pc,sendInput:Dl,remoteModifierState:pf,updateIndicator:Ja(m.deviceId),presentationReady:Ct.autoStartLive&&da.includes(m.deviceId)?$d.has(m.deviceId):void 0,showPresentationSpinner:Ct.autoStartLive&&da.includes(m.deviceId),remoteDiagnostics:nn?zl.get(m.deviceId):ln?pr.get(m.deviceId):void 0,diagnosticsMode:nn?"debug":"remote"},m.deviceId):o.jsx(c0,{index:x},`slot-${x}`))}),o.jsx(SP,{visible:Ic&&!ct})]}),!Io&&o.jsxs("aside",{className:`right-dock actions-mode ${Wr?"collapsed":""}`,"aria-label":"LiveDesk tools",children:[o.jsx("button",{className:"dock-toggle",onClick:()=>gc(m=>!m),"aria-label":Wr?"Show control panel":"Hide control panel",title:Wr?"Show control panel":"Hide control panel",type:"button",children:Wr?o.jsx(M0,{size:18}):o.jsx(qv,{size:18})}),!Wr&&o.jsxs(o.Fragment,{children:[o.jsxs("section",{className:"action-dock",children:[o.jsx("input",{ref:Do,className:"hidden-file-input",type:"file",multiple:!0,onChange:m=>{m.currentTarget.files&&od(m.currentTarget.files),m.currentTarget.value=""}}),o.jsxs("div",{className:"manual-action-bar",role:"toolbar","aria-label":"Manual Client controls",children:[o.jsx(iu,{label:"Control",tooltip:Pe?Bu?"Allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client.":Mr?Rs?"Keyboard and mouse control is ready":"Waiting for the current Control capture session":"Remote control is not available on this Client":"Select a Client to use Control",onClick:()=>{if(Pe){if(ct&&Oe){We(!1),Ce("Remote control paused. Screen viewing stays on.");return}ro(Pe.deviceId)}},disabled:!Mr||!!se,active:Oe,pressed:ct&&Oe,children:o.jsx(Yf,{size:17})}),o.jsx(iu,{label:"Audio",tooltip:Pe?Qa?je?"Stop hearing this Client":"Hear this Client":"Audio is not available on this Client":"Select a Client to use Audio",onClick:()=>{qm()},disabled:!Oo||!!se,active:je,pressed:je,children:se==="audio"?o.jsx(ps,{className:"spin",size:17}):o.jsx(xg,{size:17})}),o.jsx(iu,{label:Ks?"Retry pause":Xa?"Pause video":"Resume video",tooltip:Ki.length===0?"Select one or more Clients to pause video":Ks?"Retry every selected Client whose capture shutdown is unconfirmed":Xa?`Pause video for ${ur.length} selected Client${ur.length===1?"":"s"}`:`Resume video for ${ur.length} selected Client${ur.length===1?"":"s"}`,onClick:()=>{id()},disabled:ur.length===0||!!se,active:!Xa,pressed:!Xa,children:se==="video"?o.jsx(ps,{className:"spin",size:17}):!Xa&&!Ks?o.jsx(Bb,{size:17}):o.jsx(Fb,{size:17})}),o.jsx(iu,{label:"Send files",tooltip:Yn.length===0&&!ct?"Select one or more Clients to send files":Pe?"Choose files and send them to the selected Client":"Select a Client to send files",onClick:()=>{Ce(`Choose files to send to ${Zs}.`),Do.current?.click()},disabled:!!se||!sn||(ct?!Pe:Yn.length===0),children:o.jsx(Id,{size:17})}),o.jsx(iu,{label:"Restart",tooltip:Pe?Vs?"Restart Client":"Restart is not available on this Client":"Select a Client to restart",onClick:()=>{Yc("restart")},disabled:!Pe||!sn||!!se||!Vs,children:se==="restart"?o.jsx(ps,{className:"spin",size:17}):o.jsx(dv,{size:17})}),o.jsx(iu,{label:"Sleep",tooltip:Pe?Vs?"Put Client to sleep":"Sleep is not available on this Client":"Select a Client to put to sleep",onClick:()=>{Yc("sleep")},disabled:!Pe||!sn||!!se||!Vs,children:se==="sleep"?o.jsx(ps,{className:"spin",size:17}):o.jsx(mM,{size:17})}),o.jsx(iu,{label:"Shut down",tooltip:Pe?Vs?"Shut down Client":"Shut down is not available on this Client":"Select a Client to shut down",onClick:()=>{Yc("shutdown")},disabled:!Pe||!sn||!!se||!Vs,danger:!0,children:se==="shutdown"?o.jsx(ps,{className:"spin",size:17}):o.jsx(v0,{size:17})})]})]}),o.jsx(Rx,{hubUrl:V,devices:q,variant:"dock",selectedDeviceIds:sa})]})]})]})})]}),N&&o.jsxs("nav",{className:"mobile-console-nav","aria-label":"Mobile Console pages",children:[o.jsxs("button",{className:_s?"active":"",onClick:()=>ii(m=>{const x=!m;return eP(x),x}),type:"button","aria-label":_s?"Hide computer stats":"Show computer stats","aria-pressed":_s,title:_s?"Hide CPU, GPU, RAM, and online status":"Show CPU, GPU, RAM, and online status",children:[o.jsx(pM,{size:19}),o.jsx("span",{children:"Stats"})]}),o.jsxs("button",{className:En==="wall"?"active":"",onClick:()=>Js("wall"),type:"button",children:[o.jsx(k0,{size:19}),o.jsx("span",{children:"Wall"})]}),o.jsxs("button",{className:ct?"active":"",onClick:()=>Pe&&void ro(Pe.deviceId),disabled:!Pe||!Mr,type:"button",children:[o.jsx(Yf,{size:19}),o.jsx("span",{children:"Control"})]}),o.jsxs("button",{className:rn?"active":"",onClick:()=>Js("share-files"),type:"button",children:[o.jsx(sm,{size:19}),o.jsx("span",{children:"Files"})]}),o.jsxs("button",{className:Vt?"active":"",onClick:()=>Js("agents"),type:"button",children:[o.jsx(Kp,{size:19}),o.jsx("span",{children:"Agents"})]}),o.jsxs("button",{className:Io?"active":"",onClick:()=>Js("settings"),type:"button",children:[o.jsx(rh,{size:19}),o.jsx("span",{children:"Settings"})]})]}),Ui&&o.jsxs("aside",{className:`transfer-bar state-${Ui.status}`,"aria-live":"polite",children:[o.jsx("span",{className:"transfer-bar-icon","aria-hidden":"true",children:Ui.status==="queued"?o.jsx(tr,{size:18}):Ui.status==="failed"?o.jsx(vr,{size:18}):o.jsx(y0,{size:18})}),o.jsxs("div",{className:"transfer-bar-copy",children:[o.jsx("p",{children:Ui.message}),o.jsx("div",{className:"transfer-bar-track",children:o.jsx("span",{style:{width:`${Math.max(0,Math.min(100,Ui.progress))}%`}})})]}),o.jsxs("strong",{children:[Math.max(0,Math.min(100,Ui.progress)),"%"]})]}),In&&o.jsxs("aside",{className:`livedesk-toast tone-${In.tone}`,role:In.tone==="error"?"alert":"status","aria-live":In.tone==="error"?"assertive":"polite","aria-busy":In.tone==="progress",children:[In.tone==="progress"&&o.jsx("span",{className:"livedesk-toast-spinner","aria-hidden":"true"}),o.jsx("span",{children:In.message}),o.jsx("button",{className:"livedesk-toast-close",onClick:()=>Ce(""),type:"button","aria-label":"Dismiss notification",title:"Dismiss notification",children:o.jsx(vr,{size:15})})]})]})}const kP=1e3,MP=5e3;function AP(){return typeof window>"u"?!1:(!!window.navigator.standalone||window.matchMedia("(display-mode: standalone), (display-mode: fullscreen)").matches)&&window.matchMedia("(pointer: coarse)").matches}function TP(){return typeof window>"u"?[]:[...new Set([window.location.origin,Vn].filter(Boolean))]}function NP(){const n=ih(),r=AP(),s=n||r,l=n||typeof window>"u"?Vn:window.location.origin,u=s?{role:"hub",baseUrl:l}:null,[f,h]=d.useState(u),g=d.useRef(null);return d.useEffect(()=>{if(s){h(j=>j?.role==="hub"&&j.baseUrl===l?j:{role:"hub",baseUrl:l});return}let y=!1,w=!1,b=null;const S=new AbortController,k=async()=>{for(const j of TP()){if(S.signal.aborted)return;try{const N=(await lt("/api/runtime/status",{signal:S.signal,timeoutMs:900},j)).role==="hub"?"hub":"client";w=!0,y||h(P=>P?.role===N&&P.baseUrl===j?P:{role:N,baseUrl:j});return}catch{if(S.signal.aborted)return}}},A=()=>{yu(g,k).finally(()=>{!y&&!S.signal.aborted&&(b=window.setTimeout(A,w?MP:kP))}).catch(()=>{})};A();const T=window.setTimeout(()=>{!y&&!w&&h(j=>j?.role==="client"&&j.baseUrl===Vn?j:{role:"client",baseUrl:Vn})},2500);return()=>{y=!0,S.abort(new Error("LiveDesk runtime role probe stopped.")),b!==null&&window.clearTimeout(b),window.clearTimeout(T)}},[null,s,l]),f?f.role==="client"?o.jsx(HA,{runtimeBaseUrl:f.baseUrl}):o.jsx(CP,{runtimeBaseUrl:f.baseUrl}):o.jsxs("main",{className:"runtime-role-boot","aria-busy":"true","aria-label":"Starting LiveDesk",children:[o.jsx("span",{className:"runtime-role-boot-mark","aria-hidden":"true"}),o.jsx("strong",{children:"Starting LiveDesk"}),o.jsx("p",{children:"Loading this computer's assigned role..."})]})}SM.createRoot(document.getElementById("root")).render(o.jsx(d.StrictMode,{children:o.jsx(NP,{})}));const BC="serviceWorker"in navigator&&window.isSecureContext&&window.location.protocol==="https:";let lv=null;function cv(){!BC||lv||(lv=(async()=>{await(await navigator.serviceWorker.register("/sw.js",{updateViaCache:"none"})).update();const n=await fetch(`/sw.js?pwa-release-check=${Date.now()}`,{cache:"no-store"});if(!n.ok)return;const s=(await n.text()).match(/const PWA_RELEASE = ['"](\d+\.\d+\.\d+)['"];/)?.[1],l=new URL(window.location.href);!s||!l.searchParams.has("pwa")||l.searchParams.get("pwa")===s||(l.searchParams.set("pwa",s),window.location.replace(l.toString()))})().catch(t=>{console.warn("[LiveDesk] PWA update check failed.",t)}).finally(()=>{lv=null}))}BC&&(cv(),window.addEventListener("pageshow",cv),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&cv()}));